1use std::pin::Pin;
9
10use futures::Stream;
11
12#[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#[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")]
37pub 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#[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")]
62pub 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"))]
71pub type WasmBoxedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
73
74#[cfg(target_family = "wasm")]
75pub type WasmBoxedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
77
78#[cfg(not(target_family = "wasm"))]
79pub type WasmBoxedStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
81
82#[cfg(target_family = "wasm")]
83pub type WasmBoxedStream<'a, T> = Pin<Box<dyn Stream<Item = T> + 'a>>;
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
88#[error("future timed out")]
89pub struct Elapsed;
90
91pub 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
113pub async fn sleep(duration: std::time::Duration) {
118 futures_timer::Delay::new(duration).await;
119}
120
121#[cfg(test)]
122mod tests;