host_time_browser.rs (2078B)
1 //! Absolute deadlines with timer disposal confined to its local owner. 2 3 use core::{future::IntoFuture, pin::pin, time::Duration}; 4 use futures::{ 5 channel::oneshot, 6 future::{Either, select}, 7 }; 8 pub(crate) use web_time::Instant; 9 10 #[derive(Debug)] 11 pub(crate) struct Elapsed; 12 13 pub(crate) async fn timeout<F: IntoFuture>( 14 duration: Duration, 15 future: F, 16 ) -> Result<F::Output, Elapsed> { 17 timeout_at(Instant::now() + duration, future).await 18 } 19 20 pub(crate) async fn timeout_at<F: IntoFuture>( 21 deadline: Instant, 22 future: F, 23 ) -> Result<F::Output, Elapsed> { 24 let (elapsed, receiver) = oneshot::channel(); 25 let (cancel_on_drop, cancellation) = oneshot::channel::<()>(); 26 wasm_bindgen_futures::spawn_local(async move { 27 // Measure here: this owner may begin after the original caller yields. 28 // Dropping a losing timer here also avoids browser executor reentry in 29 // the task that polls the network future. 30 let timer = pin!(sleep_until(deadline)); 31 if matches!(select(timer, pin!(cancellation)).await, Either::Left(_)) { 32 let _ = elapsed.send(()); 33 } 34 }); 35 let result = match select(pin!(future.into_future()), pin!(receiver)).await { 36 Either::Left((value, _)) => Ok(value), 37 Either::Right(_) => Err(Elapsed), 38 }; 39 // This sender also drops if the observer cancels while select is pending. 40 drop(cancel_on_drop); 41 result 42 } 43 44 async fn sleep_until(deadline: Instant) { 45 loop { 46 let remaining = deadline.saturating_duration_since(Instant::now()); 47 if remaining.is_zero() { 48 return; 49 } 50 // Gloo truncates to whole milliseconds, then casts to the browser's 51 // signed timer argument. Round up and split long waits; recheck after 52 // every wake so neither truncation nor an early callback proves expiry. 53 let millis = remaining 54 .as_nanos() 55 .div_ceil(1_000_000) 56 .min(i32::MAX as u128) as u64; 57 async_utility::time::sleep(Duration::from_millis(millis)).await; 58 } 59 }