Skip to main content

axum/
serve.rs

1//! Serve services.
2
3pub use tower_serve::{
4    serve, ConnLimiter, ConnLimiterIo, ConnectionLifetimeLimits, Executor, IncomingStream,
5    Listener, ListenerExt, MaxConnectionAge, Serve, TapIo, TokioExecutor, WithGracefulShutdown,
6};
7
8#[cfg(test)]
9mod tests {
10    use std::{future::IntoFuture as _, net::SocketAddr, time::Duration};
11
12    use axum_core::{body::Body, extract::Request};
13    use http::StatusCode;
14    use hyper_util::rt::TokioIo;
15    #[cfg(unix)]
16    use tokio::net::UnixListener;
17    use tokio::{
18        net::{TcpListener, TcpStream},
19        task::JoinHandle,
20    };
21
22    #[cfg(unix)]
23    use super::IncomingStream;
24    use super::{serve, ConnectionLifetimeLimits, ListenerExt, MaxConnectionAge};
25    #[cfg(unix)]
26    use crate::extract::connect_info::Connected;
27    use crate::{
28        body::to_bytes,
29        handler::{Handler, HandlerWithoutStateExt},
30        routing::get,
31        Router,
32    };
33
34    // Compile-only coverage of every axum make-service integration accepted by
35    // `serve` (`Router`, `MethodRouter`, `Handler` and their `into_make_service*`
36    // forms), plus `Connected<IncomingStream>` and `ListenerExt::tap_io`. The
37    // runtime behaviour of `serve` itself is tested in the `tower-serve` crate; this
38    // only guards the axum-specific type plumbing.
39    #[allow(dead_code, unused)]
40    async fn if_it_compiles_it_works() {
41        #[derive(Clone, Debug)]
42        struct UdsConnectInfo;
43
44        #[cfg(unix)]
45        impl Connected<IncomingStream<'_, UnixListener>> for UdsConnectInfo {
46            fn connect_info(_stream: IncomingStream<'_, UnixListener>) -> Self {
47                Self
48            }
49        }
50
51        let router: Router = Router::new();
52
53        let addr = "0.0.0.0:0";
54
55        let tcp_nodelay_listener = || async {
56            TcpListener::bind(addr).await.unwrap().tap_io(|tcp_stream| {
57                if let Err(err) = tcp_stream.set_nodelay(true) {
58                    eprintln!("failed to set TCP_NODELAY on incoming connection: {err:#}");
59                }
60            })
61        };
62
63        // router
64        serve(TcpListener::bind(addr).await.unwrap(), router.clone());
65        serve(tcp_nodelay_listener().await, router.clone()).await;
66        #[cfg(unix)]
67        serve(UnixListener::bind("").unwrap(), router.clone());
68
69        serve(
70            TcpListener::bind(addr).await.unwrap(),
71            router.clone().into_make_service(),
72        );
73        serve(
74            tcp_nodelay_listener().await,
75            router.clone().into_make_service(),
76        );
77        #[cfg(unix)]
78        serve(
79            UnixListener::bind("").unwrap(),
80            router.clone().into_make_service(),
81        );
82
83        serve(
84            TcpListener::bind(addr).await.unwrap(),
85            router
86                .clone()
87                .into_make_service_with_connect_info::<std::net::SocketAddr>(),
88        );
89        serve(
90            tcp_nodelay_listener().await,
91            router
92                .clone()
93                .into_make_service_with_connect_info::<std::net::SocketAddr>(),
94        );
95        #[cfg(unix)]
96        serve(
97            UnixListener::bind("").unwrap(),
98            router.into_make_service_with_connect_info::<UdsConnectInfo>(),
99        );
100
101        // method router
102        serve(TcpListener::bind(addr).await.unwrap(), get(handler));
103        serve(tcp_nodelay_listener().await, get(handler));
104        #[cfg(unix)]
105        serve(UnixListener::bind("").unwrap(), get(handler));
106
107        serve(
108            TcpListener::bind(addr).await.unwrap(),
109            get(handler).into_make_service(),
110        );
111        serve(
112            tcp_nodelay_listener().await,
113            get(handler).into_make_service(),
114        );
115        #[cfg(unix)]
116        serve(
117            UnixListener::bind("").unwrap(),
118            get(handler).into_make_service(),
119        );
120
121        serve(
122            TcpListener::bind(addr).await.unwrap(),
123            get(handler).into_make_service_with_connect_info::<std::net::SocketAddr>(),
124        );
125        serve(
126            tcp_nodelay_listener().await,
127            get(handler).into_make_service_with_connect_info::<std::net::SocketAddr>(),
128        );
129        #[cfg(unix)]
130        serve(
131            UnixListener::bind("").unwrap(),
132            get(handler).into_make_service_with_connect_info::<UdsConnectInfo>(),
133        );
134
135        // handler
136        serve(
137            TcpListener::bind(addr).await.unwrap(),
138            handler.into_service(),
139        );
140        serve(tcp_nodelay_listener().await, handler.into_service());
141        #[cfg(unix)]
142        serve(UnixListener::bind("").unwrap(), handler.into_service());
143
144        serve(
145            TcpListener::bind(addr).await.unwrap(),
146            handler.with_state(()),
147        );
148        serve(tcp_nodelay_listener().await, handler.with_state(()));
149        #[cfg(unix)]
150        serve(UnixListener::bind("").unwrap(), handler.with_state(()));
151
152        serve(
153            TcpListener::bind(addr).await.unwrap(),
154            handler.into_make_service(),
155        );
156        serve(tcp_nodelay_listener().await, handler.into_make_service());
157        #[cfg(unix)]
158        serve(UnixListener::bind("").unwrap(), handler.into_make_service());
159
160        serve(
161            TcpListener::bind(addr).await.unwrap(),
162            handler.into_make_service_with_connect_info::<std::net::SocketAddr>(),
163        );
164        serve(
165            tcp_nodelay_listener().await,
166            handler.into_make_service_with_connect_info::<std::net::SocketAddr>(),
167        );
168        #[cfg(unix)]
169        serve(
170            UnixListener::bind("").unwrap(),
171            handler.into_make_service_with_connect_info::<UdsConnectInfo>(),
172        );
173
174        // with_executor
175        let router: Router = Router::new();
176        let exec = TestExecutor::new();
177        serve(TcpListener::bind(addr).await.unwrap(), router.clone()).with_executor(exec.clone());
178        serve(TcpListener::bind(addr).await.unwrap(), router.clone())
179            .with_executor(exec.clone())
180            .with_graceful_shutdown(std::future::pending());
181        serve(TcpListener::bind(addr).await.unwrap(), router.clone())
182            .with_graceful_shutdown(std::future::pending())
183            .with_executor(exec.clone());
184        serve(TcpListener::bind(addr).await.unwrap(), get(handler)).with_executor(exec.clone());
185        serve(
186            TcpListener::bind(addr).await.unwrap(),
187            handler.into_make_service(),
188        )
189        .with_executor(exec);
190
191        // connection_lifetime_limits, composable with the other builder methods in any order
192        let limits = ConnectionLifetimeLimits::new().max_connection_age(
193            MaxConnectionAge::new(Duration::from_secs(60))
194                .jitter(Duration::from_secs(10))
195                .grace(Duration::from_secs(5)),
196        );
197        serve(TcpListener::bind(addr).await.unwrap(), router.clone())
198            .connection_lifetime_limits(limits.clone());
199        serve(TcpListener::bind(addr).await.unwrap(), router.clone())
200            .connection_lifetime_limits(limits.clone())
201            .with_graceful_shutdown(std::future::pending());
202        serve(TcpListener::bind(addr).await.unwrap(), router.clone())
203            .with_graceful_shutdown(std::future::pending())
204            .connection_lifetime_limits(limits.clone());
205        serve(TcpListener::bind(addr).await.unwrap(), router.clone())
206            .connection_lifetime_limits(limits.clone())
207            .with_executor(TestExecutor::new());
208    }
209
210    async fn handler() {}
211
212    #[derive(Clone)]
213    struct TestExecutor(std::sync::Arc<std::sync::atomic::AtomicUsize>);
214
215    impl TestExecutor {
216        fn new() -> Self {
217            Self(std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)))
218        }
219    }
220
221    impl super::Executor for TestExecutor {
222        fn execute<Fut>(&self, fut: Fut) -> JoinHandle<Fut::Output>
223        where
224            Fut: std::future::Future + Send + 'static,
225            Fut::Output: Send + 'static,
226        {
227            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
228            tokio::spawn(fut)
229        }
230    }
231
232    // Runtime check that a `Router` is served end-to-end through the re-exported
233    // `axum::serve` over a real TCP connection. This exercises `Router`'s
234    // `Service<IncomingStream>` make-service path, which the `TestClient`-based
235    // tests bypass by wrapping services in `tower::make::Shared`.
236    #[crate::test]
237    async fn serve_router_over_tcp() {
238        let app = Router::new().route("/", get(|| async { "Hello, World!" }));
239
240        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
241        let addr = listener.local_addr().unwrap();
242        tokio::spawn(serve(listener, app).into_future());
243
244        let stream = TokioIo::new(TcpStream::connect(addr).await.unwrap());
245        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
246        tokio::spawn(conn);
247
248        let request = Request::builder().body(Body::empty()).unwrap();
249        let response = sender.send_request(request).await.unwrap();
250        assert_eq!(response.status(), StatusCode::OK);
251
252        let body = to_bytes(Body::new(response.into_body()), usize::MAX)
253            .await
254            .unwrap();
255        assert_eq!(&body[..], b"Hello, World!");
256    }
257
258    // `serve(listener, router)` used to run `self.clone().with_state(())` on
259    // every accepted connection. The `Arc` behind `Router` is shared with
260    // `serve`, so that fell back to deep-cloning every route's service for each
261    // connection and kept the copy alive for as long as the connection was open.
262    #[crate::test]
263    async fn new_connection_does_not_clone_route_services() {
264        use std::{
265            convert::Infallible,
266            future::{ready, Ready},
267            sync::{
268                atomic::{AtomicUsize, Ordering},
269                Arc,
270            },
271            task::{Context, Poll},
272        };
273
274        use axum_core::response::IntoResponse;
275        use tower_service::Service;
276
277        struct Svc(Arc<AtomicUsize>);
278
279        impl Clone for Svc {
280            fn clone(&self) -> Self {
281                self.0.fetch_add(1, Ordering::SeqCst);
282                Self(self.0.clone())
283            }
284        }
285
286        impl Service<Request> for Svc {
287            type Response = crate::response::Response;
288            type Error = Infallible;
289            type Future = Ready<Result<Self::Response, Infallible>>;
290
291            fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
292                Poll::Ready(Ok(()))
293            }
294
295            fn call(&mut self, _req: Request) -> Self::Future {
296                ready(Ok("ok".into_response()))
297            }
298        }
299
300        async fn connect(
301            addr: std::net::SocketAddr,
302        ) -> hyper::client::conn::http1::SendRequest<Body> {
303            let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
304            let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
305                .await
306                .unwrap();
307            tokio::spawn(conn);
308            sender
309        }
310
311        async fn clones_during(
312            sender: &mut hyper::client::conn::http1::SendRequest<Body>,
313            clones: &AtomicUsize,
314        ) -> usize {
315            let before = clones.load(Ordering::SeqCst);
316            let request = Request::builder().uri("/").body(Body::empty()).unwrap();
317            let response = sender.send_request(request).await.unwrap();
318            assert_eq!(response.status(), StatusCode::OK);
319            clones.load(Ordering::SeqCst) - before
320        }
321
322        let clones = Arc::new(AtomicUsize::new(0));
323        let app = Router::new().route_service("/", Svc(clones.clone()));
324
325        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
326        let addr = listener.local_addr().unwrap();
327        tokio::spawn(serve(listener, app).into_future());
328
329        let mut first = connect(addr).await;
330        clones_during(&mut first, &clones).await;
331        let per_request = clones_during(&mut first, &clones).await;
332
333        let mut second = connect(addr).await;
334        let first_request_on_new_connection = clones_during(&mut second, &clones).await;
335
336        assert_eq!(first_request_on_new_connection, per_request);
337    }
338
339    #[crate::test]
340    async fn serving_with_connect_info_over_tcp() {
341        use crate::extract::ConnectInfo;
342
343        async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
344            addr.to_string()
345        }
346
347        let app = Router::new().route("/", get(handler));
348
349        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
350        let server = serve(
351            listener,
352            app.into_make_service_with_connect_info::<SocketAddr>(),
353        );
354        let server_addr = server.local_addr().unwrap();
355        tokio::spawn(server.into_future());
356
357        let client = TcpStream::connect(server_addr).await.unwrap();
358        let client_addr = client.local_addr().unwrap();
359
360        let stream = TokioIo::new(client);
361        let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap();
362        tokio::spawn(conn);
363
364        let request = Request::builder().body(Body::empty()).unwrap();
365        let response = sender.send_request(request).await.unwrap();
366        assert_eq!(response.status(), StatusCode::OK);
367
368        let body = to_bytes(Body::new(response.into_body()), usize::MAX)
369            .await
370            .unwrap();
371        let body = String::from_utf8(body.to_vec()).unwrap();
372        assert_eq!(body.parse::<SocketAddr>().unwrap(), client_addr);
373    }
374}