teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
use std::{
    fmt,
    future::Future,
    sync::{Arc, Mutex},
};

use tokio_util::sync::CancellationToken;

use crate::stop::StopToken;

/// A token used to shut down a [`Dispatcher`].
///
/// [`Dispatcher`]: crate::dispatching::Dispatcher
#[derive(Clone)]
pub struct ShutdownToken(Arc<Mutex<Option<ActiveRun>>>);

#[derive(Clone)]
struct ActiveRun {
    listener: StopToken,
    finished: CancellationToken,
}

/// This error is returned from [`ShutdownToken::shutdown`] when trying to
/// shut down an idle [`Dispatcher`].
///
/// [`Dispatcher`]: crate::dispatching::Dispatcher
#[derive(Debug)]
pub struct IdleShutdownError;

impl ShutdownToken {
    /// Signals the update listener to stop. The returned future resolves once
    /// this dispatch run has ended, even if it ended before the future was
    /// polled.
    ///
    /// Returns an error if the dispatcher is idle at the moment.
    ///
    /// If you don't need to wait for shutdown, the returned future can be
    /// ignored.
    pub fn shutdown(&self) -> Result<impl Future<Output = ()> + '_, IdleShutdownError> {
        let run = self.0.lock().unwrap().clone().ok_or(IdleShutdownError)?;
        run.listener.stop();
        Ok(run.finished.cancelled_owned())
    }

    pub(crate) fn new() -> Self {
        Self(Arc::new(Mutex::new(None)))
    }

    pub(crate) fn start_dispatching(&self, listener: StopToken) -> DispatchRunGuard {
        let mut active = self.0.lock().unwrap();
        assert!(active.is_none(), "Dispatching is already running");
        *active = Some(ActiveRun { listener, finished: CancellationToken::new() });
        DispatchRunGuard { state: self.clone() }
    }
}

/// Ends the run on normal completion, cancellation or unwinding.
pub(crate) struct DispatchRunGuard {
    state: ShutdownToken,
}

impl Drop for DispatchRunGuard {
    fn drop(&mut self) {
        let run = self.state.0.lock().unwrap().take().expect("dispatch run is active");
        run.listener.stop();
        run.finished.cancel();
    }
}

impl fmt::Display for IdleShutdownError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Dispatcher was idle and as such couldn't be shut down")
    }
}

impl std::error::Error for IdleShutdownError {}

#[cfg(test)]
mod tests {
    use futures::FutureExt;

    use super::*;
    use crate::stop::mk_stop_token;

    #[test]
    fn shutdown_request_and_completion_are_persistent_and_run_specific() {
        let token = ShutdownToken::new();
        let (stop, flag) = mk_stop_token();
        let run = token.start_dispatching(stop);
        let first = token.shutdown().unwrap();
        let second = token.shutdown().unwrap();
        assert!(flag.is_stopped());
        drop(run);
        assert!(token.shutdown().is_err());

        let (stop, flag) = mk_stop_token();
        let next_run = token.start_dispatching(stop);
        assert_eq!(first.now_or_never(), Some(()));
        assert_eq!(second.now_or_never(), Some(()));
        assert!(!flag.is_stopped());
        drop(next_run);
        assert!(flag.is_stopped());
    }
}