use std::convert::Infallible;
use std::task::{Context, Poll};
use bytes::Bytes;
use navree_kernel::{BoxError, BoxFuture};
use tower::{Layer, Service, ServiceExt};
use crate::body::{Body, HttpBody};
use crate::error::AppError;
use crate::extract::Request;
use crate::response::{IntoResponse, Response};
#[derive(Clone, Debug)]
pub struct FallibleLayer<L> {
layer: L,
}
impl<L> FallibleLayer<L> {
pub fn new(layer: L) -> FallibleLayer<L> {
FallibleLayer { layer }
}
}
impl<S, L, B> Layer<S> for FallibleLayer<L>
where
L: Layer<S>,
L::Service: Service<Request, Response = http::Response<B>> + Clone + Send + Sync + 'static,
<L::Service as Service<Request>>::Error: Into<BoxError>,
<L::Service as Service<Request>>::Future: Send + 'static,
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
type Service = FallibleService<L::Service>;
fn layer(&self, inner: S) -> Self::Service {
FallibleService {
inner: self.layer.layer(inner),
}
}
}
#[derive(Clone, Debug)]
pub struct FallibleService<S> {
inner: S,
}
impl<S, B> Service<Request> for FallibleService<S>
where
S: Service<Request, Response = http::Response<B>> + Clone + Send + Sync + 'static,
S::Error: Into<BoxError>,
S::Future: Send + 'static,
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
#[inline]
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request) -> Self::Future {
let service = self.inner.clone();
Box::pin(async move {
Ok(match service.oneshot(request).await {
Ok(response) => response.map(Body::new),
Err(error) => AppError::internal(error).into_response(),
})
})
}
}