1use 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
10const SETTLE_LIMIT: Duration = Duration::from_secs(10);
13
14#[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 #[must_use]
77 pub fn system() -> Self {
78 Self::with_origin(Some(Instant::now()), 0)
79 }
80
81 #[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 #[must_use]
114 pub fn is_manual(&self) -> bool {
115 self.inner.origin.is_none()
116 }
117
118 #[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 #[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 pub fn settle(&self) {
169 if self.is_manual() {
170 let state = self.lock();
171 drop(self.settle_locked(state));
172 }
173 }
174
175 #[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 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 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 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
311fn 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
328pub(crate) struct Party {
330 clock: Clock,
331 id: Option<u64>,
332}
333
334impl Party {
335 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#[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 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 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}