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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//! compatibility between tower-http layer and xitca-web middleware.

use tower_layer::Layer;

use crate::service::{tower_http_compat::TowerCompatService, Service};

/// A middleware type that bridge `xitca-service` and `tower-service`.
/// Any `tower-http` type that impl [Layer] trait can be passed to it and used as xitca-web's middleware.
///
/// # Type mutation
/// `TowerHttpCompat` would mutate response body type from `B` to `CompatBody<ResB>`. Service enclosed
/// by it must be able to handle it's mutation or utilize [TypeEraser] to erase the mutation.
///
/// [TypeEraser]: crate::middleware::eraser::TypeEraser
#[derive(Clone)]
pub struct TowerHttpCompat<L>(L);

impl<L> TowerHttpCompat<L> {
    /// Construct a new xitca-web middleware from tower-http layer type.
    ///
    /// # Limitation:
    /// tower::Service::poll_ready implementation is ignored by TowerHttpCompat.
    /// if a tower Service is sensitive to poll_ready implementation it should not be used.
    ///
    /// # Example:
    /// ```rust
    /// # use std::convert::Infallible;
    /// # use xitca_web::{http::{StatusCode, WebResponse}, service::fn_service, App, WebContext};
    /// use xitca_web::middleware::tower_http_compat::TowerHttpCompat;
    /// use tower_http::set_status::SetStatusLayer;
    ///
    /// # fn doc_example() {
    /// App::new()
    ///     .at("/", fn_service(handler))
    ///     .enclosed(TowerHttpCompat::new(SetStatusLayer::new(StatusCode::NOT_FOUND)));
    /// # }
    ///
    /// # async fn handler(ctx: WebContext<'_>) -> Result<WebResponse, Infallible> {
    /// #   todo!()
    /// # }
    /// ```
    pub const fn new(layer: L) -> Self {
        Self(layer)
    }
}

impl<L, S, E> Service<Result<S, E>> for TowerHttpCompat<L>
where
    L: Layer<compat_layer::CompatLayer<S>>,
{
    type Response = TowerCompatService<L::Service>;
    type Error = E;

    async fn call(&self, res: Result<S, E>) -> Result<Self::Response, Self::Error> {
        res.map(|service| {
            let service = self.0.layer(compat_layer::CompatLayer::new(service));
            TowerCompatService::new(service)
        })
    }
}

mod compat_layer {
    use core::{
        cell::RefCell,
        future::Future,
        pin::Pin,
        task::{Context, Poll},
    };

    use std::rc::Rc;

    use crate::{
        http::{Request, RequestExt, Response, WebResponse},
        service::tower_http_compat::{CompatReqBody, CompatResBody},
        WebContext,
    };

    use super::*;

    pub struct CompatLayer<S>(Rc<S>);

    impl<S> CompatLayer<S> {
        pub(super) fn new(service: S) -> Self {
            Self(Rc::new(service))
        }
    }

    impl<S, C, ReqB, ResB, Err> tower_service::Service<Request<CompatReqBody<RequestExt<ReqB>, C>>> for CompatLayer<S>
    where
        S: for<'r> Service<WebContext<'r, C, ReqB>, Response = WebResponse<ResB>, Error = Err> + 'static,
        C: 'static,
        ReqB: 'static,
    {
        type Response = Response<CompatResBody<ResB>>;
        type Error = Err;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

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

        fn call(&mut self, req: Request<CompatReqBody<RequestExt<ReqB>, C>>) -> Self::Future {
            let service = self.0.clone();
            Box::pin(async move {
                let (parts, body) = req.into_parts();
                let (body, ctx) = body.into_parts();
                let (ext, body) = body.replace_body(());

                let mut req = Request::from_parts(parts, ext);
                let mut body = RefCell::new(body);
                let req = WebContext::new(&mut req, &mut body, &ctx);

                service.call(req).await.map(|res| res.map(CompatResBody::new))
            })
        }
    }
}

#[cfg(test)]
mod test {
    use core::convert::Infallible;

    use tower_http::set_status::SetStatusLayer;
    use xitca_unsafe_collection::futures::NowOrPanic;

    use crate::{
        body::ResponseBody,
        http::WebRequest,
        http::{StatusCode, WebResponse},
        service::fn_service,
        App, WebContext,
    };

    use super::*;

    async fn handler(ctx: WebContext<'_, &'static str>) -> Result<WebResponse, Infallible> {
        assert_eq!(*ctx.state(), "996");
        Ok(ctx.into_response(ResponseBody::empty()))
    }

    #[test]
    fn tower_set_status() {
        let res = App::new()
            .with_state("996")
            .at("/", fn_service(handler))
            .enclosed(TowerHttpCompat::new(SetStatusLayer::new(StatusCode::OK)))
            .enclosed(TowerHttpCompat::new(SetStatusLayer::new(StatusCode::NOT_FOUND)))
            .finish()
            .call(())
            .now_or_panic()
            .unwrap()
            .call(WebRequest::default())
            .now_or_panic()
            .unwrap();

        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }
}