use std::{
future::Future,
panic::{AssertUnwindSafe, resume_unwind},
};
use futures::FutureExt as _;
use tokio::task::{JoinError, JoinHandle};
type PanicPayload = Box<dyn std::any::Any + Send>;
#[must_use = "a dropped guard aborts the server without observing its outcome"]
pub struct ServerTaskGuard<T> {
handle: JoinHandle<T>,
should_abort_on_drop: bool,
}
impl<T> ServerTaskGuard<T> {
pub const fn new(handle: JoinHandle<T>) -> Self {
Self {
handle,
should_abort_on_drop: true,
}
}
pub async fn join(mut self) -> Result<T, JoinError> {
let outcome = (&mut self.handle).await;
self.should_abort_on_drop = false;
outcome
}
pub async fn abort_and_join(mut self) -> Result<Option<T>, JoinError> {
self.handle.abort();
let outcome = (&mut self.handle).await;
self.should_abort_on_drop = false;
match outcome {
Ok(value) => Ok(Some(value)),
Err(error) if error.is_cancelled() => Ok(None),
Err(error) => Err(error),
}
}
pub async fn run_and_join<R, E, Fut>(self, body: Fut) -> Result<(R, T), E>
where
Fut: Future<Output = Result<R, E>>,
E: From<JoinError>,
{
self.run_guarded(body, Self::join).await
}
pub async fn run_and_abort<R, E, Fut>(self, body: Fut) -> Result<(R, Option<T>), E>
where
Fut: Future<Output = Result<R, E>>,
E: From<JoinError>,
{
self.run_guarded(body, Self::abort_and_join).await
}
async fn run_guarded<R, E, Fut, S, F, G>(self, body: Fut, reap: F) -> Result<(R, S), E>
where
Fut: Future<Output = Result<R, E>>,
E: From<JoinError>,
F: FnOnce(Self) -> G,
G: Future<Output = Result<S, JoinError>>,
{
match AssertUnwindSafe(body).catch_unwind().await {
Ok(Ok(value)) => {
let server = reap(self).await.map_err(E::from)?;
Ok((value, server))
}
Ok(Err(error)) => {
let _cleanup = self.abort_and_join().await;
Err(error)
}
Err(payload) => Err(stop_and_resume(self, payload).await),
}
}
}
async fn stop_and_resume<T, E>(guard: ServerTaskGuard<T>, payload: PanicPayload) -> E {
let _cleanup = guard.abort_and_join().await;
resume_unwind(payload)
}
impl<T> std::fmt::Debug for ServerTaskGuard<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServerTaskGuard")
.field("should_abort_on_drop", &self.should_abort_on_drop)
.finish_non_exhaustive()
}
}
impl<T> Drop for ServerTaskGuard<T> {
fn drop(&mut self) {
if self.should_abort_on_drop {
self.handle.abort();
}
}
}
#[cfg(test)]
mod tests {
use tokio::sync::oneshot;
use super::*;
type BodyError = Box<dyn std::error::Error + Send + Sync>;
fn spawn_pending_server() -> (ServerTaskGuard<()>, oneshot::Receiver<()>) {
let (sender, receiver) = oneshot::channel();
let handle = tokio::spawn(async move {
let _keep_alive = sender;
std::future::pending::<()>().await;
});
(ServerTaskGuard::new(handle), receiver)
}
fn is_reaped(receiver: &mut oneshot::Receiver<()>) -> bool {
matches!(
receiver.try_recv(),
Err(oneshot::error::TryRecvError::Closed)
)
}
async fn wait_until_reaped(receiver: &mut oneshot::Receiver<()>) {
for _ in 0..64 {
if is_reaped(receiver) {
return;
}
tokio::task::yield_now().await;
}
}
fn assert_reaped(receiver: &mut oneshot::Receiver<()>, context: &str) {
let outcome = receiver.try_recv();
assert!(
matches!(outcome, Err(oneshot::error::TryRecvError::Closed)),
"{context}: the server task must be dropped once the guard reaps it, got {outcome:?}"
);
}
#[tokio::test]
async fn run_and_join_returns_the_body_and_server_values() {
let handle = tokio::spawn(async { 7_u32 });
let (body_value, server_value) = ServerTaskGuard::new(handle)
.run_and_join(async { Ok::<_, BodyError>(5_u32) })
.await
.expect("join a completed server");
assert_eq!(body_value, 5, "the body value must be returned");
assert_eq!(server_value, 7, "the server value must be returned");
}
#[tokio::test]
async fn run_and_join_returns_a_body_error_and_reaps_the_server() {
let (guard, mut receiver) = spawn_pending_server();
let outcome = guard
.run_and_join(async { Err::<(), _>(std::io::Error::other("body failed")) })
.await;
let error = outcome.expect_err("a body error must be returned");
assert_eq!(
error.to_string(),
"body failed",
"the body error must survive"
);
assert_reaped(&mut receiver, "body error");
}
#[tokio::test]
async fn run_and_join_resumes_a_body_panic_after_reaping_the_server() {
let (guard, mut receiver) = spawn_pending_server();
let outcome = AssertUnwindSafe(
guard.run_and_join::<(), BodyError, _>(async { panic!("body panicked") }),
)
.catch_unwind()
.await;
let payload = outcome.expect_err("a body panic must be resumed");
let message = payload.downcast_ref::<&str>().copied();
assert_eq!(
message,
Some("body panicked"),
"the original panic payload must be resumed"
);
assert_reaped(&mut receiver, "body panic");
}
#[tokio::test]
async fn run_and_join_surfaces_a_server_panic_after_body_success() {
let handle = tokio::spawn(async { panic!("server panicked") });
let outcome = ServerTaskGuard::new(handle)
.run_and_join(async { Ok::<_, BodyError>(()) })
.await;
assert!(
outcome.is_err(),
"a server panic must fail the runner instead of reporting success"
);
}
#[tokio::test]
async fn run_and_abort_treats_cancellation_as_clean() {
let (guard, mut receiver) = spawn_pending_server();
let ((), server_value) = guard
.run_and_abort(async { Ok::<_, BodyError>(()) })
.await
.expect("aborting a pending server is a clean outcome");
assert!(server_value.is_none(), "an aborted server reports no value");
assert_reaped(&mut receiver, "aborted server");
}
#[tokio::test]
async fn run_and_abort_surfaces_a_server_panic() {
let (started, has_started) = oneshot::channel();
let handle = tokio::spawn(async move {
let _signalled = started.send(());
panic!("server panicked");
});
has_started.await.expect("the server task must start");
let outcome = ServerTaskGuard::new(handle)
.run_and_abort(async { Ok::<_, BodyError>(()) })
.await;
assert!(
outcome.is_err(),
"a server panic must not be mistaken for a clean abort"
);
}
#[tokio::test]
async fn abort_on_drop_stops_an_unreaped_server() {
let (guard, mut receiver) = spawn_pending_server();
drop(guard);
wait_until_reaped(&mut receiver).await;
assert_reaped(&mut receiver, "dropped guard");
}
}