use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::thread::{self, ThreadId};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
const SETTLE_LIMIT: Duration = Duration::from_secs(10);
#[derive(Clone)]
pub struct Clock {
inner: Arc<Inner>,
}
struct Inner {
origin: Option<Instant>,
state: Mutex<State>,
changed: Condvar,
}
#[derive(Default)]
struct State {
now_ms: u64,
next_id: u64,
waiters: HashMap<u64, Waiter>,
parties: HashMap<u64, Option<ThreadId>>,
}
struct Waiter {
thread: ThreadId,
deadline: Option<Duration>,
signal: Option<(Arc<AtomicU64>, u64)>,
}
impl Waiter {
fn is_due(&self, now: Duration) -> bool {
self.signal
.as_ref()
.is_some_and(|(generation, seen)| generation.load(Ordering::SeqCst) != *seen)
|| self.deadline.is_some_and(|deadline| deadline <= now)
}
}
impl Clock {
#[must_use]
pub fn system() -> Self {
Self::with_origin(Some(Instant::now()), 0)
}
#[must_use]
pub fn manual(start_ms: u64) -> Self {
Self::with_origin(None, start_ms)
}
fn with_origin(origin: Option<Instant>, now_ms: u64) -> Self {
Self {
inner: Arc::new(Inner {
origin,
state: Mutex::new(State {
now_ms,
..State::default()
}),
changed: Condvar::new(),
}),
}
}
#[must_use]
pub fn is_manual(&self) -> bool {
self.inner.origin.is_none()
}
#[must_use]
pub fn now_ms(&self) -> u64 {
if self.is_manual() {
self.lock().now_ms
} else {
let since_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
u64::try_from(since_epoch.as_millis()).unwrap_or(u64::MAX)
}
}
#[must_use]
pub fn monotonic(&self) -> Duration {
match self.inner.origin {
Some(origin) => origin.elapsed(),
None => Duration::from_millis(self.lock().now_ms),
}
}
pub fn settle(&self) {
if self.is_manual() {
let state = self.lock();
drop(self.settle_locked(state));
}
}
#[track_caller]
pub fn advance(&self, by: Duration) {
assert!(self.is_manual(), "only a manual clock can be advanced");
let mut state = self.lock();
let target = state.now_ms.saturating_add(millis(by));
loop {
state = self.settle_locked(state);
let now = Duration::from_millis(state.now_ms);
let next = state
.waiters
.values()
.filter_map(|waiter| waiter.deadline)
.filter(|&d| d > now)
.min();
match next {
Some(deadline) if millis(deadline) <= target => state.now_ms = millis(deadline),
_ => {
state.now_ms = target;
self.inner.changed.notify_all();
drop(self.settle_locked(state));
return;
}
}
self.inner.changed.notify_all();
}
}
fn settle_locked<'a>(&'a self, mut state: MutexGuard<'a, State>) -> MutexGuard<'a, State> {
let started = Instant::now();
while !is_quiet(&state) {
assert!(
started.elapsed() < SETTLE_LIMIT,
"a thread on the manual clock didn't go idle within {SETTLE_LIMIT:?}; is it blocked on the test?"
);
state = self
.inner
.changed
.wait_timeout(state, Duration::from_millis(20))
.unwrap_or_else(PoisonError::into_inner)
.0;
}
state
}
pub(crate) fn party(&self) -> Party {
let id = if self.is_manual() {
let mut state = self.lock();
state.next_id += 1;
let id = state.next_id;
state.parties.insert(id, None);
Some(id)
} else {
None
};
Party {
clock: self.clone(),
id,
}
}
pub(crate) fn wait(&self, signal: Option<(&Signal, u64)>, deadline: Option<Duration>) {
let mut state = self.lock();
state.next_id += 1;
let id = state.next_id;
let waiter = Waiter {
thread: thread::current().id(),
deadline,
signal: signal.map(|(signal, seen)| (Arc::clone(&signal.generation), seen)),
};
state.waiters.insert(id, waiter);
loop {
let now = self.now_locked(&state);
if state.waiters[&id].is_due(now) {
break;
}
state = match (self.inner.origin, deadline) {
(Some(_), Some(deadline)) => {
self.inner
.changed
.wait_timeout(state, deadline.saturating_sub(now))
.unwrap_or_else(PoisonError::into_inner)
.0
}
_ => self.inner.changed.wait(state).unwrap_or_else(PoisonError::into_inner),
};
}
state.waiters.remove(&id);
self.inner.changed.notify_all();
}
pub(crate) fn sleep(&self, duration: Duration) {
let deadline = self.monotonic().saturating_add(duration);
self.wait(None, Some(deadline));
}
fn now_locked(&self, state: &State) -> Duration {
match self.inner.origin {
Some(origin) => origin.elapsed(),
None => Duration::from_millis(state.now_ms),
}
}
fn lock(&self) -> MutexGuard<'_, State> {
self.inner.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl fmt::Debug for Clock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_manual() {
f.debug_struct("Clock").field("manual_ms", &self.now_ms()).finish()
} else {
f.debug_struct("Clock").field("system", &true).finish()
}
}
}
fn is_quiet(state: &State) -> bool {
let now = Duration::from_millis(state.now_ms);
state.parties.values().all(|thread| {
thread.is_some_and(|thread| {
state
.waiters
.values()
.any(|waiter| waiter.thread == thread && !waiter.is_due(now))
})
})
}
fn millis(duration: Duration) -> u64 {
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}
pub(crate) struct Party {
clock: Clock,
id: Option<u64>,
}
impl Party {
pub(crate) fn bind(&self) {
if let Some(id) = self.id {
self.clock.lock().parties.insert(id, Some(thread::current().id()));
self.clock.inner.changed.notify_all();
}
}
}
impl Drop for Party {
fn drop(&mut self) {
if let Some(id) = self.id {
self.clock.lock().parties.remove(&id);
self.clock.inner.changed.notify_all();
}
}
}
impl fmt::Debug for Party {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Party").field("id", &self.id).finish_non_exhaustive()
}
}
#[derive(Clone)]
pub(crate) struct Signal {
generation: Arc<AtomicU64>,
clock: Clock,
}
impl Signal {
pub(crate) fn new(clock: &Clock) -> Self {
Self {
generation: Arc::new(AtomicU64::new(0)),
clock: clock.clone(),
}
}
pub(crate) fn seen(&self) -> u64 {
self.generation.load(Ordering::SeqCst)
}
pub(crate) fn raise(&self) {
self.generation.fetch_add(1, Ordering::SeqCst);
let _state = self.clock.lock();
self.clock.inner.changed.notify_all();
}
}
impl fmt::Debug for Signal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Signal")
.field("generation", &self.seen())
.finish_non_exhaustive()
}
}