Skip to main content

tilo_clock/
lib.rs

1//! Reading the time the same way on every target: [`now`] and [`wall`] are the
2//! sanctioned monotonic and wall-clock reads, and [`time`] names the clock types
3//! instead of `std::time`'s, which panic in a browser page. [`Clock`] is an
4//! injectable time source, for deadline behaviour a test reaches without sleeping.
5
6use std::sync::OnceLock;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use time::{Duration, Instant, SystemTime, UNIX_EPOCH};
10
11/// The clock under one module path: the types under `std::time`'s names, for signatures that
12/// need one, and every reading, made through [`now`] and [`wall`]. The UI toolkit and the process
13/// services name the clock through this module and never `std::time`, so a process whose clock
14/// must be virtualised (a deterministic replay, a test) has one boundary to provide.
15pub mod time {
16    pub use crate::imp::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
17    /// A clock held at one wall time; tilo-clock's own tests hold it per thread instead.
18    #[cfg(not(test))]
19    pub use crate::pin_wall;
20    pub use crate::{
21        from_std, now, to_std, try_unix_now, try_unix_now_ms, try_unix_now_ns, unix_now,
22        unix_now_i64, unix_now_ms, unix_now_ms_i64, unix_now_ns, wall, wall_frozen,
23    };
24
25    /// A file-system timestamp, as `std::fs::Metadata::modified` reports it, as a [`SystemTime`].
26    pub use crate::from_std as from_file_time;
27
28    /// Scoped clock readings used by production-path input and deadline tests.
29    #[cfg(any(test, feature = "test-support"))]
30    pub use crate::testing;
31}
32
33#[cfg(any(not(target_family = "wasm"), tilo_no_js))]
34mod imp {
35    pub use std::time::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
36
37    #[inline]
38    pub const fn to_std(time: SystemTime) -> std::time::SystemTime {
39        time
40    }
41
42    #[inline]
43    pub const fn from_std(time: std::time::SystemTime) -> SystemTime {
44        time
45    }
46}
47
48#[cfg(all(target_family = "wasm", not(tilo_no_js)))]
49mod imp {
50    pub use web_time::{Duration, Instant, SystemTime, SystemTimeError, UNIX_EPOCH};
51
52    pub fn to_std(time: SystemTime) -> std::time::SystemTime {
53        let converted = match time.duration_since(UNIX_EPOCH) {
54            Ok(after) => std::time::UNIX_EPOCH.checked_add(after),
55            Err(before) => std::time::UNIX_EPOCH.checked_sub(before.duration()),
56        };
57        converted.unwrap_or(std::time::UNIX_EPOCH)
58    }
59
60    pub fn from_std(time: std::time::SystemTime) -> SystemTime {
61        let converted = match time.duration_since(std::time::UNIX_EPOCH) {
62            Ok(after) => UNIX_EPOCH.checked_add(after),
63            Err(before) => UNIX_EPOCH.checked_sub(before.duration()),
64        };
65        converted.unwrap_or(UNIX_EPOCH)
66    }
67}
68
69// The page's lint pass bans std's clocks (tools/ci/wasm_clippy_conf.py), and this crate is the
70// one place a build that is not the page reads them: in a page, `Instant` and `SystemTime` are
71// `web_time`'s.
72#[allow(
73    clippy::disallowed_methods,
74    reason = "off the page this crate is where std's monotonic clock is read"
75)]
76#[must_use]
77#[inline]
78pub fn now() -> Instant {
79    #[cfg(any(test, feature = "test-support"))]
80    if let Some(at) = testing::monotonic_override() {
81        return at;
82    }
83    Instant::now()
84}
85
86#[cfg(any(test, feature = "test-support"))]
87pub mod testing {
88    use super::time::{Instant, SystemTime};
89    use std::cell::Cell;
90
91    thread_local! {
92        static MONOTONIC: Cell<Option<Instant>> = const { Cell::new(None) };
93    }
94
95    pub(super) fn monotonic_override() -> Option<Instant> {
96        MONOTONIC.with(Cell::get)
97    }
98
99    struct Restore(Option<Instant>);
100
101    impl Drop for Restore {
102        fn drop(&mut self) {
103            MONOTONIC.with(|clock| clock.set(self.0));
104        }
105    }
106
107    pub fn with_monotonic_time<T>(at: Instant, operation: impl FnOnce() -> T) -> T {
108        let _restore = Restore(MONOTONIC.with(|clock| clock.replace(Some(at))));
109        operation()
110    }
111
112    struct RestoreWall(Option<u64>);
113
114    impl Drop for RestoreWall {
115        fn drop(&mut self) {
116            super::FROZEN_HERE_MS.with(|here| here.set(self.0));
117        }
118    }
119
120    /// A test's right to pin its process's wall clock: only
121    /// `tilo_test_env::in_own_process` gives one, and `policy/ui-clock-contract`
122    /// refuses [`hold_wall_everywhere`] elsewhere.
123    #[derive(Clone, Copy)]
124    pub struct OwnProcess(());
125
126    impl OwnProcess {
127        #[doc(hidden)]
128        #[must_use]
129        pub const fn of_a_test_in_its_own_process() -> Self {
130            Self(())
131        }
132    }
133
134    /// A process-wide wall-clock pin, back to the real clock when it drops.
135    pub struct WallHold {
136        _process: OwnProcess,
137        pinned: std::sync::Arc<super::AtomicU64>,
138        replaced: Option<std::sync::Arc<super::AtomicU64>>,
139    }
140
141    impl Drop for WallHold {
142        fn drop(&mut self) {
143            let mut process = super::PROCESS
144                .lock()
145                .unwrap_or_else(std::sync::PoisonError::into_inner);
146            if process
147                .as_ref()
148                .is_some_and(|pin| std::sync::Arc::ptr_eq(pin, &self.pinned))
149            {
150                *process = self.replaced.take();
151            }
152        }
153    }
154
155    /// Pin the wall clock of `process` to `at` until the test ends; every
156    /// thread reads `at`.
157    pub fn hold_wall_everywhere(process: OwnProcess, at: SystemTime) -> WallHold {
158        let pinned = std::sync::Arc::new(super::AtomicU64::new(super::wall_ms(at)));
159        // A second pin takes over from the first.
160        let replaced = super::PROCESS
161            .lock()
162            .unwrap_or_else(std::sync::PoisonError::into_inner)
163            .replace(pinned.clone());
164        WallHold {
165            _process: process,
166            pinned,
167            replaced,
168        }
169    }
170
171    thread_local! {
172        static FOLLOWED: std::cell::RefCell<Option<std::sync::Arc<std::sync::atomic::AtomicU64>>> =
173            const { std::cell::RefCell::new(None) };
174    }
175
176    pub(super) fn followed_ms() -> u64 {
177        FOLLOWED.with(|followed| {
178            followed
179                .borrow()
180                .as_ref()
181                .map_or(0, |wall| wall.load(std::sync::atomic::Ordering::Relaxed))
182        })
183    }
184
185    /// A wall clock a test pins for the threads it owns; threads that follow
186    /// none keep their own.
187    #[derive(Clone, Debug, Default)]
188    pub struct SharedWall(std::sync::Arc<std::sync::atomic::AtomicU64>);
189
190    impl SharedWall {
191        /// This thread reads the pinned time from now on, until
192        /// [`Self::release`].
193        pub fn follow(&self) {
194            FOLLOWED.with(|followed| *followed.borrow_mut() = Some(self.0.clone()));
195        }
196
197        pub fn pin(&self, at: SystemTime) {
198            self.0
199                .store(super::wall_ms(at), std::sync::atomic::Ordering::Relaxed);
200        }
201
202        pub fn release(&self) {
203            self.0.store(0, std::sync::atomic::Ordering::Relaxed);
204        }
205    }
206
207    /// Pin the wall clock of this thread alone to `at`: the other tests of the
208    /// process and a runtime's workers keep their own clock.
209    pub fn with_wall<T>(at: SystemTime, operation: impl FnOnce() -> T) -> T {
210        let ms = super::wall_ms(at);
211        let _restore = RestoreWall(super::FROZEN_HERE_MS.with(|here| here.replace(Some(ms))));
212        operation()
213    }
214}
215
216#[cfg(test)]
217mod scoped_monotonic_tests {
218    use super::*;
219
220    tilo_test_env::scenario! {
221        fn a_held_clock_is_the_holding_threads_alone_and_ends_with_its_scope;
222
223        phase a_shared_wall_pins_the_threads_following_it_until_released;
224        {
225            const PINNED: u64 = 123_456;
226            let wall = testing::SharedWall::default();
227            let follower = {
228                let wall = wall.clone();
229                move || {
230                    wall.follow();
231                    unix_now()
232                }
233            };
234            assert_ne!(std::thread::spawn(follower.clone()).join().unwrap(), PINNED);
235            wall.pin(UNIX_EPOCH + Duration::from_secs(PINNED));
236            assert_eq!(std::thread::spawn(follower.clone()).join().unwrap(), PINNED);
237            assert_ne!(
238                unix_now(),
239                PINNED,
240                "a thread following none keeps its clock"
241            );
242            wall.release();
243            assert_ne!(std::thread::spawn(follower).join().unwrap(), PINNED);
244        }
245
246        phase scoped_time_is_thread_local_nested_and_restored_after_unwind;
247        {
248            let at = now().checked_add(Duration::from_secs(60)).unwrap();
249            testing::with_monotonic_time(at, || {
250                assert_eq!(now(), at);
251                let later = at.checked_add(Duration::from_secs(1)).unwrap();
252                testing::with_monotonic_time(later, || assert_eq!(now(), later));
253                assert_eq!(now(), at);
254                assert!(std::thread::spawn(now).join().unwrap() < at);
255                let panicked = std::panic::catch_unwind(|| {
256                    testing::with_monotonic_time(later, || panic!("unwind the clock scope"));
257                });
258                assert!(panicked.is_err());
259                assert_eq!(now(), at);
260            });
261            assert!(now() < at);
262        }
263
264        phase scoped_wall_time_is_thread_local_nested_and_restored_after_unwind;
265        {
266            let at = UNIX_EPOCH + Duration::from_secs(4_000_000_000);
267            testing::with_wall(at, || {
268                assert_eq!(wall(), at);
269                let later = at + Duration::from_secs(3);
270                testing::with_wall(later, || assert_eq!(wall(), later));
271                assert_eq!(wall(), at);
272                assert!(std::thread::spawn(wall).join().unwrap() < at);
273                let panicked = std::panic::catch_unwind(|| {
274                    testing::with_wall(later, || panic!("unwind the clock scope"));
275                });
276                assert!(panicked.is_err());
277                assert_eq!(wall(), at);
278            });
279            assert!(wall() < at);
280        }
281
282        phase a_clock_lent_at_the_epoch_is_a_clock_the_code_reads;
283        {
284            // `0` is the epoch, not the absence of a hold: a bare wasm32 has no
285            // `std` clock, so falling back to the machine's would trap a module lent
286            // this clock.
287            let (ms, held, frozen) = with_wall_ms(0, || (unix_now_ms(), wall(), wall_frozen()));
288            assert_eq!(ms, 0, "the lent time is the time the code reads");
289            assert_eq!(held, UNIX_EPOCH);
290            assert!(frozen, "a hold at the epoch is a hold");
291            assert!(
292                unix_now_ms() > 0,
293                "the thread's own clock runs again after the hold"
294            );
295        }
296
297        phase two_threads_holding_different_wall_times_at_once_each_read_their_own;
298        {
299            let first = UNIX_EPOCH + Duration::from_secs(4_000_000_000);
300            let second = UNIX_EPOCH + Duration::from_secs(4_100_000_000);
301            let together = std::sync::Arc::new(std::sync::Barrier::new(2));
302            let hold = |at: SystemTime, other: SystemTime| {
303                let together = std::sync::Arc::clone(&together);
304                std::thread::spawn(move || {
305                    testing::with_wall(at, || {
306                        together.wait();
307                        assert_eq!(wall(), at);
308                        assert_ne!(wall(), other);
309                        together.wait();
310                    });
311                    together.wait();
312                    assert!(wall() < first, "the hold ended with its scope");
313                })
314            };
315            let threads = [hold(first, second), hold(second, first)];
316            for thread in threads {
317                thread.join().unwrap();
318            }
319        }
320    }
321}
322
323thread_local! {
324    /// The wall time this thread holds; `None` while it reads its own clock.
325    static FROZEN_HERE_MS: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
326}
327
328fn frozen_ms() -> Option<u64> {
329    match FROZEN_HERE_MS.with(std::cell::Cell::get) {
330        Some(here) => Some(here),
331        None => match followed_ms() {
332            0 => match pinned_ms() {
333                0 => None,
334                pinned => Some(pinned),
335            },
336            followed => Some(followed),
337        },
338    }
339}
340
341/// Hold this thread's wall clock at `now_ms`; nested holds restore the one
342/// before them. This is how a host lends a clock to code that has none.
343pub fn with_wall_ms<T>(now_ms: u64, f: impl FnOnce() -> T) -> T {
344    struct Restore(Option<u64>);
345    impl Drop for Restore {
346        fn drop(&mut self) {
347            FROZEN_HERE_MS.with(|here| here.set(self.0));
348        }
349    }
350    let _restore = Restore(FROZEN_HERE_MS.with(|here| here.replace(Some(now_ms))));
351    f()
352}
353
354static PROCESS: std::sync::Mutex<Option<std::sync::Arc<AtomicU64>>> = std::sync::Mutex::new(None);
355
356fn pinned_ms() -> u64 {
357    PROCESS
358        .lock()
359        .unwrap_or_else(std::sync::PoisonError::into_inner)
360        .as_ref()
361        .map_or(0, |ms| ms.load(Ordering::Relaxed))
362}
363
364#[cfg(any(test, feature = "test-support"))]
365fn followed_ms() -> u64 {
366    testing::followed_ms()
367}
368
369#[cfg(not(any(test, feature = "test-support")))]
370const fn followed_ms() -> u64 {
371    0
372}
373
374#[allow(
375    clippy::disallowed_methods,
376    reason = "off the page this crate is where std's wall clock is read"
377)]
378#[must_use]
379#[inline]
380pub fn wall() -> SystemTime {
381    match frozen_ms() {
382        Some(ms) => UNIX_EPOCH
383            .checked_add(Duration::from_millis(ms))
384            .unwrap_or(UNIX_EPOCH),
385        None => SystemTime::now(),
386    }
387}
388
389/// Pin the wall clock of the whole process to `at` for a screenshot capture,
390/// so every frame shows the same date. The monotonic clock keeps running.
391#[cfg(not(test))]
392pub fn pin_wall(at: SystemTime) {
393    let pinned = std::sync::Arc::new(AtomicU64::new(wall_ms(at)));
394    *PROCESS
395        .lock()
396        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(pinned);
397}
398
399/// `at` as milliseconds since the epoch, never `0` (which means the clock runs).
400fn wall_ms(at: SystemTime) -> u64 {
401    at.duration_since(UNIX_EPOCH)
402        .map_or(1, |since| saturating_u64(since.as_millis()).max(1))
403}
404
405/// Whether a clock is held here, so a wall read answers the hold.
406#[must_use]
407pub fn wall_frozen() -> bool {
408    frozen_ms().is_some()
409}
410
411#[must_use]
412#[inline]
413pub fn to_std(time: SystemTime) -> std::time::SystemTime {
414    imp::to_std(time)
415}
416
417#[must_use]
418#[inline]
419pub fn from_std(time: std::time::SystemTime) -> SystemTime {
420    imp::from_std(time)
421}
422
423fn since_epoch() -> Option<Duration> {
424    wall().duration_since(UNIX_EPOCH).ok()
425}
426
427fn saturating_u64(value: u128) -> u64 {
428    u64::try_from(value).unwrap_or(u64::MAX)
429}
430
431pub fn try_unix_now() -> Option<u64> {
432    since_epoch().map(|duration| duration.as_secs())
433}
434
435pub fn try_unix_now_ms() -> Option<u64> {
436    since_epoch().map(|duration| saturating_u64(duration.as_millis()))
437}
438
439pub fn try_unix_now_ns() -> Option<u64> {
440    since_epoch().map(|duration| saturating_u64(duration.as_nanos()))
441}
442
443pub fn unix_now() -> u64 {
444    try_unix_now().unwrap_or(0)
445}
446
447pub fn unix_now_ms() -> u64 {
448    try_unix_now_ms().unwrap_or(0)
449}
450
451pub fn unix_now_ns() -> u64 {
452    try_unix_now_ns().unwrap_or(0)
453}
454
455pub fn unix_now_i64() -> i64 {
456    i64::try_from(unix_now()).unwrap_or(i64::MAX)
457}
458
459pub fn unix_now_ms_i64() -> i64 {
460    i64::try_from(unix_now_ms()).unwrap_or(i64::MAX)
461}
462
463pub trait Clock: Send + Sync {
464    fn now_ms(&self) -> u64;
465}
466
467#[derive(Clone, Copy, Debug, Default)]
468pub struct SystemClock;
469
470impl Clock for SystemClock {
471    fn now_ms(&self) -> u64 {
472        unix_now_ms()
473    }
474}
475
476/// Milliseconds since this process first read a monotonic clock; never moves
477/// backwards.
478#[derive(Clone, Copy, Debug, Default)]
479pub struct MonotonicClock;
480
481impl Clock for MonotonicClock {
482    #[allow(
483        clippy::disallowed_methods,
484        reason = "off the page this crate is where std's monotonic clock is read"
485    )]
486    fn now_ms(&self) -> u64 {
487        static START: OnceLock<Instant> = OnceLock::new();
488        saturating_u64(START.get_or_init(now).elapsed().as_millis())
489    }
490}
491
492#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
493pub struct FixedClock(pub u64);
494
495impl Clock for FixedClock {
496    fn now_ms(&self) -> u64 {
497        self.0
498    }
499}
500
501#[derive(Debug, Default)]
502pub struct ManualClock(AtomicU64);
503
504impl ManualClock {
505    pub const fn new(now_ms: u64) -> Self {
506        Self(AtomicU64::new(now_ms))
507    }
508
509    pub fn set(&self, now_ms: u64) {
510        self.0.store(now_ms, Ordering::SeqCst);
511    }
512
513    pub fn advance(&self, delta_ms: u64) {
514        let _ = self
515            .0
516            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |now| {
517                Some(now.saturating_add(delta_ms))
518            });
519    }
520}
521
522impl Clock for ManualClock {
523    fn now_ms(&self) -> u64 {
524        self.0.load(Ordering::SeqCst)
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    #[test]
533    fn a_threads_own_wall_clock_shadows_the_process_pin_only_on_that_thread() {
534        const OTHER: u64 = 4_000_000_000;
535        let at = UNIX_EPOCH + Duration::from_secs(OTHER);
536        tilo_test_env::in_own_process(
537            module_path!(),
538            "a_threads_own_wall_clock_shadows_the_process_pin_only_on_that_thread",
539            || {
540                let process = testing::OwnProcess::of_a_test_in_its_own_process();
541                let _held = testing::hold_wall_everywhere(process, at);
542                assert_eq!(unix_now(), OTHER);
543                assert!(wall_frozen());
544                testing::with_wall(at + Duration::from_secs(1), || {
545                    assert_eq!(wall(), at + Duration::from_secs(1), "the thread's own");
546                    assert_eq!(
547                        std::thread::spawn(wall).join().unwrap(),
548                        at,
549                        "another thread keeps the process's"
550                    );
551                });
552                assert_eq!(wall(), at, "the process's, after the thread's scope");
553            },
554        );
555    }
556
557    tilo_test_env::scenario! {
558        fn clocks_read_units_that_agree_and_a_hold_ends_with_its_scope;
559
560        phase a_frozen_wall_clock_holds_while_the_monotonic_clock_runs;
561        {
562            let at = UNIX_EPOCH + Duration::from_secs(1_782_816_120);
563            let before = now();
564            testing::with_wall(at, || {
565                assert!(wall_frozen());
566                assert_eq!(wall(), at);
567                assert_eq!(unix_now(), 1_782_816_120);
568                assert_eq!(wall(), at, "it stays put");
569                assert!(now() >= before, "the monotonic clock is not frozen");
570            });
571            assert!(!wall_frozen(), "the scope ended");
572        }
573
574        phase clocks_agree_on_units_move_only_as_told_and_never_backwards;
575        {
576            assert!(!wall_frozen(), "no other test's pinned time is read here");
577            {
578                let secs = unix_now();
579                let ms = unix_now_ms();
580                let ns = unix_now_ns();
581                assert!(secs > 1_600_000_000);
582                assert!(ms / 1_000 >= secs);
583                assert!(ns / 1_000_000 >= ms);
584                assert_eq!(unix_now_i64(), i64::try_from(unix_now()).unwrap());
585            }
586            {
587                assert_eq!(FixedClock(7).now_ms(), 7);
588                let clock = ManualClock::new(10);
589                assert_eq!(clock.now_ms(), 10);
590                clock.advance(5);
591                assert_eq!(clock.now_ms(), 15);
592                clock.set(3);
593                assert_eq!(clock.now_ms(), 3);
594                clock.set(u64::MAX - 1);
595                clock.advance(10);
596                assert_eq!(clock.now_ms(), u64::MAX);
597            }
598            {
599                let first = MonotonicClock.now_ms();
600                assert!(MonotonicClock.now_ms() >= first);
601            }
602        }
603
604        phase now_is_monotonic;
605        {
606            let earlier = now();
607            assert!(now() >= earlier);
608        }
609
610        phase wall_is_after_the_epoch;
611        {
612            assert!(wall().duration_since(UNIX_EPOCH).is_ok());
613        }
614
615        phase std_conversions_round_trip_on_both_sides_of_the_epoch;
616        {
617            let offset = Duration::from_millis(1_700_000_000_123);
618            for time in [UNIX_EPOCH + offset, UNIX_EPOCH - offset, UNIX_EPOCH] {
619                assert_eq!(from_std(to_std(time)), time);
620            }
621            assert_eq!(to_std(UNIX_EPOCH + offset), std::time::UNIX_EPOCH + offset);
622        }
623    }
624}