Skip to main content

jev_client/
clock.rs

1//! Time, behind a trait so that retry behaviour can be tested without waiting.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::time::{Duration, Instant, SystemTime};
6
7/// A source of time and a way to wait.
8///
9/// [`HttpTransport`](crate::HttpTransport) measures latency and sleeps between retries through
10/// this trait. Production code uses [`SystemClock`]; a test substitutes a clock that records the
11/// requested delays and returns at once.
12pub trait Clock: Send + Sync {
13    /// A monotonic instant, used to measure how long a call took.
14    fn now(&self) -> Instant;
15
16    /// The wall-clock time, used only to interpret a `Retry-After` header that carries a date.
17    fn wall_time(&self) -> SystemTime;
18
19    /// Waits for `duration`.
20    fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
21}
22
23/// The real clock. Sleeping uses the Tokio timer, so it must run inside a Tokio runtime.
24#[derive(Clone, Copy, Debug, Default)]
25pub struct SystemClock;
26
27impl Clock for SystemClock {
28    fn now(&self) -> Instant {
29        Instant::now()
30    }
31
32    fn wall_time(&self) -> SystemTime {
33        SystemTime::now()
34    }
35
36    fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
37        Box::pin(tokio::time::sleep(duration))
38    }
39}