Skip to main content

serialplugin_testing/
clock.rs

1//! Time of a [`FakeDevice`](crate::FakeDevice): its late answers, scheduled bytes and port
2//! timeouts run on a [`Clock`].
3
4use std::collections::BTreeMap;
5use std::sync::{Arc, Condvar, Mutex, MutexGuard};
6use std::time::{Duration, Instant};
7
8/// Work a clock runs when its time comes.
9pub type Job = Box<dyn FnOnce() + Send>;
10
11/// A source of time that runs jobs at a given moment.
12///
13/// Times are offsets from the clock's own start. Jobs due at the same moment run in the order
14/// they were given.
15pub trait Clock: Send + Sync + std::fmt::Debug {
16    /// Time since the clock started.
17    fn now(&self) -> Duration;
18
19    /// Run `job` once [`now`](Self::now) reaches `at` (at once, or soon, when it already has).
20    fn at(&self, at: Duration, job: Job);
21}
22
23/// Jobs by due time; the sequence number keeps the order of equal times.
24#[derive(Default)]
25struct Timers {
26    jobs: BTreeMap<(Duration, u64), Job>,
27    seq: u64,
28}
29
30impl Timers {
31    fn add(&mut self, at: Duration, job: Job) {
32        self.seq += 1;
33        self.jobs.insert((at, self.seq), job);
34    }
35
36    /// The first job due by `now`.
37    fn due(&mut self, now: Duration) -> Option<Job> {
38        let first = *self.jobs.keys().next()?;
39        (first.0 <= now).then(|| self.jobs.remove(&first)).flatten()
40    }
41
42    fn next(&self) -> Option<Duration> {
43        self.jobs.keys().next().map(|k| k.0)
44    }
45}
46
47fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
48    m.lock().unwrap_or_else(|e| e.into_inner())
49}
50
51/// Real time: [`std::time::Instant`]; jobs run on one timer thread per clock, started with
52/// the first job. The thread ends when the clock is dropped.
53///
54/// What a [`FakeDevice`](crate::FakeDevice) without a clock of its own delays answers with.
55#[derive(Debug, Clone)]
56pub struct SystemClock(Arc<SystemInner>);
57
58struct SystemInner {
59    start: Instant,
60    timers: Mutex<(Timers, bool)>,
61    wake: Condvar,
62}
63
64impl std::fmt::Debug for SystemInner {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("SystemClock").finish_non_exhaustive()
67    }
68}
69
70impl Default for SystemClock {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76impl SystemClock {
77    /// A clock that starts now.
78    pub fn new() -> Self {
79        Self(Arc::new(SystemInner {
80            start: Instant::now(),
81            timers: Mutex::new((Timers::default(), false)),
82            wake: Condvar::new(),
83        }))
84    }
85}
86
87impl Clock for SystemClock {
88    fn now(&self) -> Duration {
89        self.0.start.elapsed()
90    }
91
92    fn at(&self, at: Duration, job: Job) {
93        let mut timers = lock(&self.0.timers);
94        timers.0.add(at, job);
95        if !timers.1 {
96            timers.1 = true;
97            // The thread holds the clock weakly: dropping the last clock ends it.
98            let inner = Arc::downgrade(&self.0);
99            std::thread::spawn(move || run_system(inner));
100        }
101        drop(timers);
102        self.0.wake.notify_all();
103    }
104}
105
106fn run_system(inner: std::sync::Weak<SystemInner>) {
107    loop {
108        let Some(clock) = inner.upgrade() else {
109            return;
110        };
111        let mut timers = lock(&clock.timers);
112        let now = clock.start.elapsed();
113        if let Some(job) = timers.0.due(now) {
114            drop(timers);
115            // A panicking job must not end the thread: the jobs after it would never run. The
116            // panic hook has reported it.
117            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job));
118            continue;
119        }
120        // Wake up for the next job; with none, look again now and then, to see the clock go.
121        let wait = timers
122            .0
123            .next()
124            .map_or(Duration::from_millis(100), |next| next - now)
125            .min(Duration::from_millis(100));
126        let _woken = clock.wake.wait_timeout(timers, wait);
127    }
128}
129
130/// Time that moves only when the test says so: [`advance`](Self::advance) runs the jobs that
131/// became due, in order, on the caller's thread. Clones are the same clock.
132///
133/// ```
134/// use serialplugin_testing::{Clock, ManualClock};
135/// use std::sync::{Arc, Mutex};
136/// use std::time::Duration;
137///
138/// let clock = ManualClock::new();
139/// let fired = Arc::new(Mutex::new(Vec::new()));
140/// let f = fired.clone();
141/// clock.at(Duration::from_secs(2), Box::new(move || f.lock().unwrap().push(2)));
142/// clock.advance(Duration::from_secs(1));
143/// assert!(fired.lock().unwrap().is_empty());
144/// clock.advance(Duration::from_secs(1));
145/// assert_eq!(*fired.lock().unwrap(), [2]);
146/// ```
147#[derive(Clone, Default)]
148pub struct ManualClock(Arc<Mutex<(Duration, Timers)>>);
149
150impl std::fmt::Debug for ManualClock {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        f.debug_tuple("ManualClock").field(&self.now()).finish()
153    }
154}
155
156impl ManualClock {
157    /// A clock at zero.
158    pub fn new() -> Self {
159        Self::default()
160    }
161
162    /// Move the time on by `by` and run every job due by then, in order (also the ones those
163    /// jobs schedule within it).
164    ///
165    /// One thread at a time (a job may advance it too): two threads advancing at once could
166    /// run jobs side by side.
167    pub fn advance(&self, by: Duration) {
168        let target = lock(&self.0).0 + by;
169        loop {
170            let mut state = lock(&self.0);
171            let Some(next) = state.1.next().filter(|next| *next <= target) else {
172                // A job (or another thread) may have moved it further: time never goes back.
173                state.0 = state.0.max(target);
174                return;
175            };
176            // A job sees the time it was due at.
177            state.0 = state.0.max(next);
178            let now = state.0;
179            let job = state.1.due(now);
180            drop(state);
181            if let Some(job) = job {
182                job();
183            }
184        }
185    }
186}
187
188impl Clock for ManualClock {
189    fn now(&self) -> Duration {
190        lock(&self.0).0
191    }
192
193    fn at(&self, at: Duration, job: Job) {
194        // Due already: it runs with the next advance, also `advance(Duration::ZERO)`.
195        lock(&self.0).1.add(at, job);
196    }
197}
198
199/// Tokio time (feature `tokio`): [`tokio::time::Instant`], so a paused test clock
200/// (`#[tokio::test(start_paused = true)]`) drives the device's delays and nothing waits in
201/// real time. Jobs run on the runtime the clock was made in, in due order.
202#[cfg(feature = "tokio")]
203#[derive(Debug, Clone)]
204pub struct TokioClock(Arc<TokioInner>);
205
206#[cfg(feature = "tokio")]
207struct TokioInner {
208    start: tokio::time::Instant,
209    runtime: tokio::runtime::Handle,
210    timers: Mutex<Timers>,
211    /// Held while jobs run: two wakeups never run jobs side by side or out of order.
212    running: Mutex<()>,
213}
214
215#[cfg(feature = "tokio")]
216impl std::fmt::Debug for TokioInner {
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        f.debug_struct("TokioClock").finish_non_exhaustive()
219    }
220}
221
222#[cfg(feature = "tokio")]
223impl TokioClock {
224    /// A clock that starts now, on the current runtime; panics outside one.
225    // No `Default`: it needs a runtime, which `new` says.
226    #[allow(clippy::new_without_default)]
227    pub fn new() -> Self {
228        Self(Arc::new(TokioInner {
229            start: tokio::time::Instant::now(),
230            runtime: tokio::runtime::Handle::current(),
231            timers: Mutex::new(Timers::default()),
232            running: Mutex::new(()),
233        }))
234    }
235}
236
237#[cfg(feature = "tokio")]
238impl Clock for TokioClock {
239    fn now(&self) -> Duration {
240        // Outside the runtime tokio's `Instant` reads the real time: enter it, also on a port
241        // reader's own thread.
242        let _runtime = self.0.runtime.enter();
243        self.0.start.elapsed()
244    }
245
246    fn at(&self, at: Duration, job: Job) {
247        lock(&self.0.timers).add(at, job);
248        let inner = self.0.clone();
249        self.0.runtime.spawn(async move {
250            tokio::time::sleep_until(inner.start + at).await;
251            let _running = lock(&inner.running);
252            loop {
253                let job = lock(&inner.timers).due(inner.start.elapsed());
254                let Some(job) = job else { break };
255                job();
256            }
257        });
258    }
259}