1use 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#[derive(Clone)]
57pub struct AppRouter {
58 service: Arc<BoxedService>,
60}
61
62impl AppRouter {
63 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 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 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 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 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 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 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}