Skip to main content

rings_runtime/
timer.rs

1//! The one timer Rings waits on.
2//!
3//! ```text
4//!   sleep : Duration → Future (Result<(), TimerError>)
5//! ```
6//!
7//! Laws, identical on both targets:
8//!
9//! * **Lower bound.** `sleep(d)` never resolves `Ok` before `d` has elapsed (up to the host
10//!   clock's resolution). The browser rounds `d` *up* to whole milliseconds and chains
11//!   `setTimeout` calls across its `2³¹ − 1` ms ceiling instead of clamping, which would
12//!   fire early.
13//! * **Unbounded.** `sleep(d)` with `d ≥` [`UNBOUNDED_SLEEP`] never resolves: a deadline that
14//!   far out is "never", not an instant the clock would overflow computing.
15//! * **Failure.** Only the browser can fail — when no global scope owns `setTimeout`, or the
16//!   host rejects the timer — and it does so promptly with `Err`. A repeating caller must
17//!   stop on `Err`: retrying would turn a missing timer into a hot loop.
18//!
19//! Native sleeps use `futures-timer`, which needs no particular executor; code that must
20//! follow a controlled test clock (Tokio's paused time) keeps that override at its own
21//! boundary.
22
23use std::time::Duration;
24
25/// Durations at or beyond this bound (`2³² − 1` s, about 136 years) sleep forever.
26pub const UNBOUNDED_SLEEP: Duration = Duration::from_secs(4_294_967_295);
27
28/// Why the browser could not wait.
29#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
30pub enum TimerError {
31    /// The code runs outside a window, worker or service-worker global scope.
32    #[error("no JavaScript global scope owns setTimeout")]
33    NoGlobalScope,
34    /// The host refused to schedule the timeout.
35    #[error("JavaScript timer rejected: {0}")]
36    Rejected(String),
37}
38
39/// Wait for `duration` on the native timer thread; never fails.
40#[cfg(not(all(feature = "browser", target_family = "wasm")))]
41pub async fn sleep(duration: Duration) -> Result<(), TimerError> {
42    if duration >= UNBOUNDED_SLEEP {
43        return std::future::pending().await;
44    }
45    futures_timer::Delay::new(duration).await;
46    Ok(())
47}
48
49/// Wait for `duration` on the JavaScript event loop.
50#[cfg(all(feature = "browser", target_family = "wasm"))]
51pub async fn sleep(duration: Duration) -> Result<(), TimerError> {
52    if duration >= UNBOUNDED_SLEEP {
53        return std::future::pending().await;
54    }
55    for millis in TimeoutSegments::new(duration) {
56        browser::set_timeout(millis).await?;
57    }
58    Ok(())
59}
60
61/// A duration decomposed into consecutive `setTimeout` delays.
62///
63/// `setTimeout` honours at most `i32::MAX` (`2³¹ − 1`) ms; a larger delay overflows and fires
64/// at once, so a longer duration is emitted as several segments instead.
65///
66/// Laws: every segment lies in `0 ..= 2³¹ − 1`; the segments sum to `⌈d⌉` in milliseconds;
67/// a zero duration is one zero segment, so `sleep(0)` still yields to the event loop.
68#[cfg(any(test, all(feature = "browser", target_family = "wasm")))]
69struct TimeoutSegments {
70    /// Milliseconds not yet covered by an emitted segment.
71    remaining_ms: u128,
72    /// Whether no segment has been emitted yet.
73    fresh: bool,
74}
75
76#[cfg(any(test, all(feature = "browser", target_family = "wasm")))]
77impl TimeoutSegments {
78    /// Segments covering `duration`, rounded up to whole milliseconds.
79    fn new(duration: Duration) -> Self {
80        Self {
81            remaining_ms: duration.as_nanos().div_ceil(1_000_000),
82            fresh: true,
83        }
84    }
85}
86
87#[cfg(any(test, all(feature = "browser", target_family = "wasm")))]
88impl Iterator for TimeoutSegments {
89    type Item = i32;
90
91    fn next(&mut self) -> Option<i32> {
92        if self.remaining_ms == 0 && !self.fresh {
93            return None;
94        }
95        self.fresh = false;
96        // Total: a remainder beyond the ceiling saturates to it, so no segment is ever lost.
97        let segment = i32::try_from(self.remaining_ms).unwrap_or(i32::MAX);
98        // `0 ≤ segment ≤ remaining_ms`, so the subtraction cannot underflow.
99        self.remaining_ms -= u128::from(segment.unsigned_abs());
100        Some(segment)
101    }
102}
103
104#[cfg(all(feature = "browser", target_family = "wasm"))]
105mod browser {
106    use wasm_bindgen::closure::Closure;
107    use wasm_bindgen::JsCast;
108    use wasm_bindgen::JsValue;
109
110    use super::TimerError;
111    use crate::global::global;
112
113    /// Resolve after one `setTimeout` of `millis` on the current global scope.
114    pub(super) async fn set_timeout(millis: i32) -> Result<(), TimerError> {
115        let scope = global().ok_or(TimerError::NoGlobalScope)?;
116        let promise = js_sys::Promise::new(&mut |resolve, reject| {
117            let wake = Closure::once_into_js(move || {
118                // Resolving a fresh promise from its own executor cannot throw.
119                let _ = resolve.call0(&JsValue::NULL);
120            });
121            if let Err(error) = scope.set_timeout_0(wake.unchecked_ref(), millis) {
122                let _ = reject.call1(&JsValue::NULL, &error);
123            }
124        });
125        wasm_bindgen_futures::JsFuture::from(promise)
126            .await
127            .map(drop)
128            .map_err(|error| TimerError::Rejected(format!("{error:?}")))
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use std::time::Duration;
135
136    use super::TimeoutSegments;
137
138    fn segments(duration: Duration) -> Vec<i32> {
139        TimeoutSegments::new(duration).collect()
140    }
141
142    #[test]
143    fn test_zero_duration_still_yields_once() {
144        assert_eq!(segments(Duration::ZERO), vec![0]);
145    }
146
147    #[test]
148    fn test_sub_millisecond_rounds_up() {
149        assert_eq!(segments(Duration::from_nanos(1)), vec![1]);
150        assert_eq!(segments(Duration::from_micros(1_500)), vec![2]);
151        assert_eq!(segments(Duration::from_millis(7)), vec![7]);
152    }
153
154    #[test]
155    fn test_ceiling_is_chained_not_clamped() {
156        let max = i32::MAX;
157        let at_ceiling = Duration::from_millis(u64::from(max.unsigned_abs()));
158
159        assert_eq!(segments(at_ceiling), vec![max]);
160        assert_eq!(segments(at_ceiling + Duration::from_millis(1)), vec![
161            max, 1
162        ]);
163        assert_eq!(segments(at_ceiling * 2), vec![max, max]);
164    }
165
166    #[test]
167    fn test_segments_sum_to_the_rounded_duration() {
168        for nanos in [0_u64, 1, 999_999, 1_000_000, 86_400_000_000_000, u64::MAX] {
169            let duration = Duration::from_nanos(nanos);
170            let emitted = segments(duration);
171            let total: u128 = emitted
172                .iter()
173                .map(|&ms| u128::from(ms.unsigned_abs()))
174                .sum();
175
176            assert_eq!(total, duration.as_nanos().div_ceil(1_000_000));
177            assert!(emitted.iter().all(|&ms| ms >= 0));
178        }
179    }
180}
181
182#[cfg(all(test, not(target_family = "wasm")))]
183mod native_tests {
184    use std::time::Duration;
185
186    use futures::FutureExt;
187
188    use super::sleep;
189    use super::UNBOUNDED_SLEEP;
190
191    #[test]
192    fn test_unbounded_sleep_never_resolves_or_overflows() {
193        let mut never = Box::pin(sleep(Duration::MAX));
194        assert!(never.as_mut().now_or_never().is_none());
195        assert!(Box::pin(sleep(UNBOUNDED_SLEEP)).now_or_never().is_none());
196    }
197
198    #[test]
199    fn test_native_sleep_never_fails() {
200        assert_eq!(futures::executor::block_on(sleep(Duration::ZERO)), Ok(()));
201    }
202}
203
204#[cfg(all(test, feature = "browser", target_family = "wasm"))]
205mod browser_tests {
206    use std::time::Duration;
207
208    use wasm_bindgen_test::wasm_bindgen_test;
209    use wasm_bindgen_test::wasm_bindgen_test_configure;
210
211    use super::sleep;
212
213    wasm_bindgen_test_configure!(run_in_browser);
214
215    #[wasm_bindgen_test]
216    async fn test_browser_sleep_resolves_after_its_duration() {
217        let started = js_sys::Date::now();
218        sleep(Duration::from_millis(20)).await.unwrap();
219
220        // `Date.now()` is quantised to whole (possibly coarsened) milliseconds.
221        assert!(js_sys::Date::now() - started >= 19.0);
222    }
223
224    #[wasm_bindgen_test]
225    async fn test_browser_zero_sleep_yields_and_resolves() {
226        sleep(Duration::ZERO).await.unwrap();
227    }
228}