use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::watch;
pub type Timer = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
pub trait Clock: fmt::Debug + Send + Sync + 'static {
fn now(&self) -> Instant;
fn timer(&self, deadline: Instant) -> Timer;
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SystemClock;
impl Clock for SystemClock {
#[inline]
fn now(&self) -> Instant {
Instant::now()
}
fn timer(&self, deadline: Instant) -> Timer {
let sleep = tokio::time::sleep_until(deadline.into());
Box::pin(sleep)
}
}
#[derive(Debug, Clone)]
pub struct ManualClock {
now: Arc<watch::Sender<Instant>>,
}
impl ManualClock {
#[must_use]
pub fn new() -> Self {
Self::starting_at(Instant::now())
}
#[must_use]
pub fn starting_at(start: Instant) -> Self {
Self {
now: Arc::new(watch::Sender::new(start)),
}
}
pub fn advance(&self, by: Duration) {
self.now.send_modify(|now| {
*now = now.checked_add(by).unwrap_or(*now);
});
}
pub fn advance_to(&self, deadline: Instant) {
self.now.send_modify(|now| {
if deadline > *now {
*now = deadline;
}
});
}
#[must_use]
pub fn armed(&self) -> usize {
self.now.receiver_count()
}
}
impl Default for ManualClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for ManualClock {
#[inline]
fn now(&self) -> Instant {
*self.now.borrow()
}
fn timer(&self, deadline: Instant) -> Timer {
let mut observer = self.now.subscribe();
Box::pin(async move {
loop {
if *observer.borrow_and_update() >= deadline {
return;
}
if observer.changed().await.is_err() {
return;
}
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_system_timer_for_a_past_deadline_resolves_immediately() {
let clock = SystemClock;
let deadline = clock
.now()
.checked_sub(Duration::from_mins(1))
.expect("a minute ago");
tokio::time::timeout(Duration::from_secs(5), clock.timer(deadline))
.await
.expect("a past deadline must resolve at once, not wait");
}
#[test]
fn a_manual_timer_is_armed_before_timer_returns() {
let clock = ManualClock::new();
assert_eq!(clock.armed(), 0, "nothing is armed yet");
let _timer = clock.timer(clock.now() + Duration::from_secs(1));
assert_eq!(
clock.armed(),
1,
"arming must have happened inside `timer`, with no poll in between"
);
}
#[test]
fn dropping_a_manual_timer_disarms_it() {
let clock = ManualClock::new();
let timer = clock.timer(clock.now() + Duration::from_secs(1));
assert_eq!(clock.armed(), 1);
drop(timer);
assert_eq!(clock.armed(), 0);
}
#[tokio::test]
async fn a_manual_timer_fires_only_once_the_clock_reaches_its_deadline() {
let clock = ManualClock::new();
let deadline = clock.now() + Duration::from_secs(10);
let mut timer = clock.timer(deadline);
clock.advance(Duration::from_secs(9));
assert!(
futures::poll!(&mut timer).is_pending(),
"nine seconds is not ten"
);
clock.advance(Duration::from_secs(1));
tokio::time::timeout(Duration::from_secs(5), timer)
.await
.expect("the deadline has been reached, so the timer must resolve");
}
#[tokio::test]
async fn a_deadline_reached_exactly_is_due() {
let clock = ManualClock::new();
let timer = clock.timer(clock.now() + Duration::from_secs(5));
clock.advance(Duration::from_secs(5));
tokio::time::timeout(Duration::from_secs(5), timer)
.await
.expect("an exactly-reached deadline is due, not pending");
}
#[tokio::test]
async fn one_advance_wakes_every_timer_it_passes() {
let clock = ManualClock::new();
let start = clock.now();
let timers = vec![
clock.timer(start + Duration::from_secs(1)),
clock.timer(start + Duration::from_secs(2)),
clock.timer(start + Duration::from_secs(3)),
];
assert_eq!(clock.armed(), 3);
clock.advance(Duration::from_secs(3));
tokio::time::timeout(Duration::from_secs(5), futures::future::join_all(timers))
.await
.expect("every timer the advance passed must resolve");
}
#[tokio::test]
async fn a_timer_resolves_when_its_clock_is_dropped() {
let clock = ManualClock::new();
let timer = clock.timer(clock.now() + Duration::from_hours(1));
drop(clock);
tokio::time::timeout(Duration::from_secs(5), timer)
.await
.expect("a dropped clock must release its waiters rather than hang them");
}
#[test]
fn clones_share_one_timeline() {
let clock = ManualClock::new();
let other = clock.clone();
let start = clock.now();
other.advance(Duration::from_secs(7));
assert_eq!(clock.now(), start + Duration::from_secs(7));
}
#[test]
fn advance_to_never_moves_time_backwards() {
let clock = ManualClock::new();
let start = clock.now();
clock.advance(Duration::from_secs(10));
clock.advance_to(start);
assert_eq!(
clock.now(),
start + Duration::from_secs(10),
"a deadline in the past must leave the clock where it was"
);
}
#[test]
fn advancing_past_the_end_of_time_saturates() {
let clock = ManualClock::new();
let before = clock.now();
clock.advance(Duration::MAX);
assert!(clock.now() >= before, "the clock must survive an overflow");
}
}