diff --git a/Cargo.lock b/Cargo.lock index 55b5100ae98..97349852351 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4518,6 +4518,7 @@ dependencies = [ "futures", "hang", "kio 0.6.2", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -5156,6 +5157,7 @@ dependencies = [ "futures", "hang", "hmac 0.13.0", + "moq-clock", "moq-mux", "moq-net", "moq-tokio", diff --git a/quest/m1/time/crates.md b/quest/m1/time/crates.md index b33500e9200..30cfebf1228 100644 --- a/quest/m1/time/crates.md +++ b/quest/m1/time/crates.md @@ -34,6 +34,13 @@ Split the PR by crate group if review needs it; ban direct clock reads in each production scope as it finishes. Unrelated legacy test conversions and the workspace-wide lint ratchet follow in m2. +The current checkpoint migrates auth clock reads, RTMP session timestamps and +deadlines, archive retention, and listener stall accounting. The rest of the +workspace and public `SystemTime` fields still need migration. In particular, +SRT and WebRTC hand instants to third-party APIs on std's clock, and audio/video +device threads block outside an async runtime; those boundaries still need +clock support rather than a second host-clock read at each call site. + Public API: breaking wherever a crate exposes an instant or a time source. Wire: none. diff --git a/rs/moq-archive/Cargo.toml b/rs/moq-archive/Cargo.toml index 11847c512ff..3a9ad66bc6e 100644 --- a/rs/moq-archive/Cargo.toml +++ b/rs/moq-archive/Cargo.toml @@ -17,6 +17,7 @@ bytes = { workspace = true } futures = { workspace = true } hang = { workspace = true } kio = { workspace = true } +moq-clock = { workspace = true } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } diff --git a/rs/moq-archive/benches/writer.rs b/rs/moq-archive/benches/writer.rs index 8df214a4848..d342d9b7c1f 100644 --- a/rs/moq-archive/benches/writer.rs +++ b/rs/moq-archive/benches/writer.rs @@ -1,3 +1,6 @@ +// Host time measures benchmark throughput. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] + //! `Writer::run` recording every enrolled track into memory, swept over the number of tracks and //! the groups each one publishes. Throughput is per frame, so a per-event cost that grows with the //! track table shows up as a slope across the track counts. diff --git a/rs/moq-archive/clippy.toml b/rs/moq-archive/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-archive/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-archive/src/lib.rs b/rs/moq-archive/src/lib.rs index d1bc87a73c9..07aa606b8d8 100644 --- a/rs/moq-archive/src/lib.rs +++ b/rs/moq-archive/src/lib.rs @@ -21,6 +21,7 @@ pub mod info; mod mock; mod path; #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod proof; pub mod reader; mod recover; diff --git a/rs/moq-archive/src/reader/mod.rs b/rs/moq-archive/src/reader/mod.rs index 17b899d98e8..24649e51c44 100644 --- a/rs/moq-archive/src/reader/mod.rs +++ b/rs/moq-archive/src/reader/mod.rs @@ -658,4 +658,5 @@ impl quick_cache::Weighter> for Weight { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests; diff --git a/rs/moq-archive/src/writer.rs b/rs/moq-archive/src/writer.rs index 3d55b7e132f..013d5cc8e62 100644 --- a/rs/moq-archive/src/writer.rs +++ b/rs/moq-archive/src/writer.rs @@ -40,11 +40,11 @@ use futures::future::BoxFuture; use futures::stream::FuturesUnordered; use futures::{FutureExt, StreamExt}; use hang::timeline::{Position, Record}; +use moq_clock::Instant; use moq_mux::timeline::{self, Segmenter}; use moq_net::{Timescale, Timestamp, broadcast, group, track}; use object_store::ObjectStore; use tokio::sync::{mpsc, watch}; -use tokio::time::Instant; use crate::recover::{Resume, checkpoint, recover}; use crate::segment::{Frame, Group, Object}; @@ -318,7 +318,7 @@ impl Writer { _ = source.closed(), if !closed => closed = true, // Also once commands closed: an enrollment in flight still settles its count. _ = enrolling.changed(), if idle => {} - _ = tokio::time::sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() => { + _ = moq_clock::sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() => { let (_, expired) = deletions.pop_front().unwrap(); delete(&shared.store, &mut pruned, expired).await; } @@ -328,7 +328,7 @@ impl Writer { // Complete expirations already committed to the timelines; nothing new expires after the // final records. for (deadline, expired) in deletions { - tokio::time::sleep_until(deadline).await; + moq_clock::sleep_until(deadline).await; delete(&shared.store, &mut pruned, expired).await; } @@ -1048,6 +1048,7 @@ fn recorded_end(resume: &Resume, timescale: Option) -> Result Driver { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use moq_pattern::Patterns; @@ -545,6 +547,19 @@ mod tests { } } + #[tokio::test(start_paused = true)] + async fn session_duration_uses_the_lease_clock() { + let log = Log::default(); + let script = Script::new(log.clone(), |_| Some(Ok(grant(None, None)))); + let consumer = script.connect().await.unwrap(); + tokio::time::advance(Duration::from_secs(60)).await; + consumer.close("done", Bytes::default()); + match log.end().await.event { + Event::End { duration, .. } => assert_eq!(duration, Duration::from_secs(60)), + other => panic!("expected connection end, got {other:?}"), + } + } + #[tokio::test] async fn an_attached_lease_never_reports_the_connection_end() { let log = Log::default(); diff --git a/rs/moq-auth/src/key.rs b/rs/moq-auth/src/key.rs index 30a56d69901..5aed9b78601 100644 --- a/rs/moq-auth/src/key.rs +++ b/rs/moq-auth/src/key.rs @@ -555,7 +555,7 @@ impl Key { /// [`Claims::authorize`]. pub fn verify(&self, token: &str) -> crate::Result { let claims: Claims = self.decode(token)?; - validate_times(&claims, std::time::SystemTime::now())?; + validate_times(&claims, moq_clock::wall().into())?; claims.validate()?; self.validate_scope(&claims)?; Ok(claims) @@ -675,6 +675,7 @@ where } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; @@ -1105,6 +1106,18 @@ mod tests { assert!(result.is_err()); } + #[moq_clock::test] + async fn token_validity_uses_the_ambient_wall() { + let key = create_test_key(); + let mut claims = create_test_claims(); + claims.issued = Some(moq_clock::wall().into()); + claims.expires = Some((moq_clock::wall() + Duration::from_secs(10)).into()); + let token = key.sign(&claims).unwrap(); + key.verify(&token).unwrap(); + moq_clock::sleep(Duration::from_secs(10)).await; + assert!(matches!(key.verify(&token), Err(crate::Error::TokenExpired))); + } + #[test] fn test_key_verify_token_without_exp() { let key = create_test_key(); diff --git a/rs/moq-auth/src/lease.rs b/rs/moq-auth/src/lease.rs index 5b93c3d80d0..96127c501e3 100644 --- a/rs/moq-auth/src/lease.rs +++ b/rs/moq-auth/src/lease.rs @@ -434,6 +434,7 @@ fn ready_if(condition: bool) -> Poll<()> { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use std::future::Future; diff --git a/rs/moq-auth/src/serve.rs b/rs/moq-auth/src/serve.rs index bbda75dcacc..de6aab586d2 100644 --- a/rs/moq-auth/src/serve.rs +++ b/rs/moq-auth/src/serve.rs @@ -18,7 +18,7 @@ use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::routing::post; use axum::{Json, Router}; -use tokio::time::Instant; +use moq_clock::Instant; use crate::{Event, Grant, Key, KeyId, KeySet, Permissions, Request, Token}; @@ -167,7 +167,11 @@ impl Policy { let mut grant = Grant::new(permissions.publish, permissions.subscribe); grant.expires = match (expires, self.expires) { (Some(expires), _) => Some(expires), - (None, Some(bound)) => Some(SystemTime::now().checked_add(bound).ok_or(Refusal::ExpiresOutOfRange)?), + (None, Some(bound)) => Some( + SystemTime::from(moq_clock::wall()) + .checked_add(bound) + .ok_or(Refusal::ExpiresOutOfRange)?, + ), (None, None) => None, }; grant.revalidate = self.revalidate; @@ -362,7 +366,7 @@ impl Server { } if policy .expires - .is_some_and(|bound| SystemTime::now().checked_add(bound).is_none()) + .is_some_and(|bound| SystemTime::from(moq_clock::wall()).checked_add(bound).is_none()) { return Err(crate::Error::ExpiresOutOfRange); } @@ -443,6 +447,7 @@ async fn handle(State(server): State, Json(request): Json) -> R } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use crate::{Algorithm, Bytes, Claims, Client, Error, Peer, Transport, lease::Reason}; @@ -462,6 +467,20 @@ mod tests { request } + #[moq_clock::test] + async fn default_expiry_uses_the_ambient_wall() { + let policy = Policy { + public: rules(&["**"], &[]), + expires: Some(Duration::from_secs(30)), + ..Default::default() + }; + let grant = policy.decide(&request("/demo")).await.unwrap(); + assert_eq!( + grant.expires, + Some((moq_clock::wall() + Duration::from_secs(30)).into()) + ); + } + fn with_token(mut request: Request, jwt: &str) -> Request { request.query = Some(format!("jwt={jwt}")); request diff --git a/rs/moq-auth/src/set.rs b/rs/moq-auth/src/set.rs index 48e4db1a4b5..9812f7063ab 100644 --- a/rs/moq-auth/src/set.rs +++ b/rs/moq-auth/src/set.rs @@ -131,6 +131,7 @@ impl KeySet { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-rtmp/Cargo.toml b/rs/moq-rtmp/Cargo.toml index 513f1035698..21b1416b9ff 100644 --- a/rs/moq-rtmp/Cargo.toml +++ b/rs/moq-rtmp/Cargo.toml @@ -35,6 +35,7 @@ bytes = { workspace = true } futures = { workspace = true } hang = { workspace = true } hmac = "0.13" +moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } rand = { workspace = true } @@ -54,6 +55,7 @@ tracing = { workspace = true } [dev-dependencies] criterion = { workspace = true } +moq-clock = { path = "../moq-clock", features = ["sim"] } # The RTMPS test borrows moq-tokio's self-signed cert generation to build a # `rustls::ServerConfig`. No transport feature: a QUIC backend here would be # unified into every other crate a `--workspace` build selects, which is exactly diff --git a/rs/moq-rtmp/clippy.toml b/rs/moq-rtmp/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-rtmp/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-rtmp/src/dial.rs b/rs/moq-rtmp/src/dial.rs index df737f0da8f..e534d7b2f16 100644 --- a/rs/moq-rtmp/src/dial.rs +++ b/rs/moq-rtmp/src/dial.rs @@ -554,6 +554,7 @@ impl Publisher { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::time::Duration; diff --git a/rs/moq-rtmp/src/rml/mod.rs b/rs/moq-rtmp/src/rml/mod.rs index 5aa003d1876..eb567a11212 100644 --- a/rs/moq-rtmp/src/rml/mod.rs +++ b/rs/moq-rtmp/src/rml/mod.rs @@ -22,6 +22,7 @@ #![allow(clippy::pedantic)] #![allow(clippy::nursery)] #![allow(rustdoc::all)] +#![deny(clippy::disallowed_methods, clippy::disallowed_types)] pub mod amf0; diff --git a/rs/moq-rtmp/src/rml/sessions/client/mod.rs b/rs/moq-rtmp/src/rml/sessions/client/mod.rs index 742fc2510e5..556afbb050e 100644 --- a/rs/moq-rtmp/src/rml/sessions/client/mod.rs +++ b/rs/moq-rtmp/src/rml/sessions/client/mod.rs @@ -23,9 +23,9 @@ use crate::rml::messages::{RtmpMessage, UserControlEventType}; use crate::rml::sessions::StreamMetadata; use crate::rml::time::RtmpTimestamp; use bytes::Bytes; +use moq_clock::Instant; use std::collections::HashMap; use std::mem; -use std::time::SystemTime; type ClientResult = Result, ClientSessionError>; @@ -50,7 +50,7 @@ type ClientResult = Result, ClientSessionError>; /// Any violation of these points have a high probability of causing RTMP chunk parsing errors /// by either the `ClientSession` or the peer. pub struct ClientSession { - start_time: SystemTime, + start_time: Instant, serializer: ChunkSerializer, deserializer: ChunkDeserializer, config: ClientSessionConfig, @@ -72,7 +72,7 @@ impl ClientSession { /// such as setting the outbound chunk size pub fn new(config: ClientSessionConfig) -> Result<(ClientSession, Vec), ClientSessionError> { let session = ClientSession { - start_time: SystemTime::now(), + start_time: Instant::now(), serializer: ChunkSerializer::new(), deserializer: ChunkDeserializer::new(), next_transaction_id: 1, @@ -889,17 +889,8 @@ impl ClientSession { } fn get_epoch(&self) -> RtmpTimestamp { - match self.start_time.elapsed() { - Ok(duration) => { - let milliseconds = (duration.as_secs() * 1000) + (duration.subsec_nanos() as u64 / 1_000_000); - - // Casting to u32 should auto-wrap the value as expected. If not a stream will probably - // break after 49 days but testing shows it should wrap - RtmpTimestamp::new(milliseconds as u32) - } - - Err(_) => RtmpTimestamp::new(0), // Time went backwards, so just consider time as at epoch - } + // RTMP timestamps wrap every 2^32 milliseconds. + RtmpTimestamp::new(self.start_time.elapsed().as_millis() as u32) } fn get_next_transaction_id(&mut self) -> u32 { @@ -908,3 +899,19 @@ impl ClientSession { transaction_id } } + +#[cfg(test)] +mod clock_tests { + use super::*; + + #[moq_clock::test] + async fn session_epoch_uses_the_timer_clock() { + let (session, _) = ClientSession::new(ClientSessionConfig::new()).unwrap(); + moq_clock::sleep(std::time::Duration::from_millis(12_345)).await; + assert_eq!(session.get_epoch(), RtmpTimestamp::new(12_345)); + moq_clock::sim::step_wall(moq_clock::Wall::UNIX_EPOCH); + assert_eq!(session.get_epoch(), RtmpTimestamp::new(12_345)); + moq_clock::sleep(std::time::Duration::from_millis(1 << 32)).await; + assert_eq!(session.get_epoch(), RtmpTimestamp::new(12_345)); + } +} diff --git a/rs/moq-rtmp/src/rml/sessions/server/mod.rs b/rs/moq-rtmp/src/rml/sessions/server/mod.rs index 6247df23ffc..0f307022444 100644 --- a/rs/moq-rtmp/src/rml/sessions/server/mod.rs +++ b/rs/moq-rtmp/src/rml/sessions/server/mod.rs @@ -19,8 +19,8 @@ use crate::rml::messages::{PeerBandwidthLimitType, RtmpMessage, UserControlEvent use crate::rml::sessions::StreamMetadata; use crate::rml::time::RtmpTimestamp; use bytes::Bytes; +use moq_clock::Instant; use std::collections::HashMap; -use std::time::SystemTime; const FOURCC_CAN_DECODE: u32 = 0x01; @@ -48,7 +48,7 @@ pub use self::result::ServerSessionResult; /// high probability of causing RTMP chunk parsing errors by the peer or by the `ServerSession` /// instance itself. pub struct ServerSession { - start_time: SystemTime, + start_time: Instant, serializer: ChunkSerializer, deserializer: ChunkDeserializer, connected_app_name: Option, @@ -73,7 +73,7 @@ impl ServerSession { /// stream id 0 (as well as other important initial information pub fn new(config: ServerSessionConfig) -> Result<(ServerSession, Vec), ServerSessionError> { let mut session = ServerSession { - start_time: SystemTime::now(), + start_time: Instant::now(), serializer: ChunkSerializer::new(), deserializer: ChunkDeserializer::new(), connected_app_name: None, @@ -1360,17 +1360,8 @@ impl ServerSession { } fn get_epoch(&self) -> RtmpTimestamp { - match self.start_time.elapsed() { - Ok(duration) => { - let milliseconds = (duration.as_secs() * 1000) + (duration.subsec_nanos() as u64 / 1_000_000); - - // Casting to u32 should auto-wrap the value as expected. If not a stream will probably - // break after 49 days but testing shows it should wrap - RtmpTimestamp::new(milliseconds as u32) - } - - Err(_) => RtmpTimestamp::new(0), // Time went backwards, so just consider time as at epoch - } + // RTMP timestamps wrap every 2^32 milliseconds. + RtmpTimestamp::new(self.start_time.elapsed().as_millis() as u32) } fn create_error_packet( @@ -1401,3 +1392,19 @@ fn create_status_object(level: &str, code: &str, description: &str) -> HashMap, + accept_retry: Option, } impl Server { @@ -355,7 +355,7 @@ impl Server { self.pending.push(Box::pin(async move { // The TLS handshake (if any) and the RTMP handshake share one // budget, so a client that stalls either is dropped. - let outcome = tokio::time::timeout(REQUEST_TIMEOUT, async move { + let outcome = moq_clock::timeout(REQUEST_TIMEOUT, async move { #[cfg(feature = "tls")] let conn = match tls { Some(acceptor) if starts_tls(&stream).await? => Conn::Tls(Box::new( @@ -402,7 +402,7 @@ impl Server { tracing::warn!(%err, "failed to accept RTMP connection; continuing"); let wait = self.accept_delay.mul_f64(0.5 + rand::rng().random::() / 2.0); self.accept_delay = (self.accept_delay * 2).min(ACCEPT_RETRY_MAX); - self.accept_retry = Some(tokio::time::Instant::now() + wait); + self.accept_retry = Some(moq_clock::Instant::now() + wait); } }, } @@ -429,9 +429,9 @@ async fn starts_tls(stream: &TcpStream) -> io::Result { /// /// The `select!` arm that uses this is guarded on `at` being set; the pending branch keeps the arm /// well-formed rather than leaving the macro with a `None` to unwrap. -async fn sleep_until(at: Option) { +async fn sleep_until(at: Option) { match at { - Some(at) => tokio::time::sleep_until(at).await, + Some(at) => moq_clock::sleep_until(at).await, None => std::future::pending().await, } } @@ -471,7 +471,7 @@ pub fn configure_socket(stream: &TcpStream, peer: SocketAddr) { /// /// Returns `Ok(None)` if the client disconnects before issuing `publish` or /// `play`. Unlike [`Server`], this applies no timeout: wrap the call in -/// [`tokio::time::timeout`] to bound how long a connected-but-idle client can +/// [`moq_clock::timeout`] to bound how long a connected-but-idle client can /// hold the task. pub async fn accept_stream(stream: S, peer: SocketAddr) -> Result>> { Ok(accept_until_request(stream, peer).await?) @@ -773,7 +773,7 @@ impl Play { tracing::debug!(peer = %self.peer, %path, "viewer disconnected before play started"); return Ok(()); } - resolved = tokio::time::timeout(PLAY_RESOLVE_TIMEOUT, origin.routed_broadcast(&path)) => { + resolved = moq_clock::timeout(PLAY_RESOLVE_TIMEOUT, origin.routed_broadcast(&path)) => { match resolved { Ok(resolved) => resolved, Err(_) => { @@ -800,7 +800,7 @@ impl Play { tracing::debug!(peer = %self.peer, %path, "viewer disconnected before play started"); return Ok(()); } - catalog = tokio::time::timeout(PLAY_RESOLVE_TIMEOUT, CatalogStream::next(&mut check)) => { + catalog = moq_clock::timeout(PLAY_RESOLVE_TIMEOUT, CatalogStream::next(&mut check)) => { match catalog { Ok(Ok(Some(catalog))) => catalog, Ok(Ok(None)) => { @@ -848,7 +848,7 @@ impl Play { tracing::debug!(peer = %self.peer, %path, "viewer disconnected before play started"); return Ok(()); } - chunk = tokio::time::timeout(PLAY_RESOLVE_TIMEOUT, export.next()) => { + chunk = moq_clock::timeout(PLAY_RESOLVE_TIMEOUT, export.next()) => { match chunk { Ok(Ok(Some(chunk))) => chunk, Ok(Ok(None)) => { @@ -1196,7 +1196,7 @@ async fn pump( peer: SocketAddr, ) -> anyhow::Result<()> { let mut buffer = [0u8; READ_BUFFER]; - let mut media_deadline = tokio::time::Instant::now() + PUBLISH_IDLE_TIMEOUT; + let mut media_deadline = moq_clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; loop { let mut finished = false; while let Some(result) = work.pop_front() { @@ -1209,13 +1209,13 @@ async fn pump( // consumes whole tags atomically, so one bad frame doesn't desync // the stream, and tearing down a live publish over it would be worse. ServerSessionEvent::AudioDataReceived { data, timestamp, .. } => { - media_deadline = tokio::time::Instant::now() + PUBLISH_IDLE_TIMEOUT; + media_deadline = moq_clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; if let Err(err) = publisher.push(flv::TAG_AUDIO, timestamp.value, &data) { tracing::warn!(%peer, %err, "dropping RTMP audio frame that failed to demux"); } } ServerSessionEvent::VideoDataReceived { data, timestamp, .. } => { - media_deadline = tokio::time::Instant::now() + PUBLISH_IDLE_TIMEOUT; + media_deadline = moq_clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; if let Err(err) = publisher.push(flv::TAG_VIDEO, timestamp.value, &data) { tracing::warn!(%peer, %err, "dropping RTMP video frame that failed to demux"); } @@ -1238,7 +1238,7 @@ async fn pump( let n = tokio::select! { res = stream.read(&mut buffer) => res?, - _ = tokio::time::sleep_until(media_deadline) => { + _ = moq_clock::sleep_until(media_deadline) => { anyhow::bail!("peer {peer} sent no RTMP media for {:?}", PUBLISH_IDLE_TIMEOUT); } }; @@ -1508,6 +1508,7 @@ impl Publisher { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; #[tokio::test(start_paused = true)] diff --git a/rs/moq-tokio/Cargo.toml b/rs/moq-tokio/Cargo.toml index 453b0f4e90e..dc386ff27cd 100644 --- a/rs/moq-tokio/Cargo.toml +++ b/rs/moq-tokio/Cargo.toml @@ -19,7 +19,6 @@ quic = [ "_transport", "_certs", "dep:moq-quic", - "dep:moq-clock", "dep:http", "dep:kio", "dep:pin-project-lite", @@ -78,7 +77,7 @@ if-addrs = { workspace = true, optional = true } kio = { workspace = true, optional = true } mdns-sd = { workspace = true, optional = true } -moq-clock = { workspace = true, optional = true } +moq-clock = { workspace = true } # The ICE agent behind the `webrtc` module. Private, like str0m: neither appears in this crate's API. moq-ice = { workspace = true, optional = true } moq-net = { workspace = true } @@ -143,6 +142,7 @@ chrono = "0.4" # Use the channel type behind `mdns_sd::Receiver` so the mDNS readiness gate can # be driven with synthetic daemon events. flume = "0.12" +moq-clock = { path = "../moq-clock", features = ["sim"] } rcgen = { workspace = true, features = ["pem", "aws_lc_rs"] } # rustls without a provider, as iroh builds it, so the default test build covers an # `http://` dial's certificate fetch with no process default installed. diff --git a/rs/moq-tokio/src/accept.rs b/rs/moq-tokio/src/accept.rs index ffd280de6bf..cd53c208c58 100644 --- a/rs/moq-tokio/src/accept.rs +++ b/rs/moq-tokio/src/accept.rs @@ -29,9 +29,11 @@ use std::{ Arc, Mutex, atomic::{AtomicU64, Ordering}, }, - time::{Duration, Instant}, + time::Duration, }; +use moq_clock::Instant; + /// Delay after an accept failure that is not one connection's fault, escalating /// while they continue and reset by the next successful accept. /// @@ -466,4 +468,13 @@ mod tests { // episode has to see, since the process could not answer one during it. assert_eq!(health.failures(Failure::Exhausted), 6); } + + #[cfg(unix)] + #[moq_clock::test] + async fn exhaustion_stall_uses_the_retry_clock() { + let health = Health::new("test"); + let _ = health.failed(&io(libc::EMFILE)); + moq_clock::sleep(Duration::from_secs(30)).await; + assert_eq!(health.stalled(), Some(Duration::from_secs(30))); + } }