Skip to main content

tembra_runtime/
clock.rs

1//! Embeddings supply time and waits; the native adapter drives the kernel's next deadline.
2use futures::{FutureExt, future::LocalBoxFuture};
3use std::time::{Duration, Instant};
4
5/// A monotonic local clock used for linger and lifecycle deadlines.
6pub trait Clock {
7    /// Read whole monotonic milliseconds for lifecycle deadlines.
8    fn now_ms(&self) -> u64;
9    /// Read fractional milliseconds when the clock provides finer precision.
10    fn now(&self) -> f64 {
11        self.now_ms() as f64
12    }
13    /// Wait for a relative duration on the embedding clock.
14    fn sleep(&self, milliseconds: u64) -> LocalBoxFuture<'static, ()>;
15}
16
17pub(crate) struct SystemClock(Instant);
18impl Default for SystemClock {
19    fn default() -> Self {
20        Self(Instant::now())
21    }
22}
23impl Clock for SystemClock {
24    fn now_ms(&self) -> u64 {
25        self.0.elapsed().as_millis().min(u128::from(u64::MAX)) as u64
26    }
27    fn now(&self) -> f64 {
28        self.0.elapsed().as_secs_f64() * 1000.0
29    }
30
31    fn sleep(&self, milliseconds: u64) -> LocalBoxFuture<'static, ()> {
32        futures_timer::Delay::new(Duration::from_millis(milliseconds)).boxed_local()
33    }
34}