1use std::fmt;
31use std::future::Future;
32
33use futures::channel::oneshot;
34
35use crate::bound::MaybeSend;
36
37#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
41#[error("no async runtime is current on this thread")]
42pub struct RuntimeUnavailable;
43
44pub struct Unscheduled<F>(pub(crate) F);
46
47impl<F> Unscheduled<F> {
48 pub fn into_inner(self) -> F {
50 self.0
51 }
52}
53
54impl<F> fmt::Debug for Unscheduled<F> {
55 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56 formatter.write_str("Unscheduled(..)")
57 }
58}
59
60#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
62#[error("detached task ended before publishing its result")]
63pub struct Abandoned;
64
65#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
67pub enum DetachedError {
68 #[error(transparent)]
70 Unavailable(#[from] RuntimeUnavailable),
71 #[error(transparent)]
73 Abandoned(#[from] Abandoned),
74}
75
76#[derive(Clone, Debug)]
84pub struct Spawner {
85 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
86 handle: tokio::runtime::Handle,
87}
88
89impl Spawner {
90 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
94 pub fn current() -> Result<Self, RuntimeUnavailable> {
95 tokio::runtime::Handle::try_current()
96 .map(|handle| Self { handle })
97 .map_err(|_| RuntimeUnavailable)
98 }
99
100 #[cfg(all(feature = "browser", target_family = "wasm"))]
102 pub fn current() -> Result<Self, RuntimeUnavailable> {
103 Ok(Self {})
104 }
105
106 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
113 pub fn spawn<F>(&self, future: F)
114 where F: Future<Output = ()> + MaybeSend + 'static {
115 drop(self.handle.spawn(future));
117 }
118
119 #[cfg(all(feature = "browser", target_family = "wasm"))]
121 pub fn spawn<F>(&self, future: F)
122 where F: Future<Output = ()> + MaybeSend + 'static {
123 wasm_bindgen_futures::spawn_local(future);
124 }
125
126 pub fn run_detached<F, T>(
131 &self,
132 future: F,
133 ) -> impl Future<Output = Result<T, Abandoned>> + MaybeSend + 'static
134 where
135 F: Future<Output = T> + MaybeSend + 'static,
136 T: MaybeSend + 'static,
137 {
138 let (sender, receiver) = oneshot::channel();
139 self.spawn(async move {
140 let _ = sender.send(future.await);
142 });
143 async move { receiver.await.map_err(|_| Abandoned) }
144 }
145}
146
147pub fn spawn_detached<F>(future: F) -> Result<(), Unscheduled<F>>
152where F: Future<Output = ()> + MaybeSend + 'static {
153 match Spawner::current() {
154 Ok(spawner) => {
155 spawner.spawn(future);
156 Ok(())
157 }
158 Err(RuntimeUnavailable) => Err(Unscheduled(future)),
159 }
160}
161
162pub fn run_detached<F, T>(
167 future: F,
168) -> impl Future<Output = Result<T, DetachedError>> + MaybeSend + 'static
169where
170 F: Future<Output = T> + MaybeSend + 'static,
171 T: MaybeSend + 'static,
172{
173 let output = Spawner::current().map(|spawner| spawner.run_detached(future));
174 async move { Ok(output?.await?) }
175}
176
177#[cfg(not(all(feature = "browser", target_family = "wasm")))]
186pub fn run_blocking<F, T>(
187 operation: F,
188) -> impl Future<Output = Result<T, DetachedError>> + Send + 'static
189where
190 F: FnOnce() -> T + Send + 'static,
191 T: Send + 'static,
192{
193 let joined = tokio::runtime::Handle::try_current()
194 .map(|handle| handle.spawn_blocking(operation))
195 .map_err(|_| RuntimeUnavailable);
196 async move { Ok(joined?.await.map_err(|_| Abandoned)?) }
197}
198
199#[cfg(all(test, not(target_family = "wasm")))]
200mod tests {
201 use std::sync::atomic::AtomicBool;
202 use std::sync::atomic::Ordering;
203 use std::sync::Arc;
204 use std::time::Duration;
205
206 use tokio::sync::Notify;
207
208 use super::run_blocking;
209 use super::run_detached;
210 use super::spawn_detached;
211 use super::Abandoned;
212 use super::DetachedError;
213 use super::RuntimeUnavailable;
214 use super::Spawner;
215
216 #[test]
217 fn test_spawner_outside_a_runtime_is_unavailable() {
218 assert_eq!(Spawner::current().err(), Some(RuntimeUnavailable));
219 }
220
221 #[test]
222 fn test_unscheduled_future_is_handed_back_unpolled() {
223 let polled = Arc::new(AtomicBool::new(false));
224 let witness = Arc::clone(&polled);
225 let unscheduled = spawn_detached(async move { witness.store(true, Ordering::SeqCst) })
226 .expect_err("no runtime is current outside Tokio");
227
228 assert!(!polled.load(Ordering::SeqCst));
229 futures::executor::block_on(unscheduled.into_inner());
230 assert!(polled.load(Ordering::SeqCst));
231 }
232
233 #[test]
234 fn test_run_detached_outside_a_runtime_is_unavailable() {
235 let result = futures::executor::block_on(run_detached(async {}));
236
237 assert_eq!(result, Err(DetachedError::Unavailable(RuntimeUnavailable)));
238 }
239
240 #[test]
241 fn test_spawner_keeps_its_executor_on_a_runtime_less_thread() {
242 let runtime = tokio::runtime::Runtime::new().expect("test runtime");
243 let spawner = runtime
244 .block_on(async { Spawner::current() })
245 .expect("current");
246 let done = Arc::new(Notify::new());
247 let signal = Arc::clone(&done);
248
249 std::thread::spawn(move || spawner.spawn(async move { signal.notify_one() }))
250 .join()
251 .expect("spawning thread");
252
253 runtime.block_on(done.notified());
254 }
255
256 #[tokio::test]
257 async fn test_cancelling_waiter_does_not_cancel_owned_detached_work() {
258 let started = Arc::new(Notify::new());
259 let release = Arc::new(Notify::new());
260 let completed = Arc::new(Notify::new());
261 let waiter = {
262 let started = Arc::clone(&started);
263 let release = Arc::clone(&release);
264 let completed = Arc::clone(&completed);
265 tokio::spawn(run_detached(async move {
266 started.notify_one();
267 release.notified().await;
268 completed.notify_one();
269 }))
270 };
271
272 started.notified().await;
273 waiter.abort();
274 let _ = waiter.await;
275 release.notify_one();
276
277 tokio::time::timeout(Duration::from_secs(1), completed.notified())
278 .await
279 .expect("owned detached work must outlive its cancelled waiter");
280 }
281
282 #[tokio::test]
283 async fn test_work_starts_at_the_call_not_at_the_first_poll() {
284 let completed = Arc::new(Notify::new());
285 let signal = Arc::clone(&completed);
286
287 drop(run_detached(async move { signal.notify_one() }));
288
289 tokio::time::timeout(Duration::from_secs(1), completed.notified())
290 .await
291 .expect("work handed to the executor must run although its waiter was never polled");
292 }
293
294 #[test]
297 fn test_spawner_after_runtime_shutdown_drops_work_and_reports_abandoned() {
298 let runtime = tokio::runtime::Runtime::new().expect("test runtime");
299 let spawner = runtime
300 .block_on(async { Spawner::current() })
301 .expect("current");
302 drop(runtime);
303 let polled = Arc::new(AtomicBool::new(false));
304 let witness = Arc::clone(&polled);
305
306 spawner.spawn(async move { witness.store(true, Ordering::SeqCst) });
307 let result = futures::executor::block_on(spawner.run_detached(async {}));
308
309 assert!(!polled.load(Ordering::SeqCst));
310 assert_eq!(result, Err(Abandoned));
311 }
312
313 #[tokio::test]
314 async fn test_panicking_detached_work_is_abandoned() {
315 let result: Result<(), DetachedError> = run_detached(async {
316 panic!("injected detached task failure");
317 })
318 .await;
319
320 assert_eq!(result, Err(DetachedError::Abandoned(Abandoned)));
321 }
322
323 #[test]
325 fn test_run_blocking_outside_a_runtime_is_unavailable() {
326 let result = futures::executor::block_on(run_blocking(|| ()));
327
328 assert_eq!(result, Err(DetachedError::Unavailable(RuntimeUnavailable)));
329 }
330
331 #[tokio::test]
333 async fn test_dropping_the_waiter_does_not_cancel_blocking_work() {
334 let (sender, receiver) = std::sync::mpsc::channel();
335
336 drop(run_blocking(move || sender.send(()).expect("receiver alive")));
337
338 tokio::task::spawn_blocking(move || receiver.recv_timeout(Duration::from_secs(10)))
339 .await
340 .expect("waiting thread")
341 .expect("blocking work must run although its waiter was dropped");
342 }
343
344 #[tokio::test]
346 async fn test_panicking_blocking_work_is_abandoned() {
347 let result: Result<(), DetachedError> =
348 run_blocking(|| panic!("injected blocking failure")).await;
349
350 assert_eq!(result, Err(DetachedError::Abandoned(Abandoned)));
351 }
352}