1use std::sync::Arc;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5use std::{future::Future, pin::Pin};
6
7#[cfg(target_vendor = "apple")]
10#[path = "clock_apple.rs"]
11mod wall_timer;
12#[cfg(any(target_os = "linux", target_os = "android"))]
13#[path = "clock_linux.rs"]
14mod wall_timer;
15#[cfg(windows)]
16#[path = "clock_windows.rs"]
17mod wall_timer;
18
19pub trait Clock: Send + Sync {
24 fn now(&self) -> SystemTime;
26 fn elapsed(&self) -> Duration;
30 fn deadline(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>> {
36 Box::pin(tokio::time::sleep(duration))
37 }
38 fn wait_out(&self, wait: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>> {
43 self.deadline(wait)
44 }
45 fn sleep_until(
51 &self,
52 at: SystemTime,
53 ) -> Pin<Box<dyn Future<Output = Result<(), WallTimerError>> + Send>>;
54}
55
56#[derive(Clone, Debug, thiserror::Error)]
59pub enum WallTimerError {
60 #[error("this clock has no wall-clock timer coven can wait on")]
63 NoTimer,
64 #[error("the time is past what the system's wall timer holds")]
66 OutOfRange {
67 #[source]
70 source: Option<std::num::TryFromIntError>,
71 },
72 #[error("the system couldn't create a timer source")]
74 TimerSource,
75 #[error("the system's `{call}` failed")]
77 System {
78 call: &'static str,
80 #[source]
82 source: Arc<std::io::Error>,
83 },
84 #[error("the clock failed to wait for a wall-clock time")]
86 Clock(#[source] Arc<dyn std::error::Error + Send + Sync>),
87}
88
89impl WallTimerError {
90 pub fn clock(failure: impl std::error::Error + Send + Sync + 'static) -> Self {
92 Self::Clock(Arc::new(failure))
93 }
94
95 #[cfg(any(target_os = "linux", target_os = "android", windows))]
97 pub(crate) fn system(call: &'static str, source: impl Into<std::io::Error>) -> Self {
98 Self::System { call, source: Arc::new(source.into()) }
99 }
100}
101
102pub type ClockRef = Arc<dyn Clock>;
104
105pub struct SystemClock;
107
108impl Clock for SystemClock {
109 fn now(&self) -> SystemTime {
110 SystemTime::now()
111 }
112 fn elapsed(&self) -> Duration {
113 boot_time()
114 }
115 fn sleep_until(
120 &self,
121 at: SystemTime,
122 ) -> Pin<Box<dyn Future<Output = Result<(), WallTimerError>> + Send>> {
123 if at <= UNIX_EPOCH {
124 return Box::pin(std::future::ready(Ok(())));
125 }
126 wall_timer_sleep(at)
127 }
128}
129
130#[cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android", windows))]
131fn wall_timer_sleep(
132 at: SystemTime,
133) -> Pin<Box<dyn Future<Output = Result<(), WallTimerError>> + Send>> {
134 Box::pin(wall_timer::sleep_until(at))
135}
136
137#[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android", windows)))]
140fn wall_timer_sleep(
141 _at: SystemTime,
142) -> Pin<Box<dyn Future<Output = Result<(), WallTimerError>> + Send>> {
143 Box::pin(std::future::ready(Err(WallTimerError::NoTimer)))
144}
145
146#[cfg(any(target_os = "linux", target_os = "android"))]
148fn boot_time() -> Duration {
149 timespec(rustix::time::clock_gettime(rustix::time::ClockId::Boottime))
150}
151
152#[cfg(target_vendor = "apple")]
155fn boot_time() -> Duration {
156 timespec(rustix::time::clock_gettime(rustix::time::ClockId::Monotonic))
157}
158
159#[cfg(all(unix, not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))))]
162fn boot_time() -> Duration {
163 timespec(rustix::time::clock_gettime(rustix::time::ClockId::Monotonic))
164}
165
166#[cfg(unix)]
167fn timespec(time: rustix::time::Timespec) -> Duration {
168 Duration::new(
169 u64::try_from(time.tv_sec).expect("monotonic seconds are nonnegative"),
170 u32::try_from(time.tv_nsec).expect("nanoseconds below one second"),
171 )
172}
173
174#[cfg(windows)]
176fn boot_time() -> Duration {
177 let mut ticks = 0u64;
178 unsafe { windows_sys::Win32::System::WindowsProgramming::QueryInterruptTime(&mut ticks) };
180 Duration::from_nanos(ticks.saturating_mul(100))
181}
182
183#[cfg(any(test, feature = "test-utils"))]
191pub const HANG_GUARD: Duration = Duration::from_secs(300);
192
193#[cfg(any(test, feature = "test-utils"))]
197pub async fn within<F: Future>(future: F) -> Option<F::Output> {
198 tokio::time::timeout(HANG_GUARD, future).await.ok()
199}
200
201#[cfg(any(test, feature = "test-utils"))]
204pub fn wait_out_hang_guard() {
205 std::thread::sleep(HANG_GUARD);
206}
207
208#[cfg(feature = "test-utils")]
210pub struct FixedClock {
211 time: tokio::sync::watch::Sender<FixedTime>,
212 sleeps: tokio::sync::watch::Sender<(u64, Duration)>,
215 #[cfg(test)]
218 wall_tick: Duration,
219}
220
221#[cfg(feature = "test-utils")]
222struct FixedTime {
223 wall: SystemTime,
224 elapsed: Duration,
225}
226
227#[cfg(feature = "test-utils")]
228impl FixedClock {
229 pub fn new(now: SystemTime) -> Self {
231 Self {
232 time: tokio::sync::watch::channel(FixedTime { wall: now, elapsed: Duration::ZERO }).0,
233 sleeps: tokio::sync::watch::channel((0, Duration::ZERO)).0,
234 #[cfg(test)]
235 wall_tick: Duration::ZERO,
236 }
237 }
238
239 #[cfg(test)]
241 fn with_wall_tick(now: SystemTime, tick: Duration) -> Self {
242 Self { wall_tick: tick, ..Self::new(now) }
243 }
244
245 fn representable(&self, wall: SystemTime) -> SystemTime {
247 #[cfg(test)]
248 if !self.wall_tick.is_zero() {
249 let since = wall.duration_since(std::time::UNIX_EPOCH).expect("times follow the epoch");
250 let tick = self.wall_tick.as_nanos();
251 let nanos = since.as_nanos() / tick * tick;
252 return std::time::UNIX_EPOCH
253 + Duration::from_nanos(u64::try_from(nanos).expect("test times fit"));
254 }
255 wall
256 }
257
258 pub fn set(&self, now: SystemTime) {
260 let now = self.representable(now);
261 self.time.send_modify(|time| {
262 if let Ok(elapsed) = now.duration_since(time.wall) {
263 time.elapsed += elapsed;
264 }
265 time.wall = now;
266 });
267 }
268
269 pub fn advance(&self, by: Duration) {
274 self.time.send_modify(|time| {
275 time.elapsed += by;
276 time.wall = self.representable(time.wall + by);
277 });
278 }
279
280 pub fn sleeps_begun(&self) -> u64 {
282 self.sleeps.borrow().0
283 }
284
285 pub fn sleep_begun_after(
289 &self,
290 seen: u64,
291 ) -> impl Future<Output = (u64, Duration)> + Send + 'static {
292 let mut sleeps = self.sleeps.subscribe();
293 async move { *sleeps.wait_for(|(begun, _)| *begun > seen).await.expect("the clock is kept") }
294 }
295}
296
297#[cfg(feature = "test-utils")]
298impl Clock for FixedClock {
299 fn now(&self) -> SystemTime {
300 self.time.borrow().wall
301 }
302 fn elapsed(&self) -> Duration {
304 self.time.borrow().elapsed
305 }
306 fn deadline(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send>> {
307 let mut time = self.time.subscribe();
308 let deadline = time.borrow().elapsed + duration;
309 self.sleeps.send_modify(|(begun, latest)| {
310 *begun += 1;
311 *latest = deadline;
312 });
313 Box::pin(async move {
314 time.wait_for(|time| time.elapsed >= deadline)
315 .await
316 .expect("clock owner retains its sender");
317 })
318 }
319 fn sleep_until(
322 &self,
323 at: SystemTime,
324 ) -> Pin<Box<dyn Future<Output = Result<(), WallTimerError>> + Send>> {
325 let mut time = self.time.subscribe();
326 Box::pin(async move {
327 time.wait_for(|time| time.wall >= at).await.expect("clock owner retains its sender");
328 Ok(())
329 })
330 }
331}
332
333#[cfg(feature = "test-utils")]
334#[path = "clock_polling.rs"]
335mod polling;
336#[cfg(feature = "test-utils")]
337pub use polling::PollingClock;
338
339#[cfg(feature = "test-utils")]
341pub struct ClosureClock<F>(
342 pub F,
344);
345
346#[cfg(feature = "test-utils")]
347impl<F: Fn() -> SystemTime + Send + Sync> Clock for ClosureClock<F> {
348 fn now(&self) -> SystemTime {
349 (self.0)()
350 }
351 fn elapsed(&self) -> Duration {
353 Duration::ZERO
354 }
355 fn sleep_until(
357 &self,
358 _at: SystemTime,
359 ) -> Pin<Box<dyn Future<Output = Result<(), WallTimerError>> + Send>> {
360 Box::pin(std::future::ready(Err(WallTimerError::NoTimer)))
361 }
362}
363
364#[cfg(test)]
367static RELEASED: std::sync::Mutex<Vec<(SystemTime, tokio::sync::oneshot::Sender<()>)>> =
368 std::sync::Mutex::new(Vec::new());
369
370#[cfg(test)]
373fn when_released(at: SystemTime) -> tokio::sync::oneshot::Receiver<()> {
374 let (told, telling) = tokio::sync::oneshot::channel();
375 crate::locks::lock_unpoisoned(&RELEASED).push((at, told));
376 telling
377}
378
379#[cfg(all(
382 test,
383 any(target_vendor = "apple", target_os = "linux", target_os = "android", windows)
384))]
385fn released(at: SystemTime) {
386 let mut watched = crate::locks::lock_unpoisoned(&RELEASED);
387 let (found, rest): (Vec<_>, Vec<_>) =
388 std::mem::take(&mut *watched).into_iter().partition(|(watched, _)| *watched == at);
389 *watched = rest;
390 for (_, told) in found {
391 #[expect(
392 clippy::let_underscore_must_use,
393 reason = "a test that stopped listening has no use for it"
394 )]
395 let _ = told.send(());
396 }
397}
398
399#[cfg(all(test, any(target_os = "linux", target_os = "android", windows)))]
401struct ReleasedOnDrop(SystemTime);
402
403#[cfg(all(test, any(target_os = "linux", target_os = "android", windows)))]
404impl Drop for ReleasedOnDrop {
405 fn drop(&mut self) {
406 released(self.0);
407 }
408}
409
410#[cfg(test)]
411#[path = "clock_tests.rs"]
412mod tests;