teloxide/utils/
shutdown_token.rs1use std::{
2 fmt,
3 future::Future,
4 sync::{Arc, Mutex},
5};
6
7use tokio_util::sync::CancellationToken;
8
9use crate::stop::StopToken;
10
11#[derive(Clone)]
15pub struct ShutdownToken(Arc<Mutex<Option<ActiveRun>>>);
16
17#[derive(Clone)]
18struct ActiveRun {
19 listener: StopToken,
20 finished: CancellationToken,
21}
22
23#[derive(Debug)]
28pub struct IdleShutdownError;
29
30impl ShutdownToken {
31 pub fn shutdown(&self) -> Result<impl Future<Output = ()> + '_, IdleShutdownError> {
40 let run = self.0.lock().unwrap().clone().ok_or(IdleShutdownError)?;
41 run.listener.stop();
42 Ok(run.finished.cancelled_owned())
43 }
44
45 pub(crate) fn new() -> Self {
46 Self(Arc::new(Mutex::new(None)))
47 }
48
49 pub(crate) fn start_dispatching(&self, listener: StopToken) -> DispatchRunGuard {
50 let mut active = self.0.lock().unwrap();
51 assert!(active.is_none(), "Dispatching is already running");
52 *active = Some(ActiveRun { listener, finished: CancellationToken::new() });
53 DispatchRunGuard { state: self.clone() }
54 }
55}
56
57pub(crate) struct DispatchRunGuard {
59 state: ShutdownToken,
60}
61
62impl Drop for DispatchRunGuard {
63 fn drop(&mut self) {
64 let run = self.state.0.lock().unwrap().take().expect("dispatch run is active");
65 run.listener.stop();
66 run.finished.cancel();
67 }
68}
69
70impl fmt::Display for IdleShutdownError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "Dispatcher was idle and as such couldn't be shut down")
73 }
74}
75
76impl std::error::Error for IdleShutdownError {}
77
78#[cfg(test)]
79mod tests {
80 use futures::FutureExt;
81
82 use super::*;
83 use crate::stop::mk_stop_token;
84
85 #[test]
86 fn shutdown_request_and_completion_are_persistent_and_run_specific() {
87 let token = ShutdownToken::new();
88 let (stop, flag) = mk_stop_token();
89 let run = token.start_dispatching(stop);
90 let first = token.shutdown().unwrap();
91 let second = token.shutdown().unwrap();
92 assert!(flag.is_stopped());
93 drop(run);
94 assert!(token.shutdown().is_err());
95
96 let (stop, flag) = mk_stop_token();
97 let next_run = token.start_dispatching(stop);
98 assert_eq!(first.now_or_never(), Some(()));
99 assert_eq!(second.now_or_never(), Some(()));
100 assert!(!flag.is_stopped());
101 drop(next_run);
102 assert!(flag.is_stopped());
103 }
104}