1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::{
    future::poll_fn,
    sync::{Arc, Mutex},
    task::{Context, Poll},
};

use futures_core::future::BoxFuture;
use futures_util::FutureExt;
use hyper::body::Incoming;
use predawn_core::{
    error::Error, into_response::IntoResponse, request::Request, response::Response,
};
use tower::{Layer, Service};

use super::Middleware;
use crate::handler::Handler;

pub trait TowerLayerCompatExt: Sized {
    fn compat(self) -> TowerLayerCompatMiddleware<Self> {
        TowerLayerCompatMiddleware(self)
    }
}

impl<L> TowerLayerCompatExt for L {}

pub struct TowerLayerCompatMiddleware<L>(L);

impl<H, L> Middleware<H> for TowerLayerCompatMiddleware<L>
where
    H: Handler,
    L: Layer<HandlerToService<H>>,
    L::Service: Service<http::Request<Incoming>> + Send + Sync + 'static,
    <L::Service as Service<http::Request<Incoming>>>::Future: Send,
    <L::Service as Service<http::Request<Incoming>>>::Response: IntoResponse,
    <L::Service as Service<http::Request<Incoming>>>::Error: Into<Error>,
{
    type Output = ServiceToHandler<L::Service>;

    fn transform(self, input: H) -> Self::Output {
        let svc = self.0.layer(HandlerToService(Arc::new(input)));
        ServiceToHandler(Mutex::new(svc))
    }
}

pub struct HandlerToService<H>(Arc<H>);

impl<H> Service<http::Request<Incoming>> for HandlerToService<H>
where
    H: Handler,
{
    type Error = Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
    type Response = Response;

    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: http::Request<Incoming>) -> Self::Future {
        let handler = self.0.clone();

        let req = Request::try_from(req).expect("not found some element in request extensions");

        async move { handler.call(req).await }.boxed()
    }
}

pub struct ServiceToHandler<S>(Mutex<S>);

impl<S> Handler for ServiceToHandler<S>
where
    S: Service<http::Request<Incoming>> + Send + Sync + 'static,
    S::Response: IntoResponse,
    S::Error: Into<Error>,
    S::Future: Send,
{
    async fn call(&self, req: Request) -> Result<Response, Error> {
        let svc = &self.0;

        poll_fn(|cx| svc.lock().unwrap().poll_ready(cx))
            .await
            .map_err(Into::into)?;

        let fut = svc
            .lock()
            .unwrap()
            .call(http::Request::<Incoming>::from(req));

        Ok(fut.await.map_err(Into::into)?.into_response()?)
    }
}