use std::{
any::Any,
future::Future,
panic::{AssertUnwindSafe, catch_unwind},
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use axum::body::Bytes;
use serde::de::DeserializeOwned;
use super::response::{IntoInvocationResponse, Response};
use crate::RequestContext;
pub(crate) type BoxError = Box<dyn std::error::Error + Send + Sync>;
type HandlerFuture = BoxFuture<Result<Response, HandlerError>>;
pub(crate) enum HandlerError {
Decode(serde_json::Error),
Failed(Failure),
Panicked(String),
}
pub(crate) struct Failure {
pub(crate) error: String,
pub(crate) causes: Option<String>,
}
impl Failure {
pub(crate) fn of(error: BoxError) -> Self {
let hides_source = |error: &(dyn std::error::Error + 'static)| {
error.downcast_ref::<crate::Error>().is_some_and(crate::Error::hides_source)
};
let mut causes = Vec::new();
let mut current: &(dyn std::error::Error + 'static) = error.as_ref();
while causes.len() < 8 && !hides_source(current) {
let Some(source) = current.source() else { break };
causes.push(source.to_string());
current = source;
}
Self { error: error.to_string(), causes: (!causes.is_empty()).then(|| causes.join(": ")) }
}
}
pub(crate) fn panic_text(panic: &(dyn Any + Send)) -> &str {
panic
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| panic.downcast_ref::<&str>().copied())
.unwrap_or("the panic has no text")
}
pub(crate) type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
pub(crate) struct CatchPanic<T>(pub(crate) Option<BoxFuture<T>>);
impl<T> Future for CatchPanic<T> {
type Output = Result<T, String>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let Some(future) = self.0.as_mut() else { return Poll::Ready(Err("polled after its end".to_owned())) };
match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
Ok(Poll::Pending) => Poll::Pending,
Ok(Poll::Ready(output)) => {
self.0 = None;
Poll::Ready(Ok(output))
}
Err(panic) => {
let future = self.0.take();
let _ = catch_unwind(AssertUnwindSafe(|| drop(future)));
Poll::Ready(Err(panic_text(panic.as_ref()).to_owned()))
}
}
}
}
mod sealed {
use super::*;
#[derive(Clone)]
pub struct Erased(pub(super) Arc<dyn Fn(Bytes, RequestContext) -> HandlerFuture + Send + Sync>);
impl Erased {
pub(crate) fn call(&self, body: Bytes, ctx: RequestContext) -> HandlerFuture {
(self.0)(body, ctx)
}
}
impl std::fmt::Debug for Erased {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Erased")
}
}
pub trait Sealed<Marker> {
fn erase(self) -> Erased;
}
}
pub(crate) use sealed::{Erased, Sealed};
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a valid invocation handler",
label = "not a valid invocation handler",
note = "a handler is an `async fn(Req) -> Result<O, E>` or an `async fn(Req, RequestContext) -> Result<O, E>`",
note = "`Req` must implement `serde::de::DeserializeOwned + Send`, and `RequestContext` is taken by value",
note = "`O` must implement `serde::Serialize`, or be a `runtime::Response`",
note = "`E` must convert into `Box<dyn std::error::Error + Send + Sync>`",
note = "the function and its future must be `Send`, and the function must be `Sync + 'static`"
)]
pub trait InvocationHandler<Marker>: Sealed<Marker> {}
impl<T: Sealed<Marker>, Marker> InvocationHandler<Marker> for T {}
fn erase<Req, Fut, O, E>(call: impl Fn(Req, RequestContext) -> Fut + Send + Sync + 'static) -> Erased
where
Req: DeserializeOwned + Send + 'static,
Fut: Future<Output = Result<O, E>> + Send + 'static,
O: IntoInvocationResponse,
E: Into<BoxError>,
{
let call = Arc::new(call);
Erased(Arc::new(move |body, ctx| {
let call = call.clone();
let guarded = CatchPanic(Some(Box::pin(async move {
let request = serde_json::from_slice(&body).map_err(HandlerError::Decode)?;
drop(body);
match call(request, ctx).await {
Ok(output) => Ok(output.into_invocation_response()),
Err(error) => Err(HandlerError::Failed(Failure::of(error.into()))),
}
})));
Box::pin(async move { guarded.await.unwrap_or_else(|panic| Err(HandlerError::Panicked(panic))) })
}))
}
impl<F, Fut, Req, O, E> Sealed<(Req,)> for F
where
F: Fn(Req) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O, E>> + Send + 'static,
Req: DeserializeOwned + Send + 'static,
O: IntoInvocationResponse,
E: Into<BoxError>,
{
fn erase(self) -> Erased {
erase(move |request, _ctx| self(request))
}
}
impl<F, Fut, Req, O, E> Sealed<(Req, RequestContext)> for F
where
F: Fn(Req, RequestContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O, E>> + Send + 'static,
Req: DeserializeOwned + Send + 'static,
O: IntoInvocationResponse,
E: Into<BoxError>,
{
fn erase(self) -> Erased {
erase(self)
}
}