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
10pub type KernelDeadlineFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
12
13pub trait KernelClock: std::fmt::Debug + Send + Sync {
15 fn now(&self) -> Result<ProtocolTimestamp, KernelError>;
21
22 fn sleep_until(&self, deadline: ProtocolTimestamp) -> KernelDeadlineFuture<'_>;
24}
25
26#[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}