origincloud_core/
runtime.rs1use std::future::Future;
11use std::pin::Pin;
12use std::time::Duration;
13#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
14use std::time::SystemTime;
15
16use futures_core::Stream;
17
18#[cfg(not(target_arch = "wasm32"))]
19mod bounds {
20 pub trait MaybeSend: Send {}
24 impl<T: Send + ?Sized> MaybeSend for T {}
25}
26
27#[cfg(target_arch = "wasm32")]
28mod bounds {
29 pub trait MaybeSend {}
33 impl<T: ?Sized> MaybeSend for T {}
34}
35
36pub use bounds::MaybeSend;
37
38#[cfg(not(target_arch = "wasm32"))]
41pub type MaybeSendFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
42#[cfg(target_arch = "wasm32")]
45pub type MaybeSendFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
46
47#[cfg(not(target_arch = "wasm32"))]
49pub(crate) type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
50#[cfg(target_arch = "wasm32")]
52pub(crate) type BoxStream<T> = Pin<Box<dyn Stream<Item = T>>>;
53
54#[cfg(all(target_arch = "wasm32", feature = "service-account-wasm"))]
57pub(crate) use futures_util::lock::Mutex;
58#[cfg(not(target_arch = "wasm32"))]
59pub(crate) use tokio::sync::Mutex;
60
61const MAX_BROWSER_TIMER: Duration = Duration::from_millis(i32::MAX as u64);
64
65pub(crate) async fn sleep(delay: Duration) {
71 #[cfg(not(target_arch = "wasm32"))]
72 tokio::time::sleep(delay).await;
73 #[cfg(target_arch = "wasm32")]
74 gloo_timers::future::sleep(browser_timer(delay)).await;
75}
76
77#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
79fn browser_timer(delay: Duration) -> Duration {
80 delay.min(MAX_BROWSER_TIMER)
81}
82
83#[cfg(any(not(target_arch = "wasm32"), feature = "service-account-wasm"))]
87pub(crate) fn now() -> SystemTime {
88 #[cfg(not(target_arch = "wasm32"))]
89 {
90 SystemTime::now()
91 }
92 #[cfg(target_arch = "wasm32")]
93 {
94 let millis = js_sys::Date::now() as u64;
96 SystemTime::UNIX_EPOCH + Duration::from_millis(millis)
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 #[test]
105 fn a_browser_timer_waits_at_most_what_set_timeout_takes() {
106 let max = Duration::from_millis(2_147_483_647);
107 assert_eq!(
108 browser_timer(Duration::from_millis(200)),
109 Duration::from_millis(200)
110 );
111 assert_eq!(browser_timer(max), max);
112 assert_eq!(browser_timer(max + Duration::from_millis(1)), max);
113 assert_eq!(
114 browser_timer(Duration::from_secs(10 * 365 * 24 * 60 * 60)),
115 max
116 );
117 assert_eq!(browser_timer(Duration::MAX), max);
118 }
119}