use std::sync::Arc;
use static_assertions::assert_impl_all;
use tokio::sync::watch;
use tokio_util::sync::{CancellationToken, DropGuard};
use super::ServerError;
#[derive(Clone, Debug)]
pub(in crate::server) enum ServerTerminal {
Clean,
Abnormal {
message: String,
source: Option<Arc<ServerError>>,
},
Cancelled,
}
#[derive(Clone)]
pub struct ServerShutdown {
inner: Arc<ServerShutdownInner>,
}
assert_impl_all!(ServerShutdown: Send, Sync, Unpin);
struct ServerShutdownInner {
stop_requested: CancellationToken,
_stop_guard: DropGuard,
terminal: watch::Receiver<Option<ServerTerminal>>,
}
impl ServerShutdown {
pub(in crate::server) fn new(
stop_requested: CancellationToken,
terminal: watch::Receiver<Option<ServerTerminal>>,
) -> Self {
let stop_guard = stop_requested.clone().drop_guard();
Self {
inner: Arc::new(ServerShutdownInner {
stop_requested,
_stop_guard: stop_guard,
terminal,
}),
}
}
pub fn stop(&self) { self.inner.stop_requested.cancel(); }
pub async fn drained(&self) -> Result<(), ServerError> {
let mut terminal = self.inner.terminal.clone();
loop {
if let Some(outcome) = terminal.borrow_and_update().clone() {
return terminal_result(outcome);
}
terminal
.changed()
.await
.map_err(|_| ServerError::AbnormalTermination {
message: "server shutdown observer ended without a terminal outcome".to_owned(),
source: None,
})?;
}
}
#[cfg(test)]
pub(in crate::server) fn terminal_receiver(&self) -> watch::Receiver<Option<ServerTerminal>> {
self.inner.terminal.clone()
}
}
fn terminal_result(terminal: ServerTerminal) -> Result<(), ServerError> {
match terminal {
ServerTerminal::Clean => Ok(()),
ServerTerminal::Abnormal { message, source } => {
Err(ServerError::AbnormalTermination { message, source })
}
ServerTerminal::Cancelled => Err(ServerError::AbnormalTermination {
message: "server supervisor task was cancelled before a clean shutdown".to_owned(),
source: None,
}),
}
}