Skip to main content

tokio_run_until_stalled/
lib.rs

1/// A utility for running [LocalSet] asynchronous tasks until
2/// no more progress can be made on any task in the [LocalSet].
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::Arc;
7use std::task::{Context, RawWaker, RawWakerVTable, Waker};
8
9use tokio::task::LocalSet;
10
11/// An extension trait for `tokio::runtime::Runtime` that provides a method for running
12/// asynchronous tasks of a `LocalSet` until no more progress can be made on any task in the `LocalSet`.
13///
14/// This trait is implemented for `tokio::runtime::Runtime` and `tokio::runtime::Handle`.
15pub trait RuntimeExt {
16    /// Run the given [LocalSet] until it stalls.
17    ///
18    /// This method runs the given [LocalSet] until it stalls.
19    /// If the [LocalSet] stalls, this method returns `None`. Otherwise,
20    /// it returns `Some(LocalSet)` containing the [`LocalSet`] need to run again.
21    ///
22    /// # Examples
23    ///
24    /// ``` rust
25    /// use std::time::Duration;
26    /// use tokio::{runtime::Builder, time::sleep, task::LocalSet};
27    /// use tokio_run_until_stalled::*;
28    ///
29    /// let local_set = LocalSet::new();
30    /// local_set.spawn_local(async {
31    ///     println!("Task 1 completed");
32    /// });
33    /// local_set.spawn_local(async {
34    ///    sleep(Duration::from_millis(100)).await;
35    ///    println!("Task 2 completed");
36    /// });
37    /// let rt = Builder::new_multi_thread().enable_all().build().unwrap();
38    /// let result = rt.run_until_stalled(local_set);
39    /// assert!(result.is_some());
40    /// rt.block_on(async { sleep(Duration::from_millis(150)).await; });
41    /// let final_result = rt.run_until_stalled(result.unwrap());
42    /// assert!(final_result.is_none());
43    /// ```
44    fn run_until_stalled(&self, local_set: LocalSet) -> Option<LocalSet>;
45}
46
47/// An extension trait for `tokio::task::LocalSet` convert it to `RunUntilStalled`.
48pub trait LocalSetExt {
49    fn run_until_stalled(self) -> RunUntilStalled;
50}
51
52/// [RunUntilStalled] A Future for running asynchronous tasks of a `LocalSet` until no more
53/// progress can be made on any task in the `LocalSet`.
54/// This future is created by the [`LocalSet::run_until_stalled`] method.
55/// # Examples
56///
57/// ``` rust
58/// use std::time::Duration;
59/// use tokio::{time::{sleep}, task::LocalSet};
60/// use tokio_run_until_stalled::*;
61///
62/// #[tokio::main]
63/// async fn main() {
64///    let local_set = LocalSet::new();
65///    local_set.spawn_local(async {
66///        println!("Task 1 completed");
67///    });
68///    local_set.spawn_local(async {
69///        sleep(Duration::from_millis(100)).await;
70///        println!("Task 2 completed");
71///    });
72///    let mut run_stalled = local_set.run_until_stalled();
73///    while !run_stalled.is_done() {
74///        run_stalled = run_stalled.await;
75///        sleep(Duration::from_millis(150)).await;
76///    }
77///}
78/// ```
79pub struct RunUntilStalled {
80    local_set: Option<LocalSet>,
81}
82
83impl RunUntilStalled {
84    /// Convert `RunUntilStalled` to `Option<LocalSet>`
85    pub fn into_local_set(self) -> Option<LocalSet> {
86        self.local_set
87    }
88
89    /// Check if the `RunUntilStalled` is done
90    pub fn is_done(&self) -> bool {
91        self.local_set.is_none()
92    }
93
94    /// Get the `LocalSet`
95    pub fn as_local_set(&self) -> &Option<LocalSet> {
96        &self.local_set
97    }
98
99    /// Force get the `LocalSet`
100    pub fn as_local_set_force(&self) -> &LocalSet {
101        self.local_set.as_ref().unwrap()
102    }
103}
104
105struct DetectWaker {
106    flag: AtomicBool,
107    waker: Waker,
108}
109
110impl DetectWaker {
111    fn wake(&self) {
112        self.flag.store(true, Ordering::Release);
113        self.waker.wake_by_ref();
114    }
115
116    fn has_waked(&self) -> bool {
117        self.flag.load(Ordering::Acquire)
118    }
119}
120
121fn create_detector_waker(waker: Waker) -> (Arc<DetectWaker>, Waker) {
122    let detector = Arc::new(DetectWaker {
123        flag: AtomicBool::default(),
124        waker,
125    });
126    static VTABLE: RawWakerVTable = RawWakerVTable::new(
127        |data| {
128            let origin = unsafe { Arc::from_raw(data as *const DetectWaker) };
129            let cloned = origin.clone();
130            std::mem::forget(origin);
131            RawWaker::new(Arc::into_raw(cloned) as *const _ as *const (), &VTABLE)
132        },
133        |data| {
134            let waker = unsafe { Arc::from_raw(data as *const DetectWaker) };
135            waker.wake();
136        },
137        |data| {
138            let waker = unsafe { Arc::from_raw(data as *const DetectWaker) };
139            waker.wake();
140            std::mem::forget(waker);
141        },
142        |data| {
143            let _ = unsafe { Arc::from_raw(data as *const DetectWaker) };
144        },
145    );
146
147    let waker = unsafe {
148        Waker::from_raw(RawWaker::new(
149            Arc::into_raw(detector.clone()) as *const _ as *const (),
150            &VTABLE,
151        ))
152    };
153    (detector, waker)
154}
155
156impl Future for RunUntilStalled {
157    type Output = Self;
158    fn poll(
159        mut self: std::pin::Pin<&mut Self>,
160        cx: &mut std::task::Context<'_>,
161    ) -> std::task::Poll<Self::Output> {
162        if self.local_set.is_none() {
163            return std::task::Poll::Ready(RunUntilStalled { local_set: None });
164        }
165
166        let (detector, waker) = create_detector_waker(cx.waker().clone());
167        let mut new_ctx = Context::from_waker(&waker);
168        let mut local_set = self.local_set.take().unwrap();
169        if std::task::Poll::Ready(()) == Pin::new(&mut local_set).poll(&mut new_ctx) {
170            std::task::Poll::Ready(RunUntilStalled { local_set: None })
171        } else if detector.has_waked() {
172            self.local_set = Some(local_set);
173            cx.waker().wake_by_ref();
174            std::task::Poll::Pending
175        } else {
176            std::task::Poll::Ready(RunUntilStalled {
177                local_set: Some(local_set),
178            })
179        }
180    }
181}
182
183impl LocalSetExt for LocalSet {
184    fn run_until_stalled(self) -> RunUntilStalled {
185        RunUntilStalled {
186            local_set: Some(self),
187        }
188    }
189}
190
191impl RuntimeExt for tokio::runtime::Runtime {
192    fn run_until_stalled(&self, local_set: LocalSet) -> Option<LocalSet> {
193        self.block_on(local_set.run_until_stalled())
194            .into_local_set()
195    }
196}
197
198impl RuntimeExt for tokio::runtime::Handle {
199    fn run_until_stalled(&self, local_set: LocalSet) -> Option<LocalSet> {
200        self.block_on(local_set.run_until_stalled())
201            .into_local_set()
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use std::{cell::RefCell, rc::Rc};
208
209    use super::*;
210
211    use tokio::{
212        sync::mpsc::channel,
213        task,
214        time::{sleep, Duration},
215    };
216
217    #[tokio::test]
218    async fn test_run_until_stalled() {
219        let local_set = LocalSet::new();
220        let logs = Rc::new(RefCell::new(vec![]));
221        local_set.spawn_local({
222            let logger = logs.clone();
223            async move {
224                logger.borrow_mut().push("task 1");
225                async {
226                    logger.borrow_mut().push("async log in task 1");
227                }
228                .await;
229                task::spawn_local({
230                    let logger = logger.clone();
231                    async move {
232                        logger.borrow_mut().push("inner spawn task");
233                        sleep(Duration::from_millis(100)).await;
234                        logger.borrow_mut().push("inner spawn task completed");
235                    }
236                });
237                logger.borrow_mut().push("Task 1 completed");
238            }
239        });
240
241        let mut run_stalled = local_set.run_until_stalled();
242
243        run_stalled = run_stalled.await;
244        assert_eq!(
245            &*logs.borrow(),
246            &[
247                "task 1",
248                "async log in task 1",
249                "Task 1 completed",
250                "inner spawn task"
251            ]
252        );
253        sleep(Duration::from_millis(150)).await;
254        run_stalled = run_stalled.await;
255        assert_eq!(
256            &*logs.borrow(),
257            &[
258                "task 1",
259                "async log in task 1",
260                "Task 1 completed",
261                "inner spawn task",
262                "inner spawn task completed"
263            ]
264        );
265        assert!(run_stalled.is_done());
266    }
267
268    #[tokio::test]
269    async fn test_depend_on_each() {
270        let local_set = LocalSet::new();
271        let logs = Rc::new(RefCell::new(vec![]));
272        let (tx1, mut rx1) = channel::<()>(1);
273        let (tx2, mut rx2) = channel::<()>(1);
274        local_set.spawn_local({
275            let logger = logs.clone();
276            async move {
277                logger.borrow_mut().push("task1");
278                logger.borrow_mut().push("wait for rx2");
279                if let Some(_) = rx2.recv().await {
280                    logger.borrow_mut().push("rx2 recv");
281                    logger.borrow_mut().push("tx1 send");
282                    let _ = tx1.send(()).await;
283                }
284                logger.borrow_mut().push("task1 completed");
285            }
286        });
287
288        local_set.spawn_local({
289            let logger = logs.clone();
290            async move {
291                logger.borrow_mut().push("task2");
292                logger.borrow_mut().push("tx2 send");
293                let _ = tx2.send(()).await;
294                logger.borrow_mut().push("wait for rx1");
295                if let Some(_) = rx1.recv().await {
296                    logger.borrow_mut().push("rx1 recv");
297                }
298                logger.borrow_mut().push("task2 completed");
299            }
300        });
301
302        let mut run_stalled = local_set.run_until_stalled();
303
304        run_stalled = run_stalled.await;
305        assert_eq!(
306            &*logs.borrow(),
307            &[
308                "task1",
309                "wait for rx2",
310                "task2",
311                "tx2 send",
312                "wait for rx1",
313                "rx2 recv",
314                "tx1 send",
315                "task1 completed",
316                "rx1 recv",
317                "task2 completed"
318            ]
319        );
320        assert!(run_stalled.is_done());
321    }
322}