Skip to main content

rig_http/
wasm_compat.rs

1//! Target-dependent thread bounds, boxed futures, and executor-independent timers.
2//!
3//! ```
4//! use rig_http::wasm_compat::WasmBoxedFuture;
5//! let future: WasmBoxedFuture<'_, u32> = Box::pin(async { 42 });
6//! ```
7
8use std::pin::Pin;
9
10use futures::Stream;
11
12// Browser markers assume single-threaded execution; atomics would invalidate
13// that assumption. Relaxed bounds do not make non-Send handlers thread-safe.
14#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
15compile_error!(
16    "rig-http does not support threaded wasm (`+atomics`): its wasm-compat markers assume a \
17     single-threaded target"
18);
19
20#[cfg(not(target_family = "wasm"))]
21/// `Send` on native targets, a no-op marker on browser wasm.
22///
23/// ```compile_fail
24/// use std::rc::Rc;
25/// use rig_http::wasm_compat::WasmCompatSend;
26///
27/// fn shared<T: WasmCompatSend>(_: T) {}
28/// shared(Rc::new(0u8));
29/// ```
30#[diagnostic::on_unimplemented(
31    message = "`{Self}` is not `Send`, and Rig needs `Send` natively",
32    label = "not `Send`",
33    note = "handlers and transports run inside a driver's task: hold shared state behind an `Arc` (never an `Rc`), or use a `!Send` value only on browser wasm, where this marker is a no-op"
34)]
35pub trait WasmCompatSend: Send {}
36#[cfg(target_family = "wasm")]
37/// `Send` on native targets, a no-op marker on browser wasm.
38pub trait WasmCompatSend {}
39
40#[cfg(not(target_family = "wasm"))]
41impl<T> WasmCompatSend for T where T: Send {}
42#[cfg(target_family = "wasm")]
43impl<T> WasmCompatSend for T {}
44
45#[cfg(not(target_family = "wasm"))]
46/// `Sync` on native targets, a no-op marker on browser wasm.
47///
48/// ```compile_fail
49/// use std::cell::Cell;
50/// use rig_http::wasm_compat::WasmCompatSync;
51///
52/// fn shared<T: WasmCompatSync>(_: T) {}
53/// shared(Cell::new(0u8));
54/// ```
55#[diagnostic::on_unimplemented(
56    message = "`{Self}` is not `Sync`, and Rig needs `Sync` natively",
57    label = "not `Sync`",
58    note = "handlers and transports are shared between a driver and its in-flight tasks: use `Mutex`/atomics instead of `Cell`/`RefCell`, or use a `!Sync` value only on browser wasm, where this marker is a no-op"
59)]
60pub trait WasmCompatSync: Sync {}
61#[cfg(target_family = "wasm")]
62/// `Sync` on native targets, a no-op marker on browser wasm.
63pub trait WasmCompatSync {}
64
65#[cfg(not(target_family = "wasm"))]
66impl<T> WasmCompatSync for T where T: Sync {}
67#[cfg(target_family = "wasm")]
68impl<T> WasmCompatSync for T {}
69
70#[cfg(not(target_family = "wasm"))]
71/// Boxed future with `Send` on the same targets as [`WasmCompatSend`].
72pub type WasmBoxedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
73
74#[cfg(target_family = "wasm")]
75/// Boxed future type without `Send`, on browser wasm.
76pub type WasmBoxedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
77
78#[cfg(not(target_family = "wasm"))]
79/// Boxed stream with `Send` on the same targets as [`WasmCompatSend`].
80pub type WasmBoxedStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
81
82#[cfg(target_family = "wasm")]
83/// Boxed stream type without `Send`, on browser wasm.
84pub type WasmBoxedStream<'a, T> = Pin<Box<dyn Stream<Item = T> + 'a>>;
85
86/// Error returned by [`timeout`] when the future does not complete in time.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
88#[error("future timed out")]
89pub struct Elapsed;
90
91/// Await `future` until `duration` elapses, then drop it and return [`Elapsed`].
92/// The future is polled first, even for zero duration; cancellation runs only
93/// its drop cleanup. Uses a native timer thread or browser `setTimeout`, without
94/// requiring an executor timer or a feature flag.
95///
96/// # Panics
97/// May panic if the timer cannot represent the deadline for `duration`.
98pub async fn timeout<F>(duration: std::time::Duration, future: F) -> Result<F::Output, Elapsed>
99where
100    F: Future,
101{
102    use futures::future::{Either, select};
103
104    let delay = futures_timer::Delay::new(duration);
105    futures::pin_mut!(future);
106    futures::pin_mut!(delay);
107    match select(future, delay).await {
108        Either::Left((output, _)) => Ok(output),
109        Either::Right(((), _)) => Err(Elapsed),
110    }
111}
112
113/// Sleep for `duration` using the native or browser timer backend of [`timeout`].
114///
115/// # Panics
116/// May panic if the timer cannot represent the deadline for `duration`.
117pub async fn sleep(duration: std::time::Duration) {
118    futures_timer::Delay::new(duration).await;
119}
120
121#[cfg(test)]
122mod tests;