Skip to main content

moonproof_utils/
rt.rs

1//! Timers and clocks that work the same on a host and in a browser:
2//! tokio's timer and `std::time` on a host, the browser's `setTimeout`
3//! and `performance.now()` under `wasm32-unknown-unknown`, where
4//! `std::time::Instant::now` and tokio's timer driver are unavailable.
5
6use std::future::Future;
7use std::time::Duration;
8
9/// A monotonic instant: tokio's on a host, so a paused test clock moves
10/// it; `performance.now()` in a browser.
11#[cfg(not(target_arch = "wasm32"))]
12pub use tokio::time::Instant;
13#[cfg(target_arch = "wasm32")]
14pub use web_time::Instant;
15pub use web_time::{SystemTime, UNIX_EPOCH};
16
17/// `Send` on a host; nothing in a browser, where values that touch
18/// JavaScript stay on the thread that made them. Bound a future or
19/// stream by it where a host needs `Send` and a browser cannot give it.
20#[cfg(not(target_arch = "wasm32"))]
21pub trait MaybeSend: Send {}
22#[cfg(not(target_arch = "wasm32"))]
23impl<T: Send + ?Sized> MaybeSend for T {}
24
25/// `Send` on a host; nothing in a browser.
26#[cfg(target_arch = "wasm32")]
27pub trait MaybeSend {}
28#[cfg(target_arch = "wasm32")]
29impl<T: ?Sized> MaybeSend for T {}
30
31/// Run `future` in the background: on tokio's runtime on a host, on the
32/// browser's event loop in a browser.
33pub fn spawn<F>(future: F)
34where
35    F: Future<Output = ()> + MaybeSend + 'static,
36{
37    #[cfg(not(target_arch = "wasm32"))]
38    drop(tokio::spawn(future));
39    #[cfg(target_arch = "wasm32")]
40    wasm_bindgen_futures::spawn_local(future);
41}
42
43/// A background task that can be awaited or aborted, on either target.
44/// Dropping it detaches the task, which runs on, as tokio's
45/// `JoinHandle` does.
46pub struct Task<T: 'static> {
47    handle: Option<futures_util::future::RemoteHandle<Result<T, futures_util::future::Aborted>>>,
48    abort: futures_util::future::AbortHandle,
49}
50
51/// The task was aborted before it finished.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
53#[error("the task was aborted")]
54pub struct Aborted;
55
56/// Run `future` in the background, as [`spawn`] does, keeping a handle
57/// to await or abort it.
58pub fn spawn_task<F>(future: F) -> Task<F::Output>
59where
60    F: Future + MaybeSend + 'static,
61    F::Output: MaybeSend + 'static,
62{
63    use futures_util::FutureExt;
64    let (future, abort) = futures_util::future::abortable(future);
65    let (future, handle) = future.remote_handle();
66    spawn(future);
67    Task {
68        handle: Some(handle),
69        abort,
70    }
71}
72
73impl<T: 'static> Task<T> {
74    /// The task's output once it finishes.
75    ///
76    /// # Errors
77    ///
78    /// [`Aborted`] when [`Self::abort`] stopped it first.
79    pub async fn join(mut self) -> Result<T, Aborted> {
80        match self.handle.take() {
81            Some(handle) => handle.await.map_err(|_| Aborted),
82            None => Err(Aborted),
83        }
84    }
85
86    /// Stop the task at its next suspension point.
87    pub fn abort(&self) {
88        self.abort.abort();
89    }
90}
91
92impl<T: 'static> Drop for Task<T> {
93    fn drop(&mut self) {
94        if let Some(handle) = self.handle.take() {
95            handle.forget();
96        }
97    }
98}
99
100/// A deadline passed before the future finished.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
102#[error("timed out after {0:?}")]
103pub struct Elapsed(pub Duration);
104
105/// Wait for `duration`.
106pub async fn sleep(duration: Duration) {
107    #[cfg(not(target_arch = "wasm32"))]
108    tokio::time::sleep(duration).await;
109    #[cfg(target_arch = "wasm32")]
110    gloo_timers::future::sleep(duration).await;
111}
112
113/// `future`'s output, unless `duration` passes first.
114///
115/// # Errors
116///
117/// [`Elapsed`] when the deadline passes first; `future` is dropped.
118pub async fn timeout<F: Future>(duration: Duration, future: F) -> Result<F::Output, Elapsed> {
119    #[cfg(not(target_arch = "wasm32"))]
120    {
121        tokio::time::timeout(duration, future)
122            .await
123            .map_err(|_| Elapsed(duration))
124    }
125    #[cfg(target_arch = "wasm32")]
126    {
127        use futures_util::future::{select, Either};
128        let future = std::pin::pin!(future);
129        let deadline = std::pin::pin!(sleep(duration));
130        match select(future, deadline).await {
131            Either::Left((output, _)) => Ok(output),
132            Either::Right(((), _)) => Err(Elapsed(duration)),
133        }
134    }
135}