Skip to main content

legit_streams/
clock.rs

1//! Time for the worker and the in-memory double: the system's, or a manual clock tests move.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
7use std::thread::{self, ThreadId};
8use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
9
10/// How long [`Clock::settle`] and [`Clock::advance`] wait, in real time, for the threads that
11/// run on a manual clock to go idle before they give up.
12const SETTLE_LIMIT: Duration = Duration::from_secs(10);
13
14/// The time a [`Worker`](crate::Worker) and a [`MemoryStreams`](crate::MemoryStreams) run on: the
15/// system's, or a manual clock that only a test moves.
16///
17/// On a manual clock, time stands still until [`Clock::advance`]. The worker's own threads, its
18/// read loop and its lease heartbeat, take part in the clock: `advance` moves time forward one
19/// timer at a time and lets each thread that wakes finish what it does before it moves on, so a
20/// heartbeat due at 60 s runs before a claim due at 300 s, every time. [`Clock::settle`] waits for
21/// the same threads to go idle without moving time. A handler runs on a thread of its own, which
22/// doesn't take part: a test waits for it with a channel or similar.
23///
24/// The clock is a cheap handle; clones share one time.
25///
26/// ```
27/// use std::time::Duration;
28/// use legit_streams::Clock;
29///
30/// let clock = Clock::manual(1_700_000_000_000);
31/// clock.advance(Duration::from_secs(5));
32/// assert_eq!(clock.now_ms(), 1_700_000_005_000);
33/// ```
34#[derive(Clone)]
35pub struct Clock {
36    inner: Arc<Inner>,
37}
38
39struct Inner {
40    origin: Option<Instant>,
41    state: Mutex<State>,
42    changed: Condvar,
43}
44
45#[derive(Default)]
46struct State {
47    now_ms: u64,
48    next_id: u64,
49    waiters: HashMap<u64, Waiter>,
50    parties: HashMap<u64, Option<ThreadId>>,
51}
52
53struct Waiter {
54    thread: ThreadId,
55    deadline: Option<Duration>,
56    signal: Option<(Arc<AtomicU64>, u64)>,
57}
58
59impl Waiter {
60    fn is_due(&self, now: Duration) -> bool {
61        self.signal
62            .as_ref()
63            .is_some_and(|(generation, seen)| generation.load(Ordering::SeqCst) != *seen)
64            || self.deadline.is_some_and(|deadline| deadline <= now)
65    }
66}
67
68impl Clock {
69    /// The system clock.
70    ///
71    /// ```
72    /// use legit_streams::Clock;
73    ///
74    /// assert!(!Clock::system().is_manual());
75    /// ```
76    #[must_use]
77    pub fn system() -> Self {
78        Self::with_origin(Some(Instant::now()), 0)
79    }
80
81    /// A manual clock that reads `start_ms`, milliseconds since the Unix epoch, until moved.
82    ///
83    /// ```
84    /// use legit_streams::Clock;
85    ///
86    /// assert_eq!(Clock::manual(42).now_ms(), 42);
87    /// ```
88    #[must_use]
89    pub fn manual(start_ms: u64) -> Self {
90        Self::with_origin(None, start_ms)
91    }
92
93    fn with_origin(origin: Option<Instant>, now_ms: u64) -> Self {
94        Self {
95            inner: Arc::new(Inner {
96                origin,
97                state: Mutex::new(State {
98                    now_ms,
99                    ..State::default()
100                }),
101                changed: Condvar::new(),
102            }),
103        }
104    }
105
106    /// Whether this is a manual clock.
107    ///
108    /// ```
109    /// use legit_streams::Clock;
110    ///
111    /// assert!(Clock::manual(0).is_manual());
112    /// ```
113    #[must_use]
114    pub fn is_manual(&self) -> bool {
115        self.inner.origin.is_none()
116    }
117
118    /// The time, in milliseconds since the Unix epoch.
119    ///
120    /// ```
121    /// use legit_streams::Clock;
122    ///
123    /// assert!(Clock::system().now_ms() > 1_600_000_000_000);
124    /// ```
125    #[must_use]
126    pub fn now_ms(&self) -> u64 {
127        if self.is_manual() {
128            self.lock().now_ms
129        } else {
130            let since_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
131            u64::try_from(since_epoch.as_millis()).unwrap_or(u64::MAX)
132        }
133    }
134
135    /// Time for measuring how long something took: monotonic on the system clock, the manual
136    /// time on a manual one.
137    ///
138    /// ```
139    /// use std::time::Duration;
140    /// use legit_streams::Clock;
141    ///
142    /// let clock = Clock::manual(1_000);
143    /// let start = clock.monotonic();
144    /// clock.advance(Duration::from_millis(250));
145    /// assert_eq!(clock.monotonic() - start, Duration::from_millis(250));
146    /// ```
147    #[must_use]
148    pub fn monotonic(&self) -> Duration {
149        match self.inner.origin {
150            Some(origin) => origin.elapsed(),
151            None => Duration::from_millis(self.lock().now_ms),
152        }
153    }
154
155    /// Wait until every thread taking part in this manual clock is idle: waiting for time to pass
156    /// or for something that hasn't happened. Does nothing on the system clock.
157    ///
158    /// # Panics
159    ///
160    /// When a thread hasn't gone idle after 10 s of real time, which means it's blocked on
161    /// something that only the caller can release.
162    ///
163    /// ```
164    /// use legit_streams::Clock;
165    ///
166    /// Clock::manual(0).settle();
167    /// ```
168    pub fn settle(&self) {
169        if self.is_manual() {
170            let state = self.lock();
171            drop(self.settle_locked(state));
172        }
173    }
174
175    /// Move a manual clock forward by `by`, one due timer at a time, settling after each.
176    ///
177    /// # Panics
178    ///
179    /// On the system clock, and when a thread doesn't settle, as [`Clock::settle`] says.
180    ///
181    /// ```
182    /// use std::time::Duration;
183    /// use legit_streams::Clock;
184    ///
185    /// let clock = Clock::manual(0);
186    /// clock.advance(Duration::from_millis(1_500));
187    /// assert_eq!(clock.now_ms(), 1_500);
188    /// ```
189    #[track_caller]
190    pub fn advance(&self, by: Duration) {
191        assert!(self.is_manual(), "only a manual clock can be advanced");
192        let mut state = self.lock();
193        let target = state.now_ms.saturating_add(millis(by));
194        loop {
195            state = self.settle_locked(state);
196            let now = Duration::from_millis(state.now_ms);
197            let next = state
198                .waiters
199                .values()
200                .filter_map(|waiter| waiter.deadline)
201                .filter(|&d| d > now)
202                .min();
203            match next {
204                Some(deadline) if millis(deadline) <= target => state.now_ms = millis(deadline),
205                _ => {
206                    state.now_ms = target;
207                    self.inner.changed.notify_all();
208                    drop(self.settle_locked(state));
209                    return;
210                }
211            }
212            self.inner.changed.notify_all();
213        }
214    }
215
216    fn settle_locked<'a>(&'a self, mut state: MutexGuard<'a, State>) -> MutexGuard<'a, State> {
217        let started = Instant::now();
218        while !is_quiet(&state) {
219            assert!(
220                started.elapsed() < SETTLE_LIMIT,
221                "a thread on the manual clock didn't go idle within {SETTLE_LIMIT:?}; is it blocked on the test?"
222            );
223            state = self
224                .inner
225                .changed
226                .wait_timeout(state, Duration::from_millis(20))
227                .unwrap_or_else(PoisonError::into_inner)
228                .0;
229        }
230        state
231    }
232
233    /// Register a thread that takes part in a manual clock: [`Clock::settle`] waits for it until
234    /// it's idle. Until [`Party::bind`] it counts as busy, so a thread being started counts too.
235    pub(crate) fn party(&self) -> Party {
236        let id = if self.is_manual() {
237            let mut state = self.lock();
238            state.next_id += 1;
239            let id = state.next_id;
240            state.parties.insert(id, None);
241            Some(id)
242        } else {
243            None
244        };
245        Party {
246            clock: self.clone(),
247            id,
248        }
249    }
250
251    /// Block until `signal` changes from `seen`, or until `deadline`, a time on the
252    /// [`Clock::monotonic`] scale, passes. Returns at once when either already has.
253    pub(crate) fn wait(&self, signal: Option<(&Signal, u64)>, deadline: Option<Duration>) {
254        let mut state = self.lock();
255        state.next_id += 1;
256        let id = state.next_id;
257        let waiter = Waiter {
258            thread: thread::current().id(),
259            deadline,
260            signal: signal.map(|(signal, seen)| (Arc::clone(&signal.generation), seen)),
261        };
262        state.waiters.insert(id, waiter);
263        loop {
264            let now = self.now_locked(&state);
265            if state.waiters[&id].is_due(now) {
266                break;
267            }
268            state = match (self.inner.origin, deadline) {
269                (Some(_), Some(deadline)) => {
270                    self.inner
271                        .changed
272                        .wait_timeout(state, deadline.saturating_sub(now))
273                        .unwrap_or_else(PoisonError::into_inner)
274                        .0
275                }
276                _ => self.inner.changed.wait(state).unwrap_or_else(PoisonError::into_inner),
277            };
278        }
279        state.waiters.remove(&id);
280        self.inner.changed.notify_all();
281    }
282
283    /// Sleep for `duration` on this clock.
284    pub(crate) fn sleep(&self, duration: Duration) {
285        let deadline = self.monotonic().saturating_add(duration);
286        self.wait(None, Some(deadline));
287    }
288
289    fn now_locked(&self, state: &State) -> Duration {
290        match self.inner.origin {
291            Some(origin) => origin.elapsed(),
292            None => Duration::from_millis(state.now_ms),
293        }
294    }
295
296    fn lock(&self) -> MutexGuard<'_, State> {
297        self.inner.state.lock().unwrap_or_else(PoisonError::into_inner)
298    }
299}
300
301impl fmt::Debug for Clock {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        if self.is_manual() {
304            f.debug_struct("Clock").field("manual_ms", &self.now_ms()).finish()
305        } else {
306            f.debug_struct("Clock").field("system", &true).finish()
307        }
308    }
309}
310
311/// Whether every party is waiting on something that hasn't happened.
312fn is_quiet(state: &State) -> bool {
313    let now = Duration::from_millis(state.now_ms);
314    state.parties.values().all(|thread| {
315        thread.is_some_and(|thread| {
316            state
317                .waiters
318                .values()
319                .any(|waiter| waiter.thread == thread && !waiter.is_due(now))
320        })
321    })
322}
323
324fn millis(duration: Duration) -> u64 {
325    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
326}
327
328/// A thread taking part in a manual clock; see [`Clock::party`]. Dropping it ends the part.
329pub(crate) struct Party {
330    clock: Clock,
331    id: Option<u64>,
332}
333
334impl Party {
335    /// Bind the party to the calling thread, the one whose waits [`Clock::settle`] watches.
336    pub(crate) fn bind(&self) {
337        if let Some(id) = self.id {
338            self.clock.lock().parties.insert(id, Some(thread::current().id()));
339            self.clock.inner.changed.notify_all();
340        }
341    }
342}
343
344impl Drop for Party {
345    fn drop(&mut self) {
346        if let Some(id) = self.id {
347            self.clock.lock().parties.remove(&id);
348            self.clock.inner.changed.notify_all();
349        }
350    }
351}
352
353impl fmt::Debug for Party {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        f.debug_struct("Party").field("id", &self.id).finish_non_exhaustive()
356    }
357}
358
359/// Something threads wait for on a [`Clock`]: [`Signal::raise`] wakes every [`Clock::wait`] on it
360/// that saw the generation before the raise.
361#[derive(Clone)]
362pub(crate) struct Signal {
363    generation: Arc<AtomicU64>,
364    clock: Clock,
365}
366
367impl Signal {
368    pub(crate) fn new(clock: &Clock) -> Self {
369        Self {
370            generation: Arc::new(AtomicU64::new(0)),
371            clock: clock.clone(),
372        }
373    }
374
375    /// The generation to pass to [`Clock::wait`]: read it before checking for what the wait is
376    /// for, so a raise in between isn't missed.
377    pub(crate) fn seen(&self) -> u64 {
378        self.generation.load(Ordering::SeqCst)
379    }
380
381    pub(crate) fn raise(&self) {
382        self.generation.fetch_add(1, Ordering::SeqCst);
383        // Taking the lock orders this after any waiter's check of the generation...
384        let _state = self.clock.lock();
385        self.clock.inner.changed.notify_all();
386    }
387}
388
389impl fmt::Debug for Signal {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        f.debug_struct("Signal")
392            .field("generation", &self.seen())
393            .finish_non_exhaustive()
394    }
395}