Skip to main content

zero_client/client/
scheduler.rs

1//! The clock and timers the engine runs on, and values that arrive later.
2
3use super::Error;
4use std::cell::RefCell;
5use std::future::Future;
6use std::pin::Pin;
7use std::rc::Rc;
8use std::task::{Context, Poll, Waker};
9
10/// The clock and timers the engine runs on: `Date.now()`,
11/// `performance.now()` and `setTimeout` in JS. Tests use
12/// [`ManualScheduler`](crate::testing::ManualScheduler) so a scenario runs
13/// the same way every time; an app's transport provides one that runs on
14/// its event loop.
15///
16/// The engine is single-threaded: every action runs on the thread that
17/// made the client.
18pub trait Scheduler {
19    /// Milliseconds since 1970 (`Date.now()`).
20    fn now(&self) -> f64;
21    /// Milliseconds on a monotonic clock (`performance.now()`).
22    fn monotonic_now(&self) -> f64;
23    /// Calls `action` after `ms` milliseconds.
24    fn schedule(&self, ms: f64, action: Box<dyn FnOnce()>) -> Box<dyn Timer>;
25    /// Calls `action` every `ms` milliseconds until cancelled (`setInterval`).
26    fn schedule_repeating(&self, ms: f64, action: Box<dyn FnMut()>) -> Box<dyn Timer>;
27    /// Calls `action` once the caller's synchronous code is done, before any
28    /// timer: where JS runs microtasks. The engine queues its follow-ups to
29    /// API calls here.
30    fn checkpoint(&self, action: Box<dyn FnOnce()>);
31}
32
33/// A timer from [`Scheduler::schedule`].
34pub trait Timer {
35    /// Stops the timer from firing. Does nothing once it has fired.
36    fn cancel(&self);
37}
38
39/// The delay `setTimeout` and `setInterval` wait for `ms`: none for NaN, a
40/// negative delay, or one past 2^31 - 1 ms, which browsers and Node fire at
41/// once.
42pub fn timer_delay(ms: f64) -> f64 {
43    if (0.0..=2_147_483_647.0).contains(&ms) {
44        ms
45    } else {
46        0.0
47    }
48}
49
50type Observer<T> = Box<dyn FnOnce(&Result<T, Error>)>;
51
52struct DeferredState<T> {
53    result: Option<Result<T, Error>>,
54    observers: Vec<Observer<T>>,
55    wakers: Vec<Waker>,
56}
57
58/// A value that arrives later, like a JS promise: the first `resolve` or
59/// `reject` wins. [`result`](Self::result) reads it without waiting; a
60/// `Deferred` is also a future that waits for it.
61pub struct Deferred<T>(Rc<RefCell<DeferredState<T>>>);
62
63impl<T> Clone for Deferred<T> {
64    fn clone(&self) -> Self {
65        Deferred(self.0.clone())
66    }
67}
68
69impl<T: Clone + 'static> Default for Deferred<T> {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl<T: Clone + 'static> Deferred<T> {
76    /// A deferred value that is not settled yet.
77    pub fn new() -> Self {
78        Deferred(Rc::new(RefCell::new(DeferredState {
79            result: None,
80            observers: Vec::new(),
81            wakers: Vec::new(),
82        })))
83    }
84
85    /// The result, once settled.
86    pub fn result(&self) -> Option<Result<T, Error>> {
87        self.0.borrow().result.clone()
88    }
89
90    /// Whether it has settled.
91    pub fn is_settled(&self) -> bool {
92        self.0.borrow().result.is_some()
93    }
94
95    pub(crate) fn resolve(&self, value: T) {
96        self.settle(Ok(value));
97    }
98
99    pub(crate) fn reject(&self, error: impl Into<Error>) {
100        self.settle(Err(error.into()));
101    }
102
103    pub(crate) fn settle(&self, result: Result<T, Error>) {
104        let (observers, wakers) = {
105            let mut s = self.0.borrow_mut();
106            if s.result.is_some() {
107                return;
108            }
109            s.result = Some(result.clone());
110            (
111                std::mem::take(&mut s.observers),
112                std::mem::take(&mut s.wakers),
113            )
114        };
115        for o in observers {
116            o(&result);
117        }
118        for w in wakers {
119            w.wake();
120        }
121    }
122
123    /// Calls `observer` once settled (right away if it already is).
124    pub fn on_settle(&self, observer: impl FnOnce(&Result<T, Error>) + 'static) {
125        let result = self.0.borrow().result.clone();
126        match result {
127            Some(r) => observer(&r),
128            None => self.0.borrow_mut().observers.push(Box::new(observer)),
129        }
130    }
131}
132
133impl<T: Clone + 'static> Future for Deferred<T> {
134    type Output = Result<T, Error>;
135
136    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
137        let mut s = self.0.borrow_mut();
138        match &s.result {
139            Some(r) => Poll::Ready(r.clone()),
140            None => {
141                s.wakers.push(cx.waker().clone());
142                Poll::Pending
143            }
144        }
145    }
146}