Skip to main content

reth_concurrency/sync/
time.rs

1//! Monotonic and system time using native clocks or a virtual clock in simulation.
2
3#[cfg(all(feature = "fuzz", dst))]
4use crate::sync::deterministic::{self, Timer, Waiter};
5#[cfg(all(feature = "fuzz", dst))]
6use std::ops::{Add, AddAssign, Sub, SubAssign};
7
8pub use std::time::{Duration, SystemTimeError};
9
10/// Uses the native fast clock outside simulation and the virtual clock under `fuzz` plus
11/// `--cfg dst`.
12#[cfg(all(feature = "fuzz", dst))]
13pub use self::Instant as FastInstant;
14
15#[cfg(not(all(feature = "fuzz", dst)))]
16pub use reth_primitives_traits::FastInstant;
17#[cfg(not(all(feature = "fuzz", dst)))]
18pub use std::time::{Instant, SystemTime, UNIX_EPOCH};
19
20/// A point on the simulated monotonic clock, reset for each runtime execution.
21///
22/// Signed nanoseconds permit backdating before the execution origin and deadlines beyond one
23/// [`Duration::MAX`] of elapsed time. Arithmetic bounds do not depend on the host clock.
24#[cfg(all(feature = "fuzz", dst))]
25#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
26pub struct Instant(pub(crate) i128);
27
28#[cfg(all(feature = "fuzz", dst))]
29impl Instant {
30    /// Returns the current virtual time.
31    pub fn now() -> Self {
32        Self(deterministic::now())
33    }
34
35    /// Returns the time elapsed since this instant, saturating at zero.
36    pub fn elapsed(&self) -> Duration {
37        Self::now().duration_since(*self)
38    }
39
40    /// Returns the elapsed duration, saturating at zero.
41    ///
42    /// Panics if the difference exceeds [`Duration::MAX`].
43    pub const fn duration_since(&self, earlier: Self) -> Duration {
44        let nanos = self.0.saturating_sub(earlier.0);
45        let nanos = if nanos < 0 { 0 } else { nanos };
46        assert!(nanos <= Duration::MAX.as_nanos() as i128, "duration between instants overflowed");
47        // The range check above bounds both components to Duration's representation.
48        Duration::new((nanos / 1_000_000_000) as u64, (nanos % 1_000_000_000) as u32)
49    }
50
51    /// Returns the elapsed duration, saturating at zero.
52    pub const fn saturating_duration_since(&self, earlier: Self) -> Duration {
53        self.duration_since(earlier)
54    }
55
56    /// Adds a duration, returning `None` on overflow.
57    pub fn checked_add(&self, duration: Duration) -> Option<Self> {
58        self.0.checked_add(duration.as_nanos() as i128).map(Self)
59    }
60
61    /// Subtracts a duration, returning `None` if the timestamp representation overflows.
62    pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
63        self.0.checked_sub(duration.as_nanos() as i128).map(Self)
64    }
65}
66
67#[cfg(all(feature = "fuzz", dst))]
68impl Add<Duration> for Instant {
69    type Output = Self;
70    fn add(self, rhs: Duration) -> Self {
71        self.checked_add(rhs).expect("overflow when adding duration to instant")
72    }
73}
74
75#[cfg(all(feature = "fuzz", dst))]
76impl Sub<Duration> for Instant {
77    type Output = Self;
78    fn sub(self, rhs: Duration) -> Self {
79        self.checked_sub(rhs).expect("overflow when subtracting duration from instant")
80    }
81}
82
83#[cfg(all(feature = "fuzz", dst))]
84impl Sub for Instant {
85    type Output = Duration;
86    fn sub(self, rhs: Self) -> Duration {
87        self.duration_since(rhs)
88    }
89}
90
91#[cfg(all(feature = "fuzz", dst))]
92impl AddAssign<Duration> for Instant {
93    fn add_assign(&mut self, rhs: Duration) {
94        *self = *self + rhs;
95    }
96}
97#[cfg(all(feature = "fuzz", dst))]
98impl SubAssign<Duration> for Instant {
99    fn sub_assign(&mut self, rhs: Duration) {
100        *self = *self - rhs;
101    }
102}
103
104/// Suspends the current thread until at least `duration` has elapsed.
105///
106/// Simulation advances to the earliest timer only when every application task
107/// is blocked; it never sleeps an OS thread.
108pub fn sleep(duration: Duration) {
109    #[cfg(not(all(feature = "fuzz", dst)))]
110    std::thread::sleep(duration);
111    #[cfg(all(feature = "fuzz", dst))]
112    {
113        let deadline = Instant::now() + duration;
114        let waiter = Waiter::new();
115        let timer = Timer::new(deadline, waiter.clone());
116        while Instant::now() < deadline {
117            waiter.wait();
118        }
119        drop(timer);
120    }
121}
122
123/// A system timestamp measured from a fixed Unix epoch in simulation.
124///
125/// The representation preserves native timestamp arithmetic and [`SystemTimeError`], but
126/// [`Self::now`] reads only the virtual clock, never the host wall clock.
127#[cfg(all(feature = "fuzz", dst))]
128#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
129#[allow(
130    clippy::disallowed_types,
131    reason = "Native timestamp representation only; now reads the scheduler virtual clock."
132)]
133pub struct SystemTime(std::time::SystemTime);
134
135/// The fixed origin of the simulated system clock.
136#[cfg(all(feature = "fuzz", dst))]
137pub const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH;
138
139#[cfg(all(feature = "fuzz", dst))]
140impl SystemTime {
141    /// The fixed origin of the simulated system clock.
142    pub const UNIX_EPOCH: Self = Self(std::time::UNIX_EPOCH);
143
144    /// Returns the Unix epoch plus the current execution's virtual elapsed time.
145    ///
146    /// Panics outside [`crate::sync::Runtime::run`]. Each execution starts at the epoch.
147    pub fn now() -> Self {
148        Self::UNIX_EPOCH + Instant::now().duration_since(Instant(0))
149    }
150
151    /// Returns the duration since `earlier`, or an error containing the reverse duration.
152    pub fn duration_since(&self, earlier: Self) -> Result<Duration, SystemTimeError> {
153        self.0.duration_since(earlier.0)
154    }
155
156    /// Returns the elapsed virtual duration, or an error if this timestamp is in the future.
157    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
158        Self::now().duration_since(*self)
159    }
160
161    /// Adds a duration, returning `None` if the native timestamp representation overflows.
162    pub fn checked_add(&self, duration: Duration) -> Option<Self> {
163        self.0.checked_add(duration).map(Self)
164    }
165
166    /// Subtracts a duration, returning `None` if the native timestamp representation overflows.
167    pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
168        self.0.checked_sub(duration).map(Self)
169    }
170}
171
172#[cfg(all(feature = "fuzz", dst))]
173impl Add<Duration> for SystemTime {
174    type Output = Self;
175
176    fn add(self, rhs: Duration) -> Self {
177        Self(self.0 + rhs)
178    }
179}
180
181#[cfg(all(feature = "fuzz", dst))]
182impl Sub<Duration> for SystemTime {
183    type Output = Self;
184
185    fn sub(self, rhs: Duration) -> Self {
186        Self(self.0 - rhs)
187    }
188}
189
190#[cfg(all(feature = "fuzz", dst))]
191impl AddAssign<Duration> for SystemTime {
192    fn add_assign(&mut self, rhs: Duration) {
193        self.0 += rhs;
194    }
195}
196
197#[cfg(all(feature = "fuzz", dst))]
198impl SubAssign<Duration> for SystemTime {
199    fn sub_assign(&mut self, rhs: Duration) {
200        self.0 -= rhs;
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[cfg(all(feature = "fuzz", dst))]
209    use crate::sync::Runtime;
210
211    #[test]
212    fn system_time_arithmetic_preserves_native_errors_and_bounds() {
213        let duration = Duration::from_nanos(7);
214        let before_epoch = UNIX_EPOCH - duration;
215        let error: std::time::SystemTimeError =
216            before_epoch.duration_since(UNIX_EPOCH).unwrap_err();
217        assert_eq!(error.duration(), duration);
218        assert_eq!(UNIX_EPOCH.duration_since(before_epoch).unwrap(), duration);
219        assert_eq!(SystemTime::UNIX_EPOCH, UNIX_EPOCH);
220
221        let mut timestamp = before_epoch;
222        timestamp += duration;
223        assert_eq!(timestamp, UNIX_EPOCH);
224        timestamp -= duration;
225        assert_eq!(timestamp, before_epoch);
226        assert_eq!(UNIX_EPOCH.checked_sub(duration), Some(before_epoch));
227        assert_eq!(before_epoch.checked_add(duration), Some(UNIX_EPOCH));
228        assert_eq!(
229            UNIX_EPOCH.checked_add(Duration::MAX).is_none(),
230            std::time::UNIX_EPOCH.checked_add(Duration::MAX).is_none()
231        );
232        assert_eq!(
233            UNIX_EPOCH.checked_sub(Duration::MAX).is_none(),
234            std::time::UNIX_EPOCH.checked_sub(Duration::MAX).is_none()
235        );
236    }
237
238    #[cfg(all(feature = "fuzz", dst))]
239    #[test]
240    fn system_time_tracks_virtual_time_and_resets_between_executions() {
241        for _ in 0..2 {
242            Runtime::new().run(|| {
243                assert_eq!(SystemTime::now(), UNIX_EPOCH);
244                let duration = Duration::from_secs(3);
245                let future = SystemTime::now() + duration;
246                assert_eq!(future.elapsed().unwrap_err().duration(), duration);
247                sleep(duration);
248                assert_eq!(SystemTime::now(), future);
249                assert_eq!(UNIX_EPOCH.elapsed().unwrap(), duration);
250                assert_eq!(future.elapsed().unwrap(), Duration::ZERO);
251            });
252        }
253    }
254
255    #[cfg(not(all(feature = "fuzz", dst)))]
256    #[test]
257    fn native_system_time_is_the_standard_type() {
258        let timestamp: std::time::SystemTime = SystemTime::now();
259        let selected: SystemTime = timestamp;
260        assert_eq!(selected, timestamp);
261    }
262}