Skip to main content

rings_runtime/
task.rs

1//! Handing work to the executor.
2//!
3//! Three contracts, deliberately kept apart:
4//!
5//! ```text
6//!   spawn_detached : F → Result<(), Unscheduled F>        fire and forget
7//!   run_detached   : F → Future (Result<T, DetachedError>) awaited, but owned by the runtime
8//!   run_blocking   : (() → T) → Future (Result<T, DetachedError>)   native blocking pool
9//! ```
10//!
11//! All three hand ownership of the work to the executor at the call, not at a later poll:
12//! cancelling the caller (dropping the future that awaits [`run_detached`] or `run_blocking`)
13//! never cancels the work. None returns a handle that aborts the work — work whose lifetime the
14//! caller must own is not *detached*, and a caller that needs it keeps its own abort handle
15//! (native-only modules do so with Tokio's `JoinHandle`) instead of reaching for this boundary.
16//!
17//! Scheduling is fallible. Native code needs a current Tokio runtime; the browser event loop
18//! is always current. A missing runtime is reported *before* anything starts:
19//!
20//! * [`Spawner::current`] fails with [`RuntimeUnavailable`], so a caller that claims a
21//!   resource for the task acquires the spawner first and then spawns infallibly;
22//! * [`spawn_detached`] hands the unpolled future back in [`Unscheduled`], so a caller whose
23//!   task must not be lost can run it inline instead;
24//! * [`run_detached`] and `run_blocking` (native only: the browser has no blocking pool) yield
25//!   [`DetachedError::Unavailable`] at once, and their work never starts.
26//!
27//! Work that starts but publishes nothing (it panicked, or its runtime shut down first) is
28//! reported as [`Abandoned`].
29
30use std::fmt;
31use std::future::Future;
32
33use futures::channel::oneshot;
34
35use crate::bound::MaybeSend;
36
37/// No executor is current on this thread, so nothing can be scheduled on it.
38///
39/// Only native code observes this: the browser event loop is always current.
40#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
41#[error("no async runtime is current on this thread")]
42pub struct RuntimeUnavailable;
43
44/// A future that [`spawn_detached`] could not schedule, returned unpolled.
45pub struct Unscheduled<F>(pub(crate) F);
46
47impl<F> Unscheduled<F> {
48    /// Recover the future; it has never been polled.
49    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/// Scheduled work ended without publishing its output: it panicked, or its runtime shut down.
61#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
62#[error("detached task ended before publishing its result")]
63pub struct Abandoned;
64
65/// Why [`run_detached`] or `run_blocking` produced no output.
66#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
67pub enum DetachedError {
68    /// No executor was current, so the work never started.
69    #[error(transparent)]
70    Unavailable(#[from] RuntimeUnavailable),
71    /// The work started but published nothing.
72    #[error(transparent)]
73    Abandoned(#[from] Abandoned),
74}
75
76/// The capability to schedule detached work on one executor.
77///
78/// Acquired once with [`Spawner::current`]; afterwards [`Spawner::spawn`] needs no runtime
79/// on the calling thread (the native spawner pins the executor it was acquired on).
80///
81/// Invariant: a spawner does not keep its executor alive. Once a native runtime has shut
82/// down, work handed to its spawner is dropped unpolled — see [`Spawner::spawn`].
83#[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    /// The executor current on this thread.
91    ///
92    /// Post: `Err` iff native code runs outside a Tokio runtime.
93    #[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    /// The browser event loop, which is always current.
101    #[cfg(all(feature = "browser", target_family = "wasm"))]
102    pub fn current() -> Result<Self, RuntimeUnavailable> {
103        Ok(Self {})
104    }
105
106    /// Run `future` detached on this spawner's executor.
107    ///
108    /// Post: the executor owns `future` and runs it to completion while it is alive. If the
109    /// executor has shut down, `future` is dropped unpolled and `spawn` cannot report it;
110    /// work whose loss must be observed goes through [`Spawner::run_detached`], which reports
111    /// it as [`Abandoned`].
112    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
113    pub fn spawn<F>(&self, future: F)
114    where F: Future<Output = ()> + MaybeSend + 'static {
115        // Dropping the join handle detaches the task; it is not cancelled.
116        drop(self.handle.spawn(future));
117    }
118
119    /// Run `future` detached on the browser event loop.
120    #[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    /// Start `future` on this spawner's executor now and return a future of its output.
127    ///
128    /// Law: the executor, not the returned future, owns the work — dropping the returned
129    /// future abandons only the wait, and the work still runs to completion.
130    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            // The receiver is gone only when the waiter was dropped; the work has run anyway.
141            let _ = sender.send(future.await);
142        });
143        async move { receiver.await.map_err(|_| Abandoned) }
144    }
145}
146
147/// Run `future` detached from the caller on the current executor.
148///
149/// Post: `Ok` means the executor owns the future; `Err` hands it back unpolled because no
150/// executor is current, and the caller runs it inline or refuses the work.
151pub 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
162/// Start `future` on the current executor now and return a future of its output.
163///
164/// Post: the returned future yields `Unavailable` at once when no executor is current;
165/// otherwise [`Spawner::run_detached`]'s ownership law holds.
166pub 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/// Start the blocking `operation` on the current executor's blocking thread pool now and return
178/// a future of its output (native only: the browser event loop has no blocking pool).
179///
180/// Post: the returned future yields `Unavailable` at once when no executor is current (nothing
181/// runs), and `Abandoned` when `operation` panicked or the runtime shut down before its blocking
182/// task started (then `operation` never runs; see [`Abandoned`]). Otherwise the ownership law of
183/// [`run_detached`] holds: dropping the returned future abandons only the wait, and `operation`
184/// still runs to its end.
185#[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    /// Law: a spawner outliving its runtime drops work unpolled, and `run_detached` reports
295    /// the loss as `Abandoned` instead of hanging.
296    #[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    /// Law: outside a runtime, blocking work is refused before anything starts.
324    #[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    /// Law: the blocking work starts at the call and outlives a dropped waiter.
332    #[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    /// Law: blocking work that panics publishes nothing and is reported as abandoned.
345    #[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}