use std::{
panic::{AssertUnwindSafe, resume_unwind},
sync::{
Arc,
atomic::{AtomicU8, Ordering},
},
};
use futures::{Future, FutureExt};
use tokio::select;
use tokio_util::{
sync::{CancellationToken, DropGuardRef},
task::TaskTracker,
};
use crate::metrics::{
ServerCancellationReason,
inc_server_supervisor_abnormal_termination,
inc_server_supervisor_cancellation,
};
const SUPERVISOR_RUNNING: u8 = 0;
const SUPERVISOR_GRACEFUL: u8 = 1;
const SUPERVISOR_DROPPED: u8 = 2;
const SUPERVISOR_FINISHED: u8 = 3;
#[derive(Clone, Debug)]
pub(in crate::server) struct SupervisorLifecycle {
state: Arc<AtomicU8>,
}
impl SupervisorLifecycle {
pub(super) fn new() -> Self {
Self {
state: Arc::new(AtomicU8::new(SUPERVISOR_RUNNING)),
}
}
pub(super) fn record_graceful_cancellation(&self) {
self.state.store(SUPERVISOR_GRACEFUL, Ordering::Release);
record_supervisor_cancellation(ServerCancellationReason::Graceful);
}
pub(super) fn record_dropped_cancellation(&self) {
if self
.state
.compare_exchange(
SUPERVISOR_RUNNING,
SUPERVISOR_DROPPED,
Ordering::AcqRel,
Ordering::Acquire,
)
.is_ok()
{
record_supervisor_cancellation(ServerCancellationReason::Dropped);
}
}
pub(super) fn record_completion_without_cancellation(&self) {
self.state.store(SUPERVISOR_FINISHED, Ordering::Release);
}
pub(in crate::server) fn cancellation_reason(&self) -> ServerCancellationReason {
match self.state.load(Ordering::Acquire) {
SUPERVISOR_GRACEFUL => ServerCancellationReason::Graceful,
SUPERVISOR_DROPPED | SUPERVISOR_RUNNING | SUPERVISOR_FINISHED => {
ServerCancellationReason::Dropped
}
_ => ServerCancellationReason::Dropped,
}
}
}
fn record_supervisor_cancellation(reason: ServerCancellationReason) {
inc_server_supervisor_cancellation(reason);
tracing::info!(
event = "server_supervisor_cancellation",
reason = reason.label(),
"server_supervisor_cancellation",
);
}
pub(super) fn record_supervisor_abnormal_termination(message: &str) {
inc_server_supervisor_abnormal_termination();
tracing::error!(
event = "server_supervisor_abnormal_termination",
panic_message = %message,
"server supervisor terminated abnormally",
);
}
pub(super) struct SupervisorCancellationDropGuard<'a> {
_guard: DropGuardRef<'a>,
lifecycle: SupervisorLifecycle,
}
impl<'a> SupervisorCancellationDropGuard<'a> {
pub(super) const fn new(guard: DropGuardRef<'a>, lifecycle: SupervisorLifecycle) -> Self {
Self {
_guard: guard,
lifecycle,
}
}
}
impl Drop for SupervisorCancellationDropGuard<'_> {
fn drop(&mut self) { self.lifecycle.record_dropped_cancellation(); }
}
pub(super) async fn await_supervisor_termination<S>(
shutdown: S,
shutdown_token: &CancellationToken,
tracker: &TaskTracker,
lifecycle: &SupervisorLifecycle,
) where
S: Future<Output = ()>,
{
select! {
() = shutdown => {
lifecycle.record_graceful_cancellation();
shutdown_token.cancel();
}
() = tracker.wait() => lifecycle.record_completion_without_cancellation(),
}
}
pub(super) async fn run_with_panic_cleanup<S>(
supervisor: S,
shutdown_token: &CancellationToken,
tracker: &TaskTracker,
) -> Result<(), crate::server::ServerError>
where
S: Future<Output = Result<(), crate::server::ServerError>>,
{
match AssertUnwindSafe(supervisor).catch_unwind().await {
Ok(result) => result,
Err(panic) => {
shutdown_token.cancel();
tracker.close();
tracker.wait().await;
resume_unwind(panic);
}
}
}
#[cfg(test)]
#[path = "supervisor_tests.rs"]
mod tests;