Skip to main content

teloxide/
stop.rs

1//! Stopping asynchronous tasks, e.g., [listeners].
2//!
3//! [listeners]: crate::update_listeners
4
5use std::{future::Future, pin::Pin, task};
6
7use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};
8
9/// Create a new token/flag pair.
10#[must_use]
11pub fn mk_stop_token() -> (StopToken, StopFlag) {
12    let token = CancellationToken::new();
13    let flag = StopFlag::new(token.clone());
14    (StopToken(token), flag)
15}
16
17/// A stop token which corresponds to a [`StopFlag`].
18#[derive(Clone)]
19pub struct StopToken(CancellationToken);
20
21/// A flag which corresponds to [`StopToken`].
22///
23/// To know if the stop token was used you can either repeatedly call
24/// [`is_stopped`] or use this type as a `Future`.
25///
26/// [`is_stopped`]: StopFlag::is_stopped
27pub struct StopFlag {
28    token: CancellationToken,
29    wait: Pin<Box<WaitForCancellationFutureOwned>>,
30}
31
32impl StopToken {
33    /// Stops all flags associated with this token.
34    ///
35    /// Subsequent calls do not change the stopped state.
36    pub fn stop(&self) {
37        self.0.cancel();
38    }
39}
40
41impl StopFlag {
42    fn new(token: CancellationToken) -> Self {
43        let wait = Box::pin(token.clone().cancelled_owned());
44        Self { token, wait }
45    }
46
47    /// Returns true if the stop token linked to `self` was used.
48    #[must_use]
49    pub fn is_stopped(&self) -> bool {
50        self.token.is_cancelled()
51    }
52}
53
54impl Clone for StopFlag {
55    fn clone(&self) -> Self {
56        Self::new(self.token.clone())
57    }
58}
59
60/// This future resolves when a stop token was used.
61impl Future for StopFlag {
62    type Output = ();
63
64    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
65        if self.is_stopped() {
66            task::Poll::Ready(())
67        } else {
68            self.wait.as_mut().poll(cx)
69        }
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use std::sync::{atomic::AtomicBool, Arc};
76
77    use futures::task::{waker, ArcWake};
78
79    use super::*;
80
81    #[test]
82    fn stop_wakes_every_registered_flag() {
83        struct Wake(AtomicBool);
84
85        impl ArcWake for Wake {
86            fn wake_by_ref(arc_self: &Arc<Self>) {
87                arc_self.0.store(true, std::sync::atomic::Ordering::Relaxed);
88            }
89        }
90
91        let (token, flag) = mk_stop_token();
92        let mut flags = [flag.clone(), flag];
93        let wakes =
94            [Arc::new(Wake(AtomicBool::new(false))), Arc::new(Wake(AtomicBool::new(false)))];
95        for (flag, wake) in flags.iter_mut().zip(&wakes) {
96            let waker = waker(Arc::clone(wake));
97            assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_pending());
98        }
99        token.stop();
100        for (flag, wake) in flags.iter_mut().zip(wakes) {
101            assert!(wake.0.load(std::sync::atomic::Ordering::Relaxed));
102            let waker = waker(wake);
103            assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_ready());
104        }
105    }
106}