use std::panic::{AssertUnwindSafe, resume_unwind};
use futures::FutureExt;
use tracing::{debug, error};
use crate::app::lifecycle::ConnectionTeardown;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum FinalizationOutcome {
Clean,
ReturnedError,
ProcessingPanic,
}
impl FinalizationOutcome {
pub(super) const fn as_str(self) -> &'static str {
match self {
Self::Clean => "clean",
Self::ReturnedError => "returned_error",
Self::ProcessingPanic => "processing_panic",
}
}
}
pub(super) enum ConnectionFinalizer<C> {
NotSetUp,
Armed(C),
Finalized,
}
impl<C> ConnectionFinalizer<C> {
pub(super) const fn not_set_up() -> Self { Self::NotSetUp }
pub(super) fn arm(&mut self, state: C) {
if matches!(self, Self::NotSetUp) {
*self = Self::Armed(state);
}
}
pub(super) fn take_for_teardown(&mut self) -> Option<C> {
match std::mem::replace(self, Self::Finalized) {
Self::Armed(state) => Some(state),
Self::NotSetUp | Self::Finalized => None,
}
}
pub(super) async fn finalize(
&mut self,
teardown: Option<&ConnectionTeardown<C>>,
outcome: FinalizationOutcome,
) {
let Some(state) = self.take_for_teardown() else {
return;
};
let Some(callback) = teardown else {
return;
};
run_teardown(callback, state, outcome).await;
}
}
async fn run_teardown<C>(callback: &ConnectionTeardown<C>, state: C, outcome: FinalizationOutcome) {
log_teardown_started(outcome);
if let Err(payload) = AssertUnwindSafe(async move { callback(state).await })
.catch_unwind()
.await
{
log_teardown_panicked(outcome);
resume_unwind(payload);
}
log_teardown_completed(outcome);
}
fn log_teardown_started(outcome: FinalizationOutcome) {
debug!(
stage = "connection_runtime",
operation = "teardown",
outcome = outcome.as_str(),
"connection teardown started"
);
}
fn log_teardown_completed(outcome: FinalizationOutcome) {
debug!(
stage = "connection_runtime",
operation = "teardown",
outcome = outcome.as_str(),
"connection teardown completed"
);
}
fn log_teardown_panicked(outcome: FinalizationOutcome) {
error!(
stage = "connection_runtime",
operation = "teardown",
outcome = outcome.as_str(),
"connection teardown panicked; the panic is not retried"
);
}