Skip to main content

tor_rtcompat/
join_set.rs

1//! Module exposing [`FuturesJoinSet`].
2
3use async_trait::async_trait;
4use futures::FutureExt;
5use futures::future::RemoteHandle;
6use futures::stream::{FuturesUnordered, StreamExt};
7use futures::task::SpawnError;
8
9use std::any::Any;
10use std::panic::AssertUnwindSafe;
11
12use crate::traits::{JoinSet, SpawnExt};
13
14/// A [`futures`]-based [`JoinSet`] implementation.
15pub struct FuturesJoinSet<T: Send + Sync + 'static, R> {
16    /// The runtime to spawn tasks on.
17    runtime: R,
18    /// The currently pending tasks.
19    ///
20    /// The remote futures of these handles can never panic,
21    /// because [`Self::spawn`] wraps them in [`futures::future::CatchUnwind`].
22    pending: FuturesUnordered<RemoteHandle<Result<T, Box<dyn Any + Send>>>>,
23}
24
25impl<T, R> FuturesJoinSet<T, R>
26where
27    T: Send + Sync + 'static,
28    R: SpawnExt + Send + Sync + 'static,
29{
30    /// Create a [`FuturesJoinSet`], for spawning tasks on `runtime`.
31    pub fn new(runtime: R) -> Self {
32        Self {
33            runtime,
34            pending: Default::default(),
35        }
36    }
37}
38
39#[async_trait]
40impl<T, R> JoinSet<T> for FuturesJoinSet<T, R>
41where
42    T: Send + Sync + 'static,
43    R: SpawnExt + Send + Sync + 'static,
44{
45    fn spawn<F>(&mut self, task: F) -> Result<(), SpawnError>
46    where
47        F: Future<Output = T> + Send + 'static,
48    {
49        let handle = self
50            .runtime
51            .spawn_with_handle(AssertUnwindSafe(task).catch_unwind())?;
52        self.pending.push(handle);
53        Ok(())
54    }
55
56    async fn join_next(&mut self) -> Option<Result<T, Box<dyn Any + Send>>> {
57        self.pending.next().await
58    }
59}
60
61// test_with_all_runtimes! only exists if these features are satisfied.
62#[cfg(all(
63    test,
64    any(feature = "native-tls", feature = "rustls"),
65    any(feature = "tokio", feature = "async-std", feature = "smol"),
66    not(miri), // Several of these use real SystemTime
67))]
68mod test {
69    // @@ begin test lint list maintained by maint/add_warning @@
70    #![allow(clippy::bool_assert_comparison)]
71    #![allow(clippy::clone_on_copy)]
72    #![allow(clippy::dbg_macro)]
73    #![allow(clippy::mixed_attributes_style)]
74    #![allow(clippy::print_stderr)]
75    #![allow(clippy::print_stdout)]
76    #![allow(clippy::single_char_pattern)]
77    #![allow(clippy::unwrap_used)]
78    #![allow(clippy::unchecked_time_subtraction)]
79    #![allow(clippy::useless_vec)]
80    #![allow(clippy::needless_pass_by_value)]
81    #![allow(clippy::string_slice)] // See arti#2571
82    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
83
84    use super::*;
85    use crate::test_with_all_runtimes;
86
87    #[test]
88    fn catch_unwinding_panics() {
89        test_with_all_runtimes!(|rt| async move {
90            let mut join_set = FuturesJoinSet::new(rt);
91
92            // Dummy values to return from the JoinSet tasks
93            let task_results = (1..=10).collect::<Vec<_>>();
94            for res in task_results.clone() {
95                join_set
96                    .spawn(async move {
97                        // Does not panic, returns immediately
98                        res
99                    })
100                    .unwrap();
101            }
102
103            join_set
104                .spawn(async {
105                    // This panic should be mapped to an Err(),
106                    // and not cause the task awaiting the JoinSet to unwind
107                    panic!("")
108                })
109                .unwrap();
110
111            let mut num_tasks = 0;
112            let mut actual = vec![];
113            while let Some(res) = join_set.join_next().await {
114                if let Ok(res) = res {
115                    actual.push(res);
116                }
117                num_tasks += 1;
118            }
119            actual.sort();
120
121            assert_eq!(num_tasks, task_results.len() + 1);
122            assert_eq!(actual, task_results);
123        });
124    }
125}