Skip to main content

navree_http/
app.rs

1//! [`AppRouter`]: the app as one service, what [`build_router`] returns and
2//! what [`GlobalLayer`]s wrap.
3//!
4//! [`build_router`]: crate::build_router
5//! [`GlobalLayer`]: crate::GlobalLayer
6
7use std::convert::Infallible;
8use std::fmt;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12use std::task::{Context, Poll, ready};
13
14use bytes::Bytes;
15use http::Method;
16use http::header::{CONTENT_LENGTH, TRANSFER_ENCODING};
17use navree_kernel::BoxError;
18use pin_project_lite::pin_project;
19use tower::util::{BoxCloneSyncService, Oneshot};
20use tower::{Layer, Service, ServiceExt};
21
22use crate::body::{Body, HttpBody, try_downcast};
23use crate::extract::Request;
24use crate::handler::{BoxedService, Endpoint, Handler};
25use crate::response::{IntoResponse, Response};
26
27/// The app as one [`tower::Service`]: [`routing::Router`](crate::routing::Router)
28/// or any other service, wrapped in layers.
29///
30/// Layers run from the last added inward, like an onion. `AppRouter` is cheap
31/// to clone: a clone shares its stack. Call it as any tower service
32/// (`tower::ServiceExt::oneshot` in a test), or give it to
33/// [`serve()`](crate::serve()).
34///
35/// ```
36/// use http::Method;
37/// use http::header::{HeaderName, HeaderValue};
38/// use navree_http::AppRouter;
39/// use navree_http::extract::Request;
40/// use navree_http::middleware::{Next, from_fn};
41/// use navree_http::response::Response;
42/// use navree_http::routing::Router;
43///
44/// async fn stamp(request: Request, next: Next) -> Response {
45///     let mut response = next.run(request).await;
46///     response
47///         .headers_mut()
48///         .insert(HeaderName::from_static("x-stamp"), HeaderValue::from_static("1"));
49///     response
50/// }
51///
52/// let routes = Router::new().route(Method::GET, "/", || async { "hello" });
53/// let app = AppRouter::new(routes).layer(from_fn(stamp));
54/// # let _ = app;
55/// ```
56#[derive(Clone)]
57pub struct AppRouter {
58    // Shared, so a stack of layers clones in one step, not one per layer.
59    service: Arc<BoxedService>,
60}
61
62impl AppRouter {
63    /// `service` as an app.
64    pub fn new<S>(service: S) -> Self
65    where
66        S: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
67        S::Response: IntoResponse + 'static,
68        S::Future: Send + 'static,
69    {
70        try_downcast(service).unwrap_or_else(|service| Self {
71            service: Arc::new(try_downcast(service).unwrap_or_else(|service: S| {
72                BoxCloneSyncService::new(service.map_response(IntoResponse::into_response))
73            })),
74        })
75    }
76
77    /// An app that answers every request with `handler`, whatever its method
78    /// and path: a catch-all, such as a proxy.
79    pub fn from_handler<H, T>(handler: H) -> Self
80    where
81        H: Handler<T>,
82        T: 'static,
83    {
84        Self::new(Endpoint::new(handler).into_service())
85    }
86
87    /// Wraps the app in `layer`, which runs before everything added so far.
88    pub fn layer<L>(self, layer: L) -> Self
89    where
90        L: Layer<AppRouter>,
91        L::Service: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
92        <L::Service as Service<Request>>::Response: IntoResponse + 'static,
93        <L::Service as Service<Request>>::Future: Send + 'static,
94    {
95        Self::new(layer.layer(self))
96    }
97
98    /// Calls the app with `request`, without cloning the handle's service
99    /// first when nothing else shares it.
100    pub(crate) fn call_owned(self, request: Request) -> ResponseFuture {
101        let connect = request.method() == Method::CONNECT;
102        let service = Arc::unwrap_or_clone(self.service);
103        ResponseFuture {
104            inner: service.oneshot(request),
105            connect,
106        }
107    }
108}
109
110impl<B> Service<http::Request<B>> for AppRouter
111where
112    B: HttpBody<Data = Bytes> + Send + 'static,
113    B::Error: Into<BoxError>,
114{
115    type Response = Response;
116    type Error = Infallible;
117    type Future = ResponseFuture;
118
119    #[inline]
120    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
121        Poll::Ready(Ok(()))
122    }
123
124    fn call(&mut self, request: http::Request<B>) -> ResponseFuture {
125        self.clone().call_owned(request.map(Body::new))
126    }
127}
128
129impl From<crate::routing::Router> for AppRouter {
130    fn from(router: crate::routing::Router) -> Self {
131        Self::new(router)
132    }
133}
134
135impl fmt::Debug for AppRouter {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        f.debug_struct("AppRouter").finish_non_exhaustive()
138    }
139}
140
141pin_project! {
142    /// The future of a request to an [`AppRouter`].
143    pub struct ResponseFuture {
144        #[pin]
145        inner: Oneshot<BoxedService, Request>,
146        connect: bool,
147    }
148}
149
150impl Future for ResponseFuture {
151    type Output = Result<Response, Infallible>;
152
153    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
154        let this = self.project();
155        let mut response = ready!(this.inner.poll(cx))?;
156        // RFC 9110: a 2xx to CONNECT has no content, and the connection is a
157        // tunnel from here on.
158        if *this.connect
159            && response.status().is_success()
160            && (response.headers().contains_key(CONTENT_LENGTH)
161                || response.headers().contains_key(TRANSFER_ENCODING)
162                || response.body().size_hint().lower() != 0)
163        {
164            tracing::error!(target: "navree::http", "response to CONNECT with a body");
165            *response.body_mut() = Body::empty();
166        }
167        Poll::Ready(Ok(response))
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use std::sync::Mutex;
174
175    use http::{HeaderValue, StatusCode};
176    use http_body_util::BodyExt;
177    use tower::ServiceExt;
178
179    use super::*;
180    use crate::middleware::{Next, from_fn};
181    use crate::routing::Router;
182
183    fn get(uri: &str) -> Request {
184        http::Request::get(uri).body(Body::empty()).unwrap()
185    }
186
187    async fn text(response: Response) -> String {
188        let body = response.into_body().collect().await.unwrap().to_bytes();
189        String::from_utf8_lossy(&body).into_owned()
190    }
191
192    #[tokio::test]
193    async fn a_layer_added_later_runs_first() {
194        let order = Arc::new(Mutex::new(Vec::new()));
195        let step = |name: &'static str| {
196            let order = order.clone();
197            from_fn(move |request: Request, next: Next| {
198                let order = order.clone();
199                async move {
200                    order.lock().unwrap().push(name);
201                    let response = next.run(request).await;
202                    order.lock().unwrap().push(name);
203                    response
204                }
205            })
206        };
207        let app = AppRouter::new(Router::new().route(http::Method::GET, "/", || async { "hi" }))
208            .layer(step("inner"))
209            .layer(step("outer"));
210        let response = app.oneshot(get("/")).await.unwrap();
211        assert_eq!(text(response).await, "hi");
212        assert_eq!(*order.lock().unwrap(), ["outer", "inner", "inner", "outer"]);
213    }
214
215    #[tokio::test]
216    async fn a_service_is_taken_with_any_request_body() {
217        let app = AppRouter::from_handler(|body: String| async move { body });
218        let request = http::Request::post("/anything")
219            .body(http_body_util::Full::new(Bytes::from_static(b"sent")))
220            .unwrap();
221        let response = app.oneshot(request).await.unwrap();
222        assert_eq!(text(response).await, "sent");
223    }
224
225    #[tokio::test]
226    async fn a_handler_takes_every_method_and_path() {
227        let app = AppRouter::from_handler(|request: Request| async move {
228            format!("{} {}", request.method(), request.uri().path())
229        });
230        let request = http::Request::delete("/a/b").body(Body::empty()).unwrap();
231        let response = app.oneshot(request).await.unwrap();
232        assert_eq!(text(response).await, "DELETE /a/b");
233    }
234
235    #[tokio::test]
236    async fn a_2xx_to_connect_has_no_body() {
237        let app = AppRouter::from_handler(|| async { "tunnel" });
238        let connect = http::Request::connect("example.com:443")
239            .body(Body::empty())
240            .unwrap();
241        let response = app.clone().oneshot(connect).await.unwrap();
242        assert_eq!(response.status(), StatusCode::OK);
243        assert_eq!(text(response).await, "");
244
245        // Only a 2xx: a refusal keeps its body, and so does any other method.
246        let refused = AppRouter::from_handler(|| async {
247            (
248                StatusCode::FORBIDDEN,
249                [("x-why", HeaderValue::from_static("no"))],
250                "no",
251            )
252        });
253        let connect = http::Request::connect("example.com:443")
254            .body(Body::empty())
255            .unwrap();
256        let response = refused.oneshot(connect).await.unwrap();
257        assert_eq!(response.status(), StatusCode::FORBIDDEN);
258        assert_eq!(text(response).await, "no");
259        let response = app.oneshot(get("/")).await.unwrap();
260        assert_eq!(text(response).await, "tunnel");
261    }
262
263    #[test]
264    fn it_can_be_shared_between_threads() {
265        fn assert_shareable<T: Clone + Send + Sync + 'static>() {}
266        assert_shareable::<AppRouter>();
267    }
268}