use core::fmt;
use rama_error::{BoxError, ErrorExt, extra::OpaqueError};
use rama_utils::macros::define_inner_service_accessors;
use crate::{Layer, Service};
#[derive(Clone)]
pub struct MapErr<S, F> {
inner: S,
f: F,
}
impl<S, F> fmt::Debug for MapErr<S, F>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapErr")
.field("inner", &self.inner)
.field("f", &format_args!("{}", core::any::type_name::<F>()))
.finish()
}
}
#[derive(Clone)]
pub struct MapErrLayer<F> {
f: F,
}
impl<F> core::fmt::Debug for MapErrLayer<F> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("MapErrLayer")
.field("f", &format_args!("{}", core::any::type_name::<F>()))
.finish()
}
}
impl<S, F> MapErr<S, F> {
pub const fn new(inner: S, f: F) -> Self {
Self { f, inner }
}
define_inner_service_accessors!();
}
impl<S, Error> MapErr<S, fn(Error) -> BoxError>
where
Error: Into<BoxError>,
{
pub const fn into_box_error(inner: S) -> Self {
Self::new(inner, ErrorExt::into_box_error)
}
}
impl<S, Error> MapErr<S, fn(Error) -> OpaqueError>
where
Error: Into<BoxError>,
{
pub const fn into_opaque_error(inner: S) -> Self {
Self::new(inner, ErrorExt::into_opaque_error)
}
}
impl<S, F, Input, Error> Service<Input> for MapErr<S, F>
where
S: Service<Input>,
F: Fn(S::Error) -> Error + Send + Sync + 'static,
Input: Send + 'static,
Error: Send + 'static,
{
type Output = S::Output;
type Error = Error;
async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
match self.inner.serve(input).await {
Ok(resp) => Ok(resp),
Err(err) => Err((self.f)(err)),
}
}
}
impl<F> MapErrLayer<F> {
pub const fn new(f: F) -> Self {
Self { f }
}
}
impl<Error> MapErrLayer<fn(Error) -> BoxError>
where
BoxError: From<Error>,
{
pub const fn into_box_error() -> Self {
Self::new(BoxError::from)
}
}
impl<Error> MapErrLayer<fn(Error) -> OpaqueError>
where
BoxError: From<Error>,
{
pub const fn into_opaque_error() -> Self {
Self::new(|err| err.into_opaque_error())
}
}
impl<S, F> Layer<S> for MapErrLayer<F>
where
F: Clone,
{
type Service = MapErr<S, F>;
fn layer(&self, inner: S) -> Self::Service {
MapErr {
f: self.f.clone(),
inner,
}
}
fn into_layer(self, inner: S) -> Self::Service {
MapErr { f: self.f, inner }
}
}