Skip to main content

next_rust_server/
server.rs

1//! Production HTTP server built on hyper.
2//!
3//! * HTTP/1.1 with keep-alive and HTTP/2 (h2c, and via TLS-terminating
4//!   proxies) using hyper's automatic protocol detection.
5//! * Header read timeout (slowloris protection) and request timeouts.
6//! * Graceful shutdown on SIGINT/SIGTERM.
7//! * gzip compression for compressible responses, including streams.
8//!
9//! TLS and HTTP/3 are expected to be terminated by a reverse proxy or load
10//! balancer (see the "Deployment" docs page).
11
12use std::convert::Infallible;
13use std::net::SocketAddr;
14use std::time::{Duration, Instant};
15
16use bytes::Bytes;
17use futures_util::StreamExt;
18use http_body_util::combinators::UnsyncBoxBody;
19use http_body_util::{BodyExt, Empty, Full, StreamBody};
20use hyper::body::{Frame, Incoming};
21#[cfg(feature = "http2")]
22use hyper_util::rt::TokioExecutor;
23use hyper_util::rt::{TokioIo, TokioTimer};
24#[cfg(feature = "http2")]
25use hyper_util::server::conn::auto;
26use tokio::net::TcpListener;
27
28use crate::app::App;
29use crate::request::{BoxError, Request};
30use crate::response::{Body, Response};
31
32pub type HyperBody = UnsyncBoxBody<Bytes, BoxError>;
33
34impl App {
35    /// Bind to the configured address and serve until shutdown.
36    pub async fn serve(self) -> std::io::Result<()> {
37        let addr = self.config().socket_addr_string();
38        let listener = TcpListener::bind(&addr).await.map_err(|e| {
39            std::io::Error::new(
40                e.kind(),
41                format!("could not bind {addr}: {e} (is another server running? set PORT to change the port)"),
42            )
43        })?;
44        self.serve_listener(listener).await
45    }
46
47    /// Serve on an existing listener (tests, socket activation).
48    pub async fn serve_listener(self, listener: TcpListener) -> std::io::Result<()> {
49        let local = listener.local_addr()?;
50        let config = self.inner.config.clone();
51        let banner = crate::banner::enabled(self.environment());
52        if banner {
53            crate::banner::started(local, self.inner.routes.pages.len(), self.inner.routes.apis.len());
54        } else {
55            crate::log::info(&format!(
56                "ready on http://{}:{} ({}, {} routes)",
57                if local.ip().is_unspecified() { "localhost".to_string() } else { local.ip().to_string() },
58                local.port(),
59                self.environment().as_str(),
60                self.inner.routes.pages.len() + self.inner.routes.apis.len()
61            ));
62        }
63
64        let header_timeout = Duration::from_secs(config.server.header_timeout.max(1));
65        #[cfg(feature = "http2")]
66        let builder = {
67            let mut builder = auto::Builder::new(TokioExecutor::new());
68            builder.http1().timer(TokioTimer::new()).header_read_timeout(header_timeout).keep_alive(true);
69            if config.server.http2 {
70                builder.http2().timer(TokioTimer::new()).keep_alive_interval(Duration::from_secs(20));
71            } else {
72                builder = builder.http1_only();
73            }
74            builder
75        };
76        #[cfg(not(feature = "http2"))]
77        let builder = {
78            if config.server.http2 {
79                crate::log::warn("[server] http2 = true needs the `http2` feature of next-rust; serving HTTP/1.1");
80            }
81            let mut builder = hyper::server::conn::http1::Builder::new();
82            builder.timer(TokioTimer::new()).header_read_timeout(header_timeout).keep_alive(true);
83            builder
84        };
85        // Every connection task holds a receiver: sending tells them to finish
86        // gracefully, and `closed()` resolves once all of them are done.
87        let (graceful, _) = tokio::sync::watch::channel(());
88        let shutdown = shutdown_signal();
89        tokio::pin!(shutdown);
90
91        loop {
92            tokio::select! {
93                accepted = listener.accept() => {
94                    let (stream, remote) = match accepted {
95                        Ok(v) => v,
96                        Err(e) => {
97                            crate::log::warn(&format!("accept failed: {e}"));
98                            tokio::time::sleep(Duration::from_millis(50)).await;
99                            continue;
100                        }
101                    };
102                    let _ = stream.set_nodelay(true);
103                    let app = self.clone();
104                    let service = hyper::service::service_fn(move |req: hyper::Request<Incoming>| {
105                        let app = app.clone();
106                        async move { Ok::<_, Infallible>(app.handle_hyper(req, Some(remote)).await) }
107                    });
108                    #[cfg(feature = "http2")]
109                    let conn = builder.serve_connection_with_upgrades(TokioIo::new(stream), service).into_owned();
110                    #[cfg(not(feature = "http2"))]
111                    let conn = builder.serve_connection(TokioIo::new(stream), service).with_upgrades();
112                    let mut stop = graceful.subscribe();
113                    tokio::spawn(async move {
114                        let mut conn = std::pin::pin!(conn);
115                        let result = tokio::select! {
116                            result = conn.as_mut() => result,
117                            _ = stop.changed() => {
118                                conn.as_mut().graceful_shutdown();
119                                conn.await
120                            }
121                        };
122                        if let Err(e) = result {
123                            crate::log::debug(&format!("connection error: {e}"));
124                        }
125                        drop(stop);
126                    });
127                }
128                _ = &mut shutdown => {
129                    if banner {
130                        crate::banner::stopping();
131                    }
132                    crate::log::info("shutting down gracefully");
133                    break;
134                }
135            }
136        }
137        let wait = Duration::from_secs(config.server.shutdown_timeout);
138        tokio::select! {
139            _ = async {
140                let _ = graceful.send(());
141                graceful.closed().await;
142            } => {}
143            _ = tokio::time::sleep(wait) => crate::log::warn("shutdown timeout: closing remaining connections"),
144        }
145        if banner {
146            crate::banner::stopped();
147        }
148        Ok(())
149    }
150
151    /// Handle a hyper request (used by the built-in server).
152    pub async fn handle_hyper(
153        &self,
154        req: hyper::Request<Incoming>,
155        remote: Option<SocketAddr>,
156    ) -> hyper::Response<HyperBody> {
157        let start = Instant::now();
158        let config = &self.inner.config;
159        let (parts, body) = req.into_parts();
160        let method = parts.method.clone();
161        let path = parts.uri.path().to_owned();
162        let accept_encoding = parts.headers.get("accept-encoding").and_then(|v| v.to_str().ok()).map(str::to_owned);
163        let body = body.map_err(|e| Box::new(e) as BoxError).boxed_unsync();
164        let request = Request::from_parts(parts, body, remote, config.server.body_limit, !self.environment().is_dev());
165
166        let timeout = config.server.request_timeout;
167        let res = if timeout > 0 {
168            match tokio::time::timeout(Duration::from_secs(timeout), self.handle(request)).await {
169                Ok(r) => r,
170                Err(_) => Response::text("Gateway Timeout").with_status(504),
171            }
172        } else {
173            self.handle(request).await
174        };
175
176        if config.logging.requests(self.environment()) && !path.starts_with("/_nr/dev/") {
177            let id = res.header("x-request-id").map(str::to_owned);
178            crate::log::request(
179                method.as_str(),
180                &path,
181                res.status.as_u16(),
182                start.elapsed().as_secs_f64() * 1000.0,
183                id.as_deref(),
184            );
185        }
186        let res = if config.server.compression { compress(res, accept_encoding.as_deref()) } else { res };
187        into_hyper(res)
188    }
189}
190
191/// Convert a framework response into a hyper response.
192pub fn into_hyper(res: Response) -> hyper::Response<HyperBody> {
193    let body: HyperBody = match res.body {
194        Body::Empty => Empty::new().map_err(|never| match never {}).boxed_unsync(),
195        Body::Bytes(b) => Full::new(b).map_err(|never| match never {}).boxed_unsync(),
196        Body::Stream(s) => StreamBody::new(s.map(|r| r.map(Frame::data))).boxed_unsync(),
197    };
198    let mut out = hyper::Response::new(body);
199    *out.status_mut() = res.status;
200    *out.headers_mut() = res.headers;
201    out
202}
203
204async fn shutdown_signal() {
205    let ctrl_c = async {
206        let _ = tokio::signal::ctrl_c().await;
207    };
208    #[cfg(unix)]
209    let terminate = async {
210        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
211            Ok(mut s) => {
212                s.recv().await;
213            }
214            Err(_) => std::future::pending::<()>().await,
215        }
216    };
217    #[cfg(not(unix))]
218    let terminate = std::future::pending::<()>();
219    tokio::select! {
220        _ = ctrl_c => {}
221        _ = terminate => {}
222    }
223}
224
225#[cfg(feature = "compression")]
226fn accepts_gzip(header: Option<&str>) -> bool {
227    header.is_some_and(|h| {
228        h.split(',').any(|part| {
229            let mut it = part.trim().split(';');
230            let coding = it.next().unwrap_or("").trim();
231            let q = it.find_map(|p| p.trim().strip_prefix("q=")).and_then(|q| q.parse::<f32>().ok()).unwrap_or(1.0);
232            (coding.eq_ignore_ascii_case("gzip") || coding == "*") && q > 0.0
233        })
234    })
235}
236
237#[cfg(feature = "compression")]
238pub(crate) fn compress(mut res: Response, accept_encoding: Option<&str>) -> Response {
239    use std::io::Write;
240
241    use flate2::Compression;
242    use flate2::write::GzEncoder;
243
244    let ct = res.header("content-type").unwrap_or("");
245    let eligible = accepts_gzip(accept_encoding)
246        && !res.headers.contains_key("content-encoding")
247        && res.status != http::StatusCode::PARTIAL_CONTENT
248        && res.status != http::StatusCode::NOT_MODIFIED
249        && !ct.starts_with("text/event-stream")
250        && next_rust_assets::mime::is_compressible(ct);
251    if !eligible {
252        return res;
253    }
254    match std::mem::replace(&mut res.body, Body::Empty) {
255        Body::Bytes(b) if b.len() >= 1024 => {
256            let mut enc = GzEncoder::new(Vec::with_capacity(b.len() / 3), Compression::fast());
257            if enc.write_all(&b).is_err() {
258                res.body = Body::Bytes(b);
259                return res;
260            }
261            match enc.finish() {
262                Ok(out) => {
263                    res.body = Body::Bytes(Bytes::from(out));
264                    res.headers.remove("content-length");
265                    res.set_header("content-encoding", "gzip");
266                    res.append_header("vary", "Accept-Encoding");
267                }
268                Err(_) => res.body = Body::Bytes(b),
269            }
270        }
271        Body::Stream(stream) => {
272            // Each chunk is compressed and sync-flushed so streamed HTML still
273            // reaches the browser progressively.
274            let state = (stream, Some(GzEncoder::new(Vec::new(), Compression::fast())));
275            let compressed = futures_util::stream::unfold(state, |(mut stream, enc)| async move {
276                let mut enc = enc?;
277                match stream.next().await {
278                    Some(Ok(chunk)) => {
279                        if enc.write_all(&chunk).is_err() || enc.flush().is_err() {
280                            return Some((Err::<Bytes, BoxError>("gzip failure".into()), (stream, None)));
281                        }
282                        let out = std::mem::take(enc.get_mut());
283                        Some((Ok(Bytes::from(out)), (stream, Some(enc))))
284                    }
285                    Some(Err(e)) => Some((Err(e), (stream, None))),
286                    None => match enc.finish() {
287                        Ok(tail) => Some((Ok(Bytes::from(tail)), (stream, None))),
288                        Err(e) => Some((Err(e.into()), (stream, None))),
289                    },
290                }
291            });
292            res.body = Body::Stream(Box::pin(compressed));
293            res.headers.remove("content-length");
294            res.set_header("content-encoding", "gzip");
295            res.append_header("vary", "Accept-Encoding");
296        }
297        other => res.body = other,
298    }
299    res
300}
301
302#[cfg(not(feature = "compression"))]
303pub(crate) fn compress(res: Response, _accept_encoding: Option<&str>) -> Response {
304    res
305}