Skip to main content

tembra_runtime/host/
clock.rs

1//! Only the native driver owns this timer. Shared JS runtimes use the same clock origin.
2use super::*;
3use futures::future::{AbortHandle, Abortable};
4
5impl Host {
6    /// Read the monotonic host clock used by both native and embedded adapters.
7    pub fn now_ms(&self) -> u64 {
8        let clock = self.0.clock.now_ms();
9        let sampled = clock.saturating_add(self.0.clock_offset.get());
10        let accepted = self.kernel().now();
11        if accepted > sampled {
12            self.0.clock_offset.set(accepted.saturating_sub(clock));
13            accepted
14        } else {
15            sampled
16        }
17    }
18
19    /// Preserve fractional timing while sharing the kernel's calibrated monotonic origin.
20    pub fn now(&self) -> f64 {
21        self.now_ms();
22        self.0.clock.now() + self.0.clock_offset.get() as f64
23    }
24
25    pub(super) fn tick(&self) {
26        if let Err(error) = self.kernel().tick(self.now_ms()) {
27            self.0.errors.borrow_mut().push(error);
28        }
29    }
30
31    pub(super) fn schedule_deadline(&self) {
32        if self.0.external_actions.get() {
33            return;
34        }
35        let deadline = self.kernel().next_deadline();
36        if self.0.deadline.borrow().as_ref().map(|(at, _)| *at) == deadline {
37            return;
38        }
39        if let Some((_, timer)) = self.0.deadline.borrow_mut().take() {
40            timer.abort();
41        }
42        let Some(deadline) = deadline else {
43            return;
44        };
45        let (abort, registration) = AbortHandle::new_pair();
46        let wait = self.0.clock.sleep(deadline.saturating_sub(self.now_ms()));
47        let weak = Rc::downgrade(&self.0);
48        *self.0.deadline.borrow_mut() = Some((deadline, abort));
49        if let Err(error) = self.0.executor.spawn_local(async move {
50            if Abortable::new(wait, registration).await.is_err() {
51                return;
52            }
53            if let Some(inner) = weak.upgrade() {
54                let host = Host(inner);
55                host.0.deadline.borrow_mut().take();
56                host.flush();
57            }
58        }) {
59            self.0.deadline.borrow_mut().take();
60            self.0
61                .errors
62                .borrow_mut()
63                .push(Error::invalid(Reason::Executor, error.to_string()));
64        }
65    }
66}