Skip to main content

engine/core/
time.rs

1//! Virtual time.
2//!
3//! Time in the virtual world is a first-class Engine mechanism. The default
4//! [`VirtualClock`] is frozen until explicitly advanced: an idle virtual world
5//! does not age. This makes scenarios, tests, and replays deterministic.
6//!
7//! [`HostClock`] is provided for the rare case where timestamps must
8//! correspond to the host wall clock. It is non-deterministic and should not
9//! be used by scenarios or tests.
10
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14pub use super::timestamp::Timestamp;
15
16/// A source of virtual time.
17///
18/// Implementations must be shareable across threads ([`Send`] + [`Sync`]).
19pub trait Clock: Send + Sync {
20    /// The current virtual time.
21    fn now(&self) -> Timestamp;
22
23    /// Advances the clock by a duration.
24    ///
25    /// The default implementation does nothing, for clocks whose time is
26    /// externally controlled (such as the host wall clock). Virtual clocks
27    /// override this to implement `sleep` and other time-advancing behavior.
28    fn advance_by(&self, _duration: Duration) {}
29
30    /// Sets the clock to an absolute point in virtual time.
31    ///
32    /// The default implementation does nothing, for the same reason as
33    /// [`Clock::advance_by`].
34    fn set(&self, _timestamp: Timestamp) {}
35}
36
37/// A deterministic clock that is frozen until explicitly advanced.
38///
39/// Starts at [`Timestamp::ZERO`] unless seeded with [`VirtualClock::set`].
40/// Scenarios should seed it to a realistic boot date at OS initialization so
41/// the virtual world *looks* like real time while remaining deterministic.
42#[derive(Debug)]
43pub struct VirtualClock {
44    current: AtomicU64,
45}
46
47impl VirtualClock {
48    /// Creates a clock frozen at [`Timestamp::ZERO`].
49    pub const fn new() -> Self {
50        Self {
51            current: AtomicU64::new(0),
52        }
53    }
54}
55
56impl Default for VirtualClock {
57    fn default() -> Self {
58        Self::new()
59    }
60}
61
62impl Clock for VirtualClock {
63    fn now(&self) -> Timestamp {
64        Timestamp::from_nanos(self.current.load(Ordering::Relaxed))
65    }
66
67    fn advance_by(&self, duration: Duration) {
68        let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
69        // Atomic read-modify-write: two concurrent advances must compose,
70        // never overwrite one another (which could move time backwards).
71        let _ = self
72            .current
73            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
74                Some(current.saturating_add(nanos))
75            });
76    }
77
78    fn set(&self, timestamp: Timestamp) {
79        let nanos = timestamp.as_nanos();
80        // Seeding a fresh clock is the only sanctioned absolute set; an
81        // already-running timeline must never move backwards.
82        let _ = self
83            .current
84            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
85                debug_assert!(nanos >= current, "virtual time must never move backwards");
86                Some(nanos)
87            });
88    }
89}
90
91/// A clock backed by the host wall clock.
92///
93/// Non-deterministic: two runs of the same scenario produce different
94/// timestamps. Use only when wall-clock correspondence is explicitly required.
95#[derive(Clone, Copy, Debug)]
96pub struct HostClock;
97
98impl HostClock {
99    /// Creates a host-backed clock.
100    pub const fn new() -> Self {
101        Self
102    }
103}
104
105impl Default for HostClock {
106    fn default() -> Self {
107        Self::new()
108    }
109}
110
111impl Clock for HostClock {
112    fn now(&self) -> Timestamp {
113        let nanos = SystemTime::now()
114            .duration_since(UNIX_EPOCH)
115            .unwrap_or_default()
116            .as_nanos();
117        Timestamp::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))
118    }
119}