use std::{
fmt,
future::Future,
sync::{Arc, Mutex},
};
use tokio_util::sync::CancellationToken;
use crate::stop::StopToken;
#[derive(Clone)]
pub struct ShutdownToken(Arc<Mutex<Option<ActiveRun>>>);
#[derive(Clone)]
struct ActiveRun {
listener: StopToken,
finished: CancellationToken,
}
#[derive(Debug)]
pub struct IdleShutdownError;
impl ShutdownToken {
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() }
}
}
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());
}
}