Skip to main content

tea_kernel/
clock.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::time::{Duration, SystemTime};
4
5use chrono::{DateTime, SecondsFormat, Utc};
6use tea_protocol::ProtocolTimestamp;
7
8use crate::{KernelError, KernelErrorCode};
9
10/// Boxed deadline future returned by a kernel clock.
11pub type KernelDeadlineFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
12
13/// Replaceable source of canonical time and deterministic deadlines.
14pub trait KernelClock: std::fmt::Debug + Send + Sync {
15    /// Returns the current caller-visible protocol timestamp.
16    ///
17    /// # Errors
18    ///
19    /// Returns a typed error when the source cannot produce canonical time.
20    fn now(&self) -> Result<ProtocolTimestamp, KernelError>;
21
22    /// Completes when the supplied canonical deadline is reached.
23    fn sleep_until(&self, deadline: ProtocolTimestamp) -> KernelDeadlineFuture<'_>;
24}
25
26/// Production clock backed by system UTC and Tokio deadlines.
27#[derive(Debug, Clone, Copy, Default)]
28pub struct TokioKernelClock;
29
30impl KernelClock for TokioKernelClock {
31    fn now(&self) -> Result<ProtocolTimestamp, KernelError> {
32        canonical_system_time(SystemTime::now())
33    }
34
35    fn sleep_until(&self, deadline: ProtocolTimestamp) -> KernelDeadlineFuture<'_> {
36        let duration = self
37            .now()
38            .ok()
39            .and_then(|now| (deadline.as_utc() - now.as_utc()).to_std().ok())
40            .unwrap_or(Duration::ZERO);
41        Box::pin(tokio::time::sleep(duration))
42    }
43}
44
45fn canonical_system_time(time: SystemTime) -> Result<ProtocolTimestamp, KernelError> {
46    let value = DateTime::<Utc>::from(time).to_rfc3339_opts(SecondsFormat::Millis, true);
47    value.parse().map_err(|_| {
48        KernelError::new(
49            KernelErrorCode::ClockFailure,
50            "system clock did not produce a canonical timestamp",
51        )
52    })
53}