Skip to main content

webserver_base/webserver/
server.rs

1//! The web server builder.
2
3use std::future::Future;
4use std::net::{IpAddr, SocketAddr};
5use std::path::PathBuf;
6use std::str::FromStr;
7
8use crate::traces::UpstreamFailure;
9use axum::Router;
10use axum::extract::DefaultBodyLimit;
11use axum::http::StatusCode;
12use axum::response::{IntoResponse, Response};
13use axum::routing::get;
14use tokio::net::TcpListener;
15use tower_http::CompressionLevel;
16use tower_http::LatencyUnit;
17use tower_http::classify::{
18    ClassifiedResponse, ClassifyResponse, MakeClassifier, NeverClassifyEos, ServerErrorsAsFailures,
19    ServerErrorsFailureClass,
20};
21use tower_http::compression::CompressionLayer;
22use tower_http::compression::predicate::{DefaultPredicate, NotForContentType, Predicate};
23use tower_http::trace::{DefaultOnResponse, TraceLayer};
24use tracing::{Level, error, info, instrument, warn};
25
26use crate::env;
27use crate::environment::Environment;
28
29use super::connections::{self, ConnectionLimits};
30use super::error::WebServerError;
31use super::shutdown::{AppShutdown, DEFAULT_DRAIN_TIMEOUT, Shutdown};
32use super::state::{StateParts, WebServerState};
33use super::telemetry;
34
35/// The environment variable holding the bind host.
36pub const ENV_HOST: &str = "WSB_HOST";
37
38/// The environment variable holding the bind port.
39pub const ENV_PORT: &str = "WSB_PORT";
40
41/// The port used when [`ENV_PORT`] is unset.
42pub const DEFAULT_PORT: u16 = 8080;
43
44/// The request body ceiling used when none is set.
45///
46/// 256 KiB comfortably covers a form post or a JSON payload while still
47/// bounding abuse. A project that accepts uploads raises it explicitly.
48pub const DEFAULT_BODY_LIMIT: usize = 256 * 1024;
49
50/// The prefix every built-in endpoint is nested under.
51///
52/// Fixed rather than configurable: every route in every project is then
53/// predictable from the outside, and the derived analytics endpoint can be
54/// stated in the documentation without qualification.
55pub const API_PREFIX: &str = "/api/v1";
56
57/// An HTTP server.
58///
59/// Requires only an address, a port and an [`Environment`]. A sidecar that
60/// serves nothing but its health check is a valid server; a full site adds
61/// [`frontend`](WebServer::frontend). A single binary can run several of these
62/// and drain them from one [`Shutdown`].
63pub struct WebServer<S = ()> {
64    host: String,
65    port: u16,
66    environment: Environment,
67    app: S,
68
69    body_limit: usize,
70    compression: bool,
71    security: Option<super::security::SecurityHeaders>,
72    limits: ConnectionLimits,
73    root_dir: PathBuf,
74    router: Router<WebServerState<S>>,
75    /// Prefixes of the project's own [`Self::nest_service`] services, never traced.
76    nested: Vec<String>,
77
78    #[cfg(feature = "pages")]
79    frontend: Option<super::frontend::FrontendParams<S>>,
80
81    /// Gated on `pages` rather than `feed`: a feed without a frontend is a
82    /// boot failure, so the two always travel together.
83    #[cfg(feature = "pages")]
84    feed: Option<crate::feed::Feed>,
85}
86
87impl WebServer<()> {
88    /// A server with no application state.
89    #[must_use]
90    pub fn new(host: impl Into<String>, port: u16, environment: Environment) -> Self {
91        Self::with_state(host, port, environment, ())
92    }
93
94    /// A server with no application state, read entirely from the environment.
95    ///
96    /// `WSB_ENVIRONMENT` is required. `WSB_HOST` defaults to `127.0.0.1`
97    /// locally and `0.0.0.0` in production; `WSB_PORT` defaults to
98    /// [`DEFAULT_PORT`].
99    ///
100    /// # Errors
101    ///
102    /// [`WebServerError::Env`] if a variable is missing or malformed.
103    pub fn from_env() -> Result<Self, WebServerError> {
104        Self::from_env_with_state(())
105    }
106}
107
108impl<S> WebServer<S>
109where
110    S: Clone + Send + Sync + 'static,
111{
112    /// A server carrying application state.
113    #[must_use]
114    pub fn with_state(
115        host: impl Into<String>,
116        port: u16,
117        environment: Environment,
118        app: S,
119    ) -> Self {
120        Self {
121            host: host.into(),
122            port,
123            environment,
124            app,
125            body_limit: DEFAULT_BODY_LIMIT,
126            compression: true,
127            security: Some(super::security::SecurityHeaders::new()),
128            limits: ConnectionLimits::new(),
129            // Empty joins to the bare relative path: the working directory.
130            root_dir: PathBuf::new(),
131            router: Router::new(),
132            nested: Vec::new(),
133            #[cfg(feature = "pages")]
134            frontend: None,
135            #[cfg(feature = "pages")]
136            feed: None,
137        }
138    }
139
140    /// A server carrying application state, read entirely from the
141    /// environment.
142    ///
143    /// # Errors
144    ///
145    /// [`WebServerError::Env`] if a variable is missing or malformed.
146    pub fn from_env_with_state(app: S) -> Result<Self, WebServerError> {
147        let environment: Environment = Environment::from_env()?;
148        let host: String = env::optional(ENV_HOST).unwrap_or_else(|| {
149            if environment.is_production() {
150                String::from("0.0.0.0")
151            } else {
152                String::from("127.0.0.1")
153            }
154        });
155        let port: u16 =
156            env::parse_or(ENV_PORT, "port number", DEFAULT_PORT).map_err(WebServerError::Env)?;
157
158        Ok(Self::with_state(host, port, environment, app))
159    }
160
161    /// Caps request bodies. Defaults to [`DEFAULT_BODY_LIMIT`].
162    ///
163    /// The one size that genuinely varies: an image-upload endpoint and a
164    /// landing page have nothing in common here.
165    #[must_use]
166    pub const fn body_limit(mut self, body_limit: usize) -> Self {
167        self.body_limit = body_limit;
168        self
169    }
170
171    /// Replaces the browser security headers every server sends by default
172    /// ([`SecurityHeaders::new`](super::SecurityHeaders::new)): `nosniff`, a referrer policy, a
173    /// permissions policy, no framing, and optionally a Content-Security-Policy with a
174    /// per-response script nonce. The whole set is replaced, so start from
175    /// `SecurityHeaders::new()` and change what the site needs. See
176    /// [`SecurityHeaders`](super::SecurityHeaders).
177    #[must_use]
178    pub fn security_headers(mut self, headers: super::security::SecurityHeaders) -> Self {
179        self.security = Some(headers);
180        self
181    }
182
183    /// Sends no browser security headers at all. Rarely right: every server sends them by
184    /// default, and a site that needs framing or a device permission should loosen only that
185    /// through [`security_headers`](Self::security_headers) instead.
186    #[must_use]
187    pub fn without_security_headers(mut self) -> Self {
188        self.security = None;
189        self
190    }
191
192    /// Turns response compression off. On by default.
193    ///
194    /// Every response a client accepts compressed (zstd, brotli or gzip) is,
195    /// unless it is small, already compressed, an image, a range, or an event
196    /// or NDJSON stream. A route that streams any other type must set an exempt
197    /// `Content-Type` or the encoder buffers it; or use this to opt out.
198    /// Turn it off when a proxy in front already compresses and the origin's
199    /// CPU matters more than its bandwidth.
200    #[must_use]
201    pub const fn without_compression(mut self) -> Self {
202        self.compression = false;
203        self
204    }
205
206    /// The header read (and keep-alive idle) timeout and the connection cap.
207    /// Defaults to [`ConnectionLimits::new`]: 30 seconds and 4096 connections.
208    ///
209    /// Without them a slow or silent client holds its socket forever, and a
210    /// burst of slow requests runs the process out of file descriptors.
211    #[must_use]
212    pub const fn connection_limits(mut self, limits: ConnectionLimits) -> Self {
213        self.limits = limits;
214        self
215    }
216
217    /// Where `html/`, `static/` and `cache-buster.json` are read from.
218    /// Defaults to the working directory.
219    ///
220    /// Covers every file the server reads, at boot and per request. It does
221    /// not move the build-time asset pipeline, which always runs in the working
222    /// directory. Set it when the process cannot run from the built site: a
223    /// `cargo test` runs from its crate's directory, not from `bin/`.
224    #[must_use]
225    pub fn root_dir(mut self, root_dir: impl Into<PathBuf>) -> Self {
226        self.root_dir = root_dir.into();
227        self
228    }
229
230    /// Nests a router under `path`.
231    #[must_use]
232    pub fn nest(mut self, path: &str, router: Router<WebServerState<S>>) -> Self {
233        self.router = self.router.nest(path, router);
234        self
235    }
236
237    /// Merges a router at the root.
238    #[must_use]
239    pub fn merge(mut self, router: Router<WebServerState<S>>) -> Self {
240        self.router = self.router.merge(router);
241        self
242    }
243
244    /// Nests a service under `path`.
245    #[must_use]
246    pub fn nest_service<T>(mut self, path: &str, service: T) -> Self
247    where
248        T: tower::Service<axum::extract::Request, Error = std::convert::Infallible>
249            + Clone
250            + Send
251            + Sync
252            + 'static,
253        T::Response: axum::response::IntoResponse,
254        T::Future: Send + 'static,
255    {
256        self.router = self.router.nest_service(path, service);
257        self.nested.push(path.trim_end_matches('/').to_owned());
258        self
259    }
260
261    /// Declares this server a frontend: it serves HTML to humans.
262    ///
263    /// This is the line between a site and a service, and everything downstream
264    /// hangs off it — the embedded layout, the icon set, the web manifest,
265    /// `robots.txt`, the sitemaps, analytics and browser error monitoring. A
266    /// server that never calls it needs none of them and boots clean.
267    #[cfg(feature = "pages")]
268    #[must_use]
269    pub fn frontend(mut self, params: super::frontend::FrontendParams<S>) -> Self {
270        self.frontend = Some(params);
271        self
272    }
273
274    /// Gives this site a feed, served as RSS 2.0, Atom 1.0 and JSON Feed.
275    ///
276    /// Omittable, because most sites publish no stream: a site that never calls
277    /// this serves no feed documents and emits no autodiscovery links. Requires
278    /// [`frontend`](WebServer::frontend) — calling this without it fails the
279    /// boot rather than silently serving nothing.
280    ///
281    /// Entries are supplied rather than derived: a blog is a
282    /// [`dynamic_page_group`](Pages::dynamic_page_group), and a dynamic page
283    /// builds its template data per request, so there is nothing to read at
284    /// boot. They may be in any order and may exceed
285    /// [`MAX_FEED_ENTRIES`](crate::feed::MAX_FEED_ENTRIES); the newest survive.
286    #[cfg(feature = "pages")]
287    #[must_use]
288    pub fn feed(mut self, feed: crate::feed::Feed) -> Self {
289        self.feed = Some(feed);
290        self
291    }
292
293    /// The finished application, without binding a socket.
294    ///
295    /// Exactly the router [`run`](WebServer::run) serves — pages, the 404, the
296    /// well-known documents, the cache policy, tracing and the body limit — so
297    /// driving it with `tower::ServiceExt::oneshot` tests what ships. Boot
298    /// validation runs here too: `Ok` is a server `run` would have started.
299    ///
300    /// It never runs the drain window or [`AppShutdown::on_shutdown`];
301    /// triggering `shutdown` reaches only handlers that listen for it. A
302    /// `.layer()` added on top of the result is outside what this library
303    /// guarantees.
304    ///
305    /// # Errors
306    ///
307    /// [`WebServerError`] if the frontend cannot be assembled.
308    pub fn into_router(self, shutdown: Shutdown) -> Result<Router, WebServerError> {
309        Ok(self.assemble(shutdown)?.router)
310    }
311
312    /// Binds, serves, and drains.
313    ///
314    /// # Errors
315    ///
316    /// [`WebServerError`] if the host is unparseable, the port cannot be bound,
317    /// the frontend cannot be assembled, or serving fails.
318    #[instrument(skip_all)]
319    pub async fn run(self, shutdown: Shutdown) -> Result<(), WebServerError>
320    where
321        S: AppShutdown,
322    {
323        let Assembled {
324            router,
325            state,
326            host,
327            port,
328            environment,
329            limits,
330        } = self.assemble(shutdown.clone())?;
331
332        if environment.is_production() {
333            tokio::spawn(telemetry::serve_metrics(shutdown.clone()));
334        }
335
336        serve_on(router, &host, port, limits, shutdown, async move {
337            state.app().on_shutdown().await;
338        })
339        .await
340    }
341
342    /// Everything [`run`](WebServer::run) does before it binds.
343    ///
344    /// The one assembly path, so the router [`into_router`](WebServer::into_router)
345    /// hands a test cannot drift from the one production serves.
346    #[instrument(skip_all)]
347    #[cfg_attr(
348        not(feature = "pages"),
349        expect(unused_mut, reason = "only a frontend merges routes into the router")
350    )]
351    #[expect(
352        clippy::too_many_lines,
353        reason = "one linear assembly path, so a test router cannot drift from the served one"
354    )]
355    fn assemble(self, shutdown: Shutdown) -> Result<Assembled<S>, WebServerError> {
356        let Self {
357            host,
358            port,
359            environment,
360            app,
361            body_limit,
362            compression,
363            security,
364            limits,
365            root_dir,
366            router,
367            nested,
368            #[cfg(feature = "pages")]
369            frontend,
370            #[cfg(feature = "pages")]
371            feed,
372        } = self;
373
374        // A feed on a server that is not a frontend is never served, and
375        // nothing at runtime would say so.
376        #[cfg(feature = "pages")]
377        if feed.is_some() && frontend.is_none() {
378            return Err(WebServerError::FeedWithoutFrontend);
379        }
380
381        // Hashing is a build step, so this only ever reads what the build
382        // produced. A project with no `static/` gets an empty map.
383        let cache_buster: crate::assets::CacheBuster =
384            crate::assets::CacheBuster::load_in(&root_dir)?;
385
386        let mut no_cache: Router<WebServerState<S>> = router;
387        let mut built_in: Router<WebServerState<S>> = Router::new().route("/health", get(health));
388        let mut untraced: Vec<String> =
389            vec![format!("{API_PREFIX}/health"), String::from("/static")];
390        untraced.extend(nested);
391        #[cfg_attr(
392            not(feature = "pages"),
393            expect(unused_mut, reason = "only a frontend adds redirects")
394        )]
395        let mut untraced_exact: Vec<String> = Vec::new();
396
397        // Gated on `templates`, the gate of the `StateParts` fields that read
398        // them; only `pages` ever assigns them.
399        #[cfg(feature = "templates")]
400        #[cfg_attr(
401            not(feature = "pages"),
402            expect(unused_mut, reason = "only a frontend assigns them")
403        )]
404        let mut slots: FrontendSlots = FrontendSlots::default();
405        #[cfg(feature = "pages")]
406        let mut not_found: Option<super::not_found::NotFound<S>> = None;
407        #[cfg(feature = "pages")]
408        let mut proxy_scripts: Option<Router<WebServerState<S>>> = None;
409        #[cfg(feature = "pages")]
410        let mut feed_router: Option<Router<WebServerState<S>>> = None;
411
412        log_immutable_assets(&cache_buster);
413
414        #[cfg(feature = "pages")]
415        if let Some(params) = frontend {
416            let assembled: AssembledFrontend<S> =
417                assemble_frontend(params, feed, &cache_buster, environment)?;
418
419            untraced.extend(assembled.untraced);
420            untraced_exact.extend(assembled.redirects);
421            no_cache = no_cache.merge(assembled.routes);
422            built_in = built_in.merge(assembled.api);
423            proxy_scripts = Some(assembled.proxy_scripts);
424            feed_router = assembled.feeds;
425            not_found = Some(assembled.not_found);
426            slots = assembled.slots;
427        }
428
429        let no_cache: Router<WebServerState<S>> = no_cache.nest(API_PREFIX, built_in);
430
431        let mut app_router: Router<WebServerState<S>> = apply_cache_policy(no_cache, &cache_buster);
432
433        // Merged after the never-cache layer so the upstream's own headers
434        // survive: the vendor scripts carry their own policy, and stamping
435        // `no-store` over it would re-download them on every page view.
436        #[cfg(feature = "pages")]
437        if let Some(scripts) = proxy_scripts {
438            app_router = app_router.merge(scripts);
439        }
440
441        #[cfg(feature = "pages")]
442        if let Some(feeds) = feed_router {
443            app_router = app_router.merge(feeds);
444        }
445
446        #[cfg(feature = "pages")]
447        let app_router: Router<WebServerState<S>> = attach_not_found(app_router, not_found);
448        #[cfg(not(feature = "pages"))]
449        let app_router: Router<WebServerState<S>> = app_router.fallback(plain_not_found);
450
451        let state: WebServerState<S> = WebServerState::new(StateParts {
452            host: host.clone(),
453            port,
454            environment,
455            shutdown,
456            #[cfg(feature = "templates")]
457            base: slots.base,
458            #[cfg(feature = "templates")]
459            templates: slots.templates,
460            cache_buster: Some(cache_buster),
461            #[cfg(feature = "templates")]
462            frontend: slots.runtime,
463            app,
464        });
465
466        // The router takes the state by value; `run`'s cleanup needs it after
467        // serving ends, and `WebServerState` is an `Arc` so this is a refcount.
468        let app_router: Router = with_middleware(
469            super::security::apply(app_router.with_state(state.clone()), security),
470            body_limit,
471            compression,
472            telemetry::TraceRoutes::new(untraced).with_untraced_exact(untraced_exact),
473        );
474
475        Ok(Assembled {
476            router: app_router,
477            state,
478            host,
479            port,
480            environment,
481            limits,
482        })
483    }
484}
485
486/// Every server's middleware, innermost first: route metrics (they need the
487/// matched route), tracing (which also names and samples the Sentry
488/// transaction, so it needs it too), the request id (outside tracing, so the span sees
489/// it), then the body cap (outermost, so tracing never sees a request it may
490/// never finish reading). Compression sits just inside the cap, outside
491/// tracing, so it sees every response (404s included). It adds `Vary` only to
492/// a response it considers for compression: not 304s, tiny bodies or streams.
493fn with_middleware(
494    router: Router,
495    body_limit: usize,
496    compression: bool,
497    trace_routes: telemetry::TraceRoutes,
498) -> Router {
499    let router: Router = router
500        .layer(axum::middleware::from_fn(telemetry::http_metrics))
501        .layer(
502            TraceLayer::new(RelayAwareClassifier)
503                .make_span_with(move |request: &axum::http::Request<axum::body::Body>| {
504                    trace_routes.span(request)
505                })
506                .on_response(
507                    DefaultOnResponse::new()
508                        .level(Level::INFO)
509                        .latency_unit(LatencyUnit::Millis),
510                ),
511        )
512        .layer(axum::middleware::from_fn(telemetry::request_id));
513    let router: Router = if compression {
514        router.layer(compression_layer())
515    } else {
516        router
517    };
518    router.layer(DefaultBodyLimit::max(body_limit))
519}
520
521/// Tower-http's 5xx-is-failure rule, except a response marked
522/// [`UpstreamFailure`] (an analytics or Sentry proxy relaying its upstream's
523/// 5xx) is not a failure here: the relay already logged it at `warn`. Nor is
524/// one marked [`DeliberateOverload`], an app's own load shedding.
525#[derive(Clone, Copy)]
526struct RelayAwareClassifier;
527
528impl MakeClassifier for RelayAwareClassifier {
529    type Classifier = RelayAwareClassifier;
530    type FailureClass = ServerErrorsFailureClass;
531    type ClassifyEos = NeverClassifyEos<ServerErrorsFailureClass>;
532
533    fn make_classifier<B>(&self, _request: &axum::http::Request<B>) -> Self::Classifier {
534        *self
535    }
536}
537
538impl ClassifyResponse for RelayAwareClassifier {
539    type FailureClass = ServerErrorsFailureClass;
540    type ClassifyEos = NeverClassifyEos<ServerErrorsFailureClass>;
541
542    fn classify_response<B>(
543        self,
544        response: &axum::http::Response<B>,
545    ) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
546        if response.extensions().get::<UpstreamFailure>().is_some()
547            || response
548                .extensions()
549                .get::<super::DeliberateOverload>()
550                .is_some()
551        {
552            return ClassifiedResponse::Ready(Ok(()));
553        }
554        ServerErrorsAsFailures::new().classify_response(response)
555    }
556
557    fn classify_error<E>(self, error: &E) -> Self::FailureClass
558    where
559        E: std::fmt::Display + 'static,
560    {
561        ServerErrorsAsFailures::new().classify_error(error)
562    }
563}
564
565/// Level 3 of every algorithm, chosen by measurement (see the README): about
566/// 25% of the original on JSON at roughly 20-150 microseconds per 10-100 KB
567/// body. The library defaults are far costlier (brotli's is 11, tens of
568/// milliseconds a response). `deflate` is off: no client that sends it lacks gzip.
569///
570/// The default predicate skips bodies under 32 bytes, images (but not SVG),
571/// gRPC and `text/event-stream`; newline-delimited JSON is added, so those
572/// streams keep flushing. Any other streamed body would sit in the encoder.
573fn compression_layer() -> CompressionLayer<impl Predicate> {
574    CompressionLayer::new()
575        .no_deflate()
576        .quality(CompressionLevel::Precise(3))
577        .compress_when(
578            DefaultPredicate::new()
579                .and(NotForContentType::const_new("application/x-ndjson"))
580                .and(NotForContentType::const_new("application/jsonl")),
581        )
582}
583
584/// The frontend-only state parts, empty until a frontend assigns them.
585#[cfg(feature = "templates")]
586#[derive(Default)]
587struct FrontendSlots {
588    runtime: Option<crate::templates::FrontendRuntime>,
589    base: Option<crate::templates::BaseTemplateData>,
590    templates: Option<crate::templates::TemplateRegistry<'static>>,
591}
592
593/// A server ready to bind: what [`WebServer::run`] serves and what it cleans
594/// up afterwards.
595struct Assembled<S> {
596    router: Router,
597    /// Kept beside the router because `with_state` consumes it, and the
598    /// shutdown hook runs after serving ends.
599    state: WebServerState<S>,
600    host: String,
601    port: u16,
602    environment: Environment,
603    limits: ConnectionLimits,
604}
605
606/// Attaches the 404 fallback.
607///
608/// A frontend renders its own page at the requested URL with a real 404 status;
609/// a service with no pages answers with a bare body. Split out of `run` because
610/// it is the one branch there that is about a single route rather than about
611/// assembling the router.
612#[cfg(feature = "pages")]
613fn attach_not_found<S>(
614    router: Router<WebServerState<S>>,
615    not_found: Option<super::not_found::NotFound<S>>,
616) -> Router<WebServerState<S>>
617where
618    S: Clone + Send + Sync + 'static,
619{
620    match not_found {
621        Some(not_found) => router.fallback(
622            move |axum::extract::State(state): axum::extract::State<WebServerState<S>>,
623                  uri: axum::http::Uri| {
624                let not_found: super::not_found::NotFound<S> = not_found.clone();
625                async move {
626                    let data: serde_json::Value = not_found.data(state.clone(), uri).await;
627                    state.not_found(data)
628                }
629            },
630        ),
631        None => router.fallback(plain_not_found),
632    }
633}
634
635/// Binds and serves until the last connection closes, or the drain window
636/// shuts, whichever comes first.
637///
638/// `on_shutdown` is the application's own cleanup. It is only ever awaited if a
639/// shutdown signal actually arrives — a server that dies on a bind error drops
640/// it unrun, rather than hanging on cleanup nobody asked for.
641async fn serve_on<F>(
642    router: Router,
643    host: &str,
644    port: u16,
645    limits: ConnectionLimits,
646    shutdown: Shutdown,
647    on_shutdown: F,
648) -> Result<(), WebServerError>
649where
650    F: Future<Output = ()> + Send,
651{
652    let ip: IpAddr = IpAddr::from_str(host).map_err(|source| WebServerError::Bind {
653        addr: SocketAddr::from(([0, 0, 0, 0], port)),
654        source: std::io::Error::new(std::io::ErrorKind::InvalidInput, source),
655    })?;
656    let address: SocketAddr = SocketAddr::new(ip, port);
657    let listener: TcpListener =
658        TcpListener::bind(address)
659            .await
660            .map_err(|source| WebServerError::Bind {
661                addr: address,
662                source,
663            })?;
664
665    info!("{}", listening_message(address));
666
667    let serving = connections::serve("app", listener, router, limits, shutdown.clone().recv());
668    tokio::pin!(serving);
669
670    // The drain window is a ceiling on the wait, not the wait itself, so the
671    // clock cannot start until the drain does — and `serving` resolves the
672    // moment the last connection closes, which for an idle server is at once.
673    // `serving` ends only once the signal has arrived, so the signal is polled
674    // first: otherwise both are ready and a random pick could skip the cleanup.
675    tokio::select! {
676        biased;
677        () = shutdown.recv() => {}
678        () = &mut serving => return Ok(()),
679    }
680
681    // Two ceilings started at one instant, not one after the other: the drain
682    // and the cleanup are independent, so the process leaves in the longer of
683    // the two rather than their sum — which is what keeps the whole shutdown
684    // inside a single orchestrator kill window.
685    let (served, cleaned) = tokio::join!(
686        tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, &mut serving),
687        tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, on_shutdown),
688    );
689
690    // The hook's own reporting never runs when it is cancelled from out here,
691    // so the overrun has to be reported from out here too, or the work it
692    // failed to finish is lost silently.
693    if cleaned.is_err() {
694        error!(
695            "app shutdown hook exceeded {DEFAULT_DRAIN_TIMEOUT:?}; cleanup was cancelled part-way"
696        );
697    }
698
699    match served {
700        Ok(()) => Ok(()),
701        // Expected of anything holding a socket open, not a misconfiguration:
702        // the ceiling exists precisely because such a connection never ends.
703        Err(_elapsed) => {
704            warn!("drain window elapsed after {DEFAULT_DRAIN_TIMEOUT:?}; closing what remained");
705            Ok(())
706        }
707    }
708}
709
710/// The two cache policies: nothing outside `/static` is cached unless its
711/// handler set `Cache-Control` itself, and everything inside it is immutable
712/// because its URL carries a content hash.
713fn apply_cache_policy<S>(
714    router: Router<WebServerState<S>>,
715    cache_buster: &crate::assets::CacheBuster,
716) -> Router<WebServerState<S>>
717where
718    S: Clone + Send + Sync + 'static,
719{
720    let router: Router<WebServerState<S>> = router.layer(axum::middleware::from_fn(
721        crate::assets::CacheBuster::never_cache_middleware,
722    ));
723
724    if cache_buster.is_empty() {
725        return router;
726    }
727
728    router.merge(
729        Router::new()
730            .nest_service(
731                "/static",
732                // A `.br`, `.zst` or `.gz` sibling beside a file is served as-is to
733                // clients that accept it; no sibling falls back to the file,
734                // which the compression layer then handles.
735                tower_http::services::ServeDir::new(
736                    cache_buster.root().join(crate::assets::STATIC_DIRECTORY),
737                )
738                .precompressed_br()
739                .precompressed_zstd()
740                .precompressed_gzip(),
741            )
742            .layer(axum::middleware::from_fn(reject_unservable_static_path))
743            .layer(axum::middleware::from_fn(
744                crate::assets::CacheBuster::forever_cache_middleware,
745            )),
746    )
747}
748
749/// Linux's longest file name (`NAME_MAX`), in bytes.
750const MAX_FILE_NAME_BYTES: usize = 255;
751
752/// True when a segment of the (still percent-encoded) path is longer than any
753/// file name can be. Decoding only shortens a segment, so a raw segment within
754/// the limit always decodes within it too.
755fn has_overlong_segment(path: &str) -> bool {
756    path.split('/')
757        .any(|segment: &str| segment.len() > MAX_FILE_NAME_BYTES)
758}
759
760/// A plain 404 for a `/static` path no file can have, before `ServeDir` tries
761/// it: the file system answers such a name with ENAMETOOLONG, which `ServeDir`
762/// logs as an error and turns into a 500. Only scanners send these.
763async fn reject_unservable_static_path(
764    request: axum::extract::Request,
765    next: axum::middleware::Next,
766) -> Response {
767    if has_overlong_segment(request.uri().path()) {
768        return plain_not_found_response();
769    }
770    next.run(request).await
771}
772
773/// `GET /api/v1/health`. Always routed: every deployment target expects one,
774/// and a bool to switch it off was surface for nothing.
775async fn health() -> StatusCode {
776    StatusCode::OK
777}
778
779/// The fallback for a server with no 404 page of its own.
780async fn plain_not_found() -> Response {
781    plain_not_found_response()
782}
783
784/// A bare 404, for a server that has no page to render one with.
785pub(super) fn plain_not_found_response() -> Response {
786    let mut response: Response = (StatusCode::NOT_FOUND, "404").into_response();
787    crate::assets::mark_never_cached(response.headers_mut());
788    response
789}
790
791/// Serves the generated and embedded documents from memory.
792///
793/// None of these is a file. Sitemaps need the route table, so they are built at
794/// boot; `robots.txt` and the manifest are derived from site data; humans.txt is
795/// compiled in. All are served at fixed never-cached routes where a content hash
796/// would mean nothing — which is also why the server needs no writable disk.
797#[cfg(feature = "pages")]
798fn well_known_routes<S>(well_known: &super::frontend::WellKnown) -> Router<WebServerState<S>>
799where
800    S: Clone + Send + Sync + 'static,
801{
802    use axum::http::header;
803
804    fn text<S>(
805        router: Router<WebServerState<S>>,
806        path: &str,
807        content_type: &'static str,
808        body: String,
809    ) -> Router<WebServerState<S>>
810    where
811        S: Clone + Send + Sync + 'static,
812    {
813        router.route(
814            path,
815            get(move || {
816                let body: String = body.clone();
817                async move { ([(header::CONTENT_TYPE, content_type)], body) }
818            }),
819        )
820    }
821
822    let mut router: Router<WebServerState<S>> = Router::new();
823    router = text(
824        router,
825        "/robots.txt",
826        "text/plain; charset=utf-8",
827        well_known.robots_txt.clone(),
828    );
829    router = text(
830        router,
831        "/humans.txt",
832        "text/plain; charset=utf-8",
833        well_known.humans_txt.clone(),
834    );
835    router = text(
836        router,
837        "/site.webmanifest",
838        "application/manifest+json",
839        well_known.webmanifest.clone(),
840    );
841    router = text(
842        router,
843        crate::sitemap::SITEMAP_INDEX_PATH,
844        "application/xml",
845        well_known.sitemaps.index().to_string(),
846    );
847    for (index, chunk) in well_known.sitemaps.chunks().iter().enumerate() {
848        router = text(
849            router,
850            &format!("/sitemap-{}.xml", index + 1),
851            "application/xml",
852            chunk.clone(),
853        );
854    }
855    router
856}
857
858/// Each icon's root route and the file it resolves to.
859///
860/// Only a project whose art is vector has an SVG one to serve.
861#[cfg(feature = "pages")]
862fn icon_sources(has_svg_icon: bool) -> Vec<(&'static str, &'static str)> {
863    let mut icons: Vec<(&str, &str)> = vec![
864        ("/favicon.ico", "static/image/favicon/favicon.ico"),
865        (
866            "/apple-touch-icon.png",
867            "static/image/favicon/apple-touch-icon.png",
868        ),
869        ("/icon-192.png", "static/image/favicon/icon-192.png"),
870        ("/icon-512.png", "static/image/favicon/icon-512.png"),
871    ];
872    if has_svg_icon {
873        icons.push(("/favicon.svg", "static/image/favicon/favicon.svg"));
874    }
875    icons
876}
877
878/// Serves the icon set at the well-known root paths browsers actually request.
879///
880/// Each one resolves through the manifest to its hashed file under `/static`,
881/// so the same bytes are reachable both ways: immutable at the hashed URL, and
882/// never-cached here where the URL cannot change.
883#[cfg(feature = "pages")]
884fn icon_routes<S>(
885    cache_buster: &crate::assets::CacheBuster,
886    has_svg_icon: bool,
887) -> Router<WebServerState<S>>
888where
889    S: Clone + Send + Sync + 'static,
890{
891    use tower_http::services::ServeFile;
892
893    let mut router: Router<WebServerState<S>> = Router::new();
894    for (route, original) in icon_sources(has_svg_icon) {
895        // Existence was proved at boot, so this is a resolution, not a check.
896        router = router.nest_service(route, ServeFile::new(cache_buster.file(original)));
897    }
898    router
899}
900
901/// A `Last-Modified` value: an HTTP date, always `GMT`.
902#[cfg(feature = "pages")]
903fn http_date(moment: jiff::Timestamp) -> String {
904    moment.strftime("%a, %d %b %Y %H:%M:%S GMT").to_string()
905}
906
907/// The feed routes, with the conditional-GET handling the rest of the site has
908/// no use for.
909///
910/// A feed is polled relentlessly — a few hundred subscribers across Feedly,
911/// Inoreader and `NetNewsWire` is tens of thousands of requests a day for a
912/// document that changes twice a year. A strong validator computed at boot
913/// turns all but the first of those into a bodiless `304`.
914///
915/// These routes never see [`CacheBuster::never_cache_middleware`], which
916/// removes `ETag` and `If-None-Match` outright.
917#[cfg(feature = "pages")]
918fn feed_routes<S>(feeds: &crate::feed::FeedSet) -> Router<WebServerState<S>>
919where
920    S: Clone + Send + Sync + 'static,
921{
922    use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
923
924    // Parsed once, at boot: a header value that cannot be built is a
925    // programming error, and discovering it per request would mean either a
926    // panic in a handler or a feed served without its validators.
927    let last_modified: HeaderValue = HeaderValue::from_str(&http_date(feeds.last_modified()))
928        .unwrap_or_else(|_| HeaderValue::from_static(""));
929    let cache_control: HeaderValue = HeaderValue::from_str(&format!(
930        "public, max-age={}",
931        crate::feed::FEED_MAX_AGE_SECONDS
932    ))
933    .unwrap_or_else(|_| HeaderValue::from_static("public"));
934
935    let mut router: Router<WebServerState<S>> = Router::new();
936    for document in feeds.documents() {
937        let body: String = String::from(document.body());
938        let etag_text: String = String::from(document.etag());
939        let etag: HeaderValue =
940            HeaderValue::from_str(&etag_text).unwrap_or_else(|_| HeaderValue::from_static(""));
941        let content_type: HeaderValue = HeaderValue::from_static(document.content_type());
942        let last_modified: HeaderValue = last_modified.clone();
943        let cache_control: HeaderValue = cache_control.clone();
944
945        router = router.route(
946            document.path(),
947            get(move |headers: HeaderMap| {
948                let body: String = body.clone();
949                let etag_text: String = etag_text.clone();
950                let etag: HeaderValue = etag.clone();
951                let content_type: HeaderValue = content_type.clone();
952                let last_modified: HeaderValue = last_modified.clone();
953                let cache_control: HeaderValue = cache_control.clone();
954                async move {
955                    let fresh: bool = if_none_match(&headers, &etag_text);
956
957                    // Built rather than tupled so the headers are *inserted*:
958                    // appending leaves axum's own `text/plain` for the string
959                    // body in place ahead of ours, and a reader that reads the
960                    // first `Content-Type` then treats the feed as plain text.
961                    let mut response: Response = if fresh {
962                        StatusCode::NOT_MODIFIED.into_response()
963                    } else {
964                        (StatusCode::OK, body).into_response()
965                    };
966
967                    let headers: &mut HeaderMap = response.headers_mut();
968                    headers.insert(header::CACHE_CONTROL, cache_control);
969                    headers.insert(header::ETAG, etag);
970                    headers.insert(header::LAST_MODIFIED, last_modified);
971                    if !fresh {
972                        headers.insert(header::CONTENT_TYPE, content_type);
973                    }
974
975                    response
976                }
977            }),
978        );
979    }
980
981    router
982}
983
984/// Whether the request already holds this exact document.
985///
986/// `If-None-Match` is a comma-separated list, entries may be weak (`W/"…"`),
987/// and `*` matches anything that exists — so a bare string comparison against
988/// the header would 200 on requests that should 304.
989#[cfg(feature = "pages")]
990fn if_none_match(headers: &axum::http::HeaderMap, etag: &str) -> bool {
991    let Some(header) = headers
992        .get(axum::http::header::IF_NONE_MATCH)
993        .and_then(|value| value.to_str().ok())
994    else {
995        return false;
996    };
997
998    header.split(',').any(|candidate| {
999        let candidate: &str = candidate.trim();
1000        candidate == "*" || candidate.trim_start_matches("W/") == etag
1001    })
1002}
1003
1004/// Names every immutable asset and the URL it is actually served at, once per
1005/// boot.
1006///
1007/// Per-request logging cannot answer the question this exists for: a request
1008/// for an immutable asset reaching the origin is indistinguishable from a first
1009/// visit, a bot, a hard refresh or an evicted entry, and only one of those is a
1010/// fault. What *is* checkable is whether the tier was wired up at all, and that
1011/// is decided once, here. The hashed path is printed because it is the URL to
1012/// `curl` when verifying the edge.
1013fn log_immutable_assets(cache_buster: &crate::assets::CacheBuster) {
1014    for (original, hashed) in cache_buster.cache() {
1015        info!("immutable 1y  /{original} -> /{hashed}");
1016    }
1017}
1018
1019/// Names the generated documents and the tier each is served under.
1020#[cfg(feature = "pages")]
1021fn log_served_documents(well_known: &super::frontend::WellKnown) {
1022    for path in ["/robots.txt", "/humans.txt", "/site.webmanifest"] {
1023        info!("uncached      {path}");
1024    }
1025    for path in well_known.sitemaps.paths() {
1026        info!("uncached      {path}");
1027    }
1028
1029    if let Some(feeds) = well_known.feeds.as_ref() {
1030        for document in feeds.documents() {
1031            info!(
1032                "cached {}m    {} (etag {})",
1033                crate::feed::FEED_MAX_AGE_SECONDS / 60,
1034                document.path(),
1035                document.etag()
1036            );
1037        }
1038    }
1039}
1040
1041/// Everything a frontend contributes to the router, assembled.
1042///
1043/// A struct rather than a tuple of eight: `run` merges these into differently
1044/// cached layers, and two routers transposed would put the analytics script
1045/// behind `no-store`.
1046#[cfg(feature = "pages")]
1047struct AssembledFrontend<S> {
1048    /// Pages, icons and the never-cached well-known documents.
1049    routes: Router<WebServerState<S>>,
1050    /// Endpoints to nest under the API prefix.
1051    api: Router<WebServerState<S>>,
1052    /// Vendor scripts, which carry their own cache policy.
1053    proxy_scripts: Router<WebServerState<S>>,
1054    /// Feed documents, which carry theirs.
1055    feeds: Option<Router<WebServerState<S>>>,
1056    slots: FrontendSlots,
1057    not_found: super::not_found::NotFound<S>,
1058    /// Every route the library itself serves, which is never traced.
1059    untraced: Vec<String>,
1060    /// The pages' trailing-slash redirect patterns, never traced.
1061    redirects: Vec<String>,
1062}
1063
1064/// Builds the frontend and sorts its routes by the cache policy each needs.
1065#[cfg(feature = "pages")]
1066fn assemble_frontend<S>(
1067    mut params: super::frontend::FrontendParams<S>,
1068    feed: Option<crate::feed::Feed>,
1069    cache_buster: &crate::assets::CacheBuster,
1070    environment: Environment,
1071) -> Result<AssembledFrontend<S>, WebServerError>
1072where
1073    S: Clone + Send + Sync + 'static,
1074{
1075    let mut templates: crate::templates::TemplateRegistry<'static> =
1076        crate::templates::TemplateRegistry::from_dir(
1077            cache_buster.root().join(crate::templates::TEMPLATE_ROOT),
1078        )?;
1079    for (name, helper) in std::mem::take(&mut params.helpers) {
1080        templates.register_project_helper(&name, helper)?;
1081    }
1082
1083    let built: super::frontend::Frontend<S> =
1084        super::frontend::Frontend::build(params, feed, cache_buster, environment)?;
1085
1086    log_served_documents(&built.well_known);
1087
1088    // Feeds are deliberately kept out of the never-cache layer: it strips
1089    // conditional headers and stamps `no-store`, which on the most-polled
1090    // document a site serves means re-sending every byte on every poll.
1091    let feeds: Option<Router<WebServerState<S>>> = built.well_known.feeds.as_ref().map(feed_routes);
1092
1093    let mut routes: Router<WebServerState<S>> = well_known_routes(&built.well_known);
1094    routes = routes.merge(icon_routes(cache_buster, built.has_svg_icon));
1095
1096    // The vendor scripts are likewise kept out: they carry the vendor's own
1097    // cache policy, and stamping `no-store` over it would re-download the
1098    // analytics script on every page view.
1099    let (proxy_scripts, api) = proxy_routes(&built);
1100    let untraced: Vec<String> = library_routes(&built);
1101
1102    let redirects: Vec<String> = built.pages.redirect_routes();
1103    routes = routes.merge(built.pages.into_router()?);
1104
1105    Ok(AssembledFrontend {
1106        routes,
1107        api,
1108        proxy_scripts,
1109        feeds,
1110        slots: FrontendSlots {
1111            runtime: Some(built.runtime),
1112            base: Some(built.base),
1113            templates: Some(templates),
1114        },
1115        not_found: built.not_found,
1116        untraced,
1117        redirects,
1118    })
1119}
1120
1121/// The route patterns the library serves itself: the documents, icons, feeds
1122/// and proxies of [`assemble_frontend`]. None is traced.
1123#[cfg(feature = "pages")]
1124pub(super) fn library_routes<S>(frontend: &super::frontend::Frontend<S>) -> Vec<String>
1125where
1126    S: Clone + Send + Sync + 'static,
1127{
1128    let mut routes: Vec<String> = vec![
1129        String::from("/robots.txt"),
1130        String::from("/humans.txt"),
1131        String::from("/site.webmanifest"),
1132        frontend.runtime.sentry_browser.script_path.clone(),
1133        frontend.runtime.sentry_browser.tunnel_path.clone(),
1134    ];
1135    routes.extend(frontend.well_known.sitemaps.paths());
1136    routes.extend(
1137        icon_sources(frontend.has_svg_icon)
1138            .into_iter()
1139            .map(|(route, _original)| String::from(route)),
1140    );
1141    if let Some(feeds) = &frontend.well_known.feeds {
1142        routes.extend(
1143            feeds
1144                .documents()
1145                .iter()
1146                .map(|document| String::from(document.path())),
1147        );
1148    }
1149    if let Some(analytics) = frontend.runtime.analytics.as_ref() {
1150        routes.push(analytics.script_path.clone());
1151        routes.push(analytics.event_path.clone());
1152    }
1153    routes
1154}
1155
1156/// The first-party proxy routes.
1157///
1158/// Split in two because the scripts sit at the root — where they read as
1159/// ordinary bundler output — while the endpoints they post to belong under the
1160/// API prefix.
1161#[cfg(feature = "pages")]
1162fn proxy_routes<S>(
1163    frontend: &super::frontend::Frontend<S>,
1164) -> (Router<WebServerState<S>>, Router<WebServerState<S>>)
1165where
1166    S: Clone + Send + Sync + 'static,
1167{
1168    use crate::analytics::{AnalyticsConfig, ScriptRelay, SentryDsn, relay_envelope, relay_event};
1169    use axum::body::Bytes;
1170    use axum::extract::ConnectInfo;
1171    use axum::http::HeaderMap;
1172    use axum::routing::post;
1173
1174    let client: reqwest::Client = reqwest::Client::new();
1175    let paths: &crate::templates::FrontendRuntime = &frontend.runtime;
1176
1177    let analytics_event_upstream: String = AnalyticsConfig::upstream_event_url();
1178    let sentry_envelope_upstream: String = frontend.sentry_dsn.upstream_envelope_url();
1179
1180    let script_route = |relay: ScriptRelay| {
1181        get(move |headers: HeaderMap| {
1182            let relay: ScriptRelay = relay.clone();
1183            async move { relay.respond(&headers).await }
1184        })
1185    };
1186    let mut scripts: Router<WebServerState<S>> = Router::new();
1187    // Analytics disabled (local, or no id): the routes are not mounted, so they
1188    // 404 and nothing ever reaches Plausible.
1189    if let (Some(analytics_paths), Some(upstream)) = (
1190        paths.analytics.as_ref(),
1191        frontend.analytics.upstream_script_url_if_enabled(),
1192    ) {
1193        scripts = scripts.route(
1194            &analytics_paths.script_path,
1195            script_route(ScriptRelay::new(client.clone(), upstream)),
1196        );
1197    }
1198    let scripts: Router<WebServerState<S>> = scripts.route(
1199        &paths.sentry_browser.script_path,
1200        script_route(ScriptRelay::new(
1201            client.clone(),
1202            SentryDsn::upstream_bundle_url(frontend.browser_traces_sample_rate.is_on()),
1203        )),
1204    );
1205
1206    // Nested under the API prefix, so the paths registered here are relative.
1207    let tunnel_path: String = strip_api_prefix(&paths.sentry_browser.tunnel_path);
1208
1209    let mut endpoints: Router<WebServerState<S>> = Router::new();
1210    if let Some(analytics_paths) = paths
1211        .analytics
1212        .as_ref()
1213        .filter(|_| frontend.analytics.is_enabled())
1214    {
1215        let event_path: String = strip_api_prefix(&analytics_paths.event_path);
1216        endpoints = endpoints.route(
1217            &event_path,
1218            post({
1219                let client: reqwest::Client = client.clone();
1220                let upstream: std::sync::Arc<str> =
1221                    std::sync::Arc::from(analytics_event_upstream.as_str());
1222                move |ConnectInfo(peer): ConnectInfo<SocketAddr>,
1223                      headers: HeaderMap,
1224                      body: Bytes| {
1225                    let client: reqwest::Client = client.clone();
1226                    let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1227                    async move { relay_event(&client, &upstream, &headers, peer, body).await }
1228                }
1229            }),
1230        );
1231    }
1232    let endpoints: Router<WebServerState<S>> = endpoints.route(
1233        &tunnel_path,
1234        post({
1235            let upstream: std::sync::Arc<str> =
1236                std::sync::Arc::from(sentry_envelope_upstream.as_str());
1237            move |body: Bytes| {
1238                let client: reqwest::Client = client.clone();
1239                let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1240                async move { relay_envelope(&client, &upstream, body).await }
1241            }
1242        }),
1243    );
1244
1245    (scripts, endpoints)
1246}
1247
1248/// `/api/v1/thing` → `/thing`, for a router that will be nested under the
1249/// prefix.
1250#[cfg(feature = "pages")]
1251fn strip_api_prefix(path: &str) -> String {
1252    path.strip_prefix(API_PREFIX)
1253        .map_or_else(|| path.to_string(), String::from)
1254}
1255
1256/// The startup log line: the crate version beside the listen address.
1257fn listening_message(address: SocketAddr) -> String {
1258    format!(
1259        "listening on http://{address} (webserver-base {})",
1260        env!("CARGO_PKG_VERSION")
1261    )
1262}
1263
1264#[cfg(test)]
1265mod tests {
1266    #[test]
1267    fn the_startup_line_names_the_address_and_the_crate_version() {
1268        let message: String = super::listening_message(([127, 0, 0, 1], 8080).into());
1269        assert!(message.contains("http://127.0.0.1:8080"), "{message}");
1270        assert!(message.contains(env!("CARGO_PKG_VERSION")), "{message}");
1271    }
1272
1273    #[cfg(feature = "pages")]
1274    #[test]
1275    fn the_last_modified_header_is_an_http_date_in_gmt() {
1276        let moment: jiff::Timestamp = "2026-01-02T03:04:05Z".parse().expect("a real instant");
1277
1278        assert_eq!("Fri, 02 Jan 2026 03:04:05 GMT", super::http_date(moment));
1279    }
1280
1281    mod static_paths {
1282        use crate::webserver::server::has_overlong_segment;
1283
1284        #[test]
1285        fn a_hashed_asset_name_is_servable() {
1286            let expected: bool = false;
1287            let actual: bool = has_overlong_segment("/css/main.0123456789abcdef.css");
1288            assert_eq!(expected, actual);
1289        }
1290
1291        #[test]
1292        fn a_segment_at_the_file_name_limit_is_still_tried() {
1293            let expected: bool = false;
1294            let actual: bool = has_overlong_segment(&format!("/js/{}", "a".repeat(255)));
1295            assert_eq!(expected, actual);
1296        }
1297
1298        #[test]
1299        fn a_segment_past_the_file_name_limit_is_a_404() {
1300            let expected: bool = true;
1301            let actual: bool = has_overlong_segment(&format!("/js/{}", "a".repeat(256)));
1302            assert_eq!(expected, actual);
1303        }
1304    }
1305
1306    #[test]
1307    fn a_deliberate_overload_is_not_a_failure_but_a_plain_503_is() {
1308        use axum::response::IntoResponse;
1309        use tower_http::classify::{ClassifiedResponse, ClassifyResponse};
1310
1311        use super::RelayAwareClassifier;
1312
1313        let failed = |response: &axum::response::Response| {
1314            matches!(
1315                RelayAwareClassifier.classify_response(response),
1316                ClassifiedResponse::Ready(Err(_))
1317            )
1318        };
1319        assert!(!failed(&crate::webserver::overloaded(
1320            std::time::Duration::from_secs(1)
1321        )));
1322        assert!(failed(
1323            &axum::http::StatusCode::SERVICE_UNAVAILABLE.into_response()
1324        ));
1325    }
1326
1327    #[cfg(all(feature = "analytics", feature = "observability"))]
1328    mod upstream_failures {
1329        use std::net::SocketAddr;
1330        use std::sync::Arc;
1331
1332        use axum::Router;
1333        use axum::body::Bytes;
1334        use axum::http::{HeaderMap, StatusCode};
1335        use axum::routing::post;
1336        use sentry::protocol::EnvelopeItem;
1337        use sentry::test::TestTransport;
1338        use sentry::{Client, ClientOptions, Hub, HubSwitchGuard};
1339        use tower::ServiceExt;
1340        use tracing_subscriber::Layer;
1341
1342        use crate::analytics::relay_event;
1343        use crate::webserver::server::with_middleware;
1344        use crate::webserver::telemetry::TraceRoutes;
1345
1346        /// How many Sentry events a POST to each of `paths` files, through the
1347        /// real middleware, with a proxy that relays a 503 upstream and a
1348        /// handler of the site's own that fails with a 500.
1349        async fn events_filed(path: &str) -> (StatusCode, usize) {
1350            let upstream: tokio::net::TcpListener = tokio::net::TcpListener::bind("127.0.0.1:0")
1351                .await
1352                .expect("a free port");
1353            let url: String = format!("http://{}/", upstream.local_addr().expect("an address"));
1354            tokio::spawn(async move {
1355                let app: Router =
1356                    Router::new().fallback(|| async { StatusCode::SERVICE_UNAVAILABLE });
1357                axum::serve(upstream, app).await.expect("serves");
1358            });
1359            let client: reqwest::Client = reqwest::Client::new();
1360            let router: Router = with_middleware(
1361                Router::new()
1362                    .route(
1363                        "/proxy",
1364                        post(move |headers: HeaderMap, body: Bytes| {
1365                            let client: reqwest::Client = client.clone();
1366                            let url: String = url.clone();
1367                            async move {
1368                                let peer: SocketAddr = "203.0.113.7:1".parse().expect("an address");
1369                                relay_event(&client, &url, &headers, peer, body).await
1370                            }
1371                        }),
1372                    )
1373                    .route(
1374                        "/boom",
1375                        post(|| async { StatusCode::INTERNAL_SERVER_ERROR }),
1376                    ),
1377                1024,
1378                false,
1379                TraceRoutes::new(Vec::new()),
1380            );
1381
1382            let transport: Arc<TestTransport> = TestTransport::new();
1383            let mut options: ClientOptions = ClientOptions::default();
1384            options.dsn = Some("https://public@sentry.invalid/1".parse().expect("a DSN"));
1385            options.transport = Some(Arc::new(transport.clone()));
1386            let hub: Arc<Hub> = Arc::new(Hub::new(
1387                Some(Arc::new(Client::from(options))),
1388                Arc::new(sentry::Scope::default()),
1389            ));
1390            let _hub: HubSwitchGuard = HubSwitchGuard::new(hub);
1391            let _subscriber: tracing::subscriber::DefaultGuard =
1392                tracing::subscriber::set_default(tracing_subscriber::layer::SubscriberExt::with(
1393                    tracing_subscriber::registry(),
1394                    // The production layer that turns `error!` into an event.
1395                    sentry::integrations::tracing::ErrorLayer::new()
1396                        .with_filter(tracing_subscriber::filter::LevelFilter::ERROR),
1397                ));
1398
1399            let response = router
1400                .oneshot(
1401                    axum::http::Request::builder()
1402                        .method("POST")
1403                        .uri(path)
1404                        .body(axum::body::Body::empty())
1405                        .expect("a valid request"),
1406                )
1407                .await
1408                .expect("a router never fails");
1409            let status: StatusCode = response.status();
1410            let events: usize = transport
1411                .fetch_and_clear_envelopes()
1412                .iter()
1413                .flat_map(|envelope| envelope.items())
1414                .filter(|item| matches!(item, EnvelopeItem::Event(_)))
1415                .count();
1416            (status, events)
1417        }
1418
1419        #[tokio::test(flavor = "current_thread")]
1420        async fn an_upstream_503_through_a_proxy_reaches_the_visitor_but_files_no_sentry_event() {
1421            let expected: (StatusCode, usize) = (StatusCode::SERVICE_UNAVAILABLE, 0);
1422            let actual: (StatusCode, usize) = events_filed("/proxy").await;
1423            assert_eq!(expected, actual);
1424        }
1425
1426        #[tokio::test(flavor = "current_thread")]
1427        async fn a_500_from_a_sites_own_handler_still_files_a_sentry_event() {
1428            let expected: (StatusCode, usize) = (StatusCode::INTERNAL_SERVER_ERROR, 1);
1429            let actual: (StatusCode, usize) = events_filed("/boom").await;
1430            assert_eq!(expected, actual);
1431        }
1432    }
1433
1434    #[cfg(feature = "pages")]
1435    mod conditional_get {
1436        use axum::http::{HeaderMap, HeaderValue, header};
1437
1438        use crate::webserver::server::if_none_match;
1439
1440        const ETAG: &str = "\"abc123\"";
1441
1442        fn headers(value: &str) -> HeaderMap {
1443            let mut headers: HeaderMap = HeaderMap::new();
1444            headers.insert(
1445                header::IF_NONE_MATCH,
1446                HeaderValue::from_str(value).expect("a valid header"),
1447            );
1448            headers
1449        }
1450
1451        #[test]
1452        fn a_request_without_the_header_always_gets_the_body() {
1453            let expected: bool = false;
1454            let actual: bool = if_none_match(&HeaderMap::new(), ETAG);
1455            assert_eq!(expected, actual);
1456        }
1457
1458        #[test]
1459        fn the_same_validator_means_the_reader_already_has_this_feed() {
1460            let expected: bool = true;
1461            let actual: bool = if_none_match(&headers(ETAG), ETAG);
1462            assert_eq!(expected, actual);
1463        }
1464
1465        #[test]
1466        fn a_weak_validator_still_matches_because_feeds_need_no_byte_equality() {
1467            let expected: bool = true;
1468            let actual: bool = if_none_match(&headers("W/\"abc123\""), ETAG);
1469            assert_eq!(expected, actual);
1470        }
1471
1472        #[test]
1473        fn a_star_matches_anything_that_exists() {
1474            let expected: bool = true;
1475            let actual: bool = if_none_match(&headers("*"), ETAG);
1476            assert_eq!(expected, actual);
1477        }
1478
1479        #[test]
1480        fn one_match_anywhere_in_the_list_is_enough() {
1481            // The header is a comma-separated list, so a naive string compare
1482            // against the whole value would re-send the body to a reader that
1483            // already holds it.
1484            let expected: bool = true;
1485            let actual: bool = if_none_match(&headers("\"other\", \"abc123\""), ETAG);
1486            assert_eq!(expected, actual);
1487        }
1488
1489        #[test]
1490        fn a_stale_validator_gets_the_new_document() {
1491            let expected: bool = false;
1492            let actual: bool = if_none_match(&headers("\"stale\""), ETAG);
1493            assert_eq!(expected, actual);
1494        }
1495    }
1496    use std::sync::Arc;
1497    use std::sync::atomic::{AtomicBool, Ordering};
1498    use std::time::Duration;
1499
1500    use axum::Router;
1501    use axum::routing::get;
1502    use tokio::time::timeout;
1503
1504    use super::super::shutdown::Shutdown;
1505    use super::{
1506        API_PREFIX, AppShutdown, ConnectionLimits, DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_TIMEOUT,
1507        WebServerError, health, serve_on,
1508    };
1509
1510    /// Records whether cleanup ran, and can be made slow enough to overrun the
1511    /// drain window.
1512    #[derive(Clone)]
1513    struct RecordingState {
1514        ran: Arc<AtomicBool>,
1515        linger: Option<Duration>,
1516    }
1517
1518    impl RecordingState {
1519        fn instant() -> Self {
1520            Self {
1521                ran: Arc::new(AtomicBool::new(false)),
1522                linger: None,
1523            }
1524        }
1525    }
1526
1527    impl AppShutdown for RecordingState {
1528        async fn on_shutdown(&self) {
1529            if let Some(linger) = self.linger {
1530                tokio::time::sleep(linger).await;
1531            }
1532            self.ran.store(true, Ordering::SeqCst);
1533        }
1534    }
1535
1536    /// Serves `state` on an ephemeral port and returns once serving has ended.
1537    async fn serve_until_shutdown(
1538        state: RecordingState,
1539        shutdown: Shutdown,
1540    ) -> Result<(), WebServerError> {
1541        let router: Router = Router::new().route("/health", get(health));
1542        let cleanup: RecordingState = state.clone();
1543        // Port 0 asks the OS for a free one; nothing here connects to it.
1544        serve_on(
1545            router,
1546            "127.0.0.1",
1547            0,
1548            ConnectionLimits::new(),
1549            shutdown,
1550            async move {
1551                cleanup.on_shutdown().await;
1552            },
1553        )
1554        .await
1555    }
1556
1557    #[tokio::test]
1558    async fn app_cleanup_runs_when_the_shutdown_signal_arrives() {
1559        let shutdown: Shutdown = Shutdown::manual();
1560        let state: RecordingState = RecordingState::instant();
1561        let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1562
1563        shutdown.trigger();
1564        timeout(
1565            Duration::from_secs(1),
1566            serve_until_shutdown(state, shutdown.clone()),
1567        )
1568        .await
1569        .expect("serving ended promptly")
1570        .expect("serving ended cleanly");
1571
1572        let expected: bool = true;
1573        let actual: bool = ran.load(Ordering::SeqCst);
1574        assert_eq!(expected, actual);
1575    }
1576
1577    #[tokio::test]
1578    async fn app_cleanup_never_runs_when_the_server_dies_before_any_signal() {
1579        // An unparseable host fails before the listener binds, so no signal is
1580        // ever sent — the hook must be dropped unrun rather than awaited, or a
1581        // failed boot would hang until the drain window closed.
1582        let shutdown: Shutdown = Shutdown::manual();
1583        let state: RecordingState = RecordingState::instant();
1584        let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1585        let cleanup: RecordingState = state.clone();
1586
1587        let router: Router = Router::new().route("/health", get(health));
1588        let result: Result<(), WebServerError> = timeout(
1589            Duration::from_secs(1),
1590            serve_on(
1591                router,
1592                "not-an-ip",
1593                0,
1594                ConnectionLimits::new(),
1595                shutdown,
1596                async move {
1597                    cleanup.on_shutdown().await;
1598                },
1599            ),
1600        )
1601        .await
1602        .expect("a bind failure returns immediately, it does not wait for cleanup");
1603
1604        assert!(result.is_err(), "an unparseable host is a bind error");
1605
1606        let expected: bool = false;
1607        let actual: bool = ran.load(Ordering::SeqCst);
1608        assert_eq!(expected, actual);
1609    }
1610
1611    #[tokio::test(start_paused = true)]
1612    async fn a_cleanup_that_overruns_the_window_is_cancelled_rather_than_awaited() {
1613        // Longer than the ceiling, so the hook cannot finish. With a paused
1614        // clock this costs no real time; the assertion is that serving still
1615        // returns, which it cannot do if the hook is awaited to completion.
1616        let shutdown: Shutdown = Shutdown::manual();
1617        let state: RecordingState = RecordingState {
1618            ran: Arc::new(AtomicBool::new(false)),
1619            linger: Some(DEFAULT_DRAIN_TIMEOUT * 2),
1620        };
1621        let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1622
1623        shutdown.trigger();
1624        serve_until_shutdown(state, shutdown.clone())
1625            .await
1626            .expect("serving still ends cleanly when cleanup is cancelled");
1627
1628        let expected: bool = false;
1629        let actual: bool = ran.load(Ordering::SeqCst);
1630        assert_eq!(
1631            expected, actual,
1632            "the hook was cancelled at its await, so it never reached its final store"
1633        );
1634    }
1635
1636    #[tokio::test]
1637    async fn a_server_with_nothing_in_flight_stops_at_once_instead_of_waiting_out_the_window() {
1638        let shutdown: Shutdown = Shutdown::manual();
1639        let router: Router = Router::new().route("/health", get(health));
1640
1641        // Port 0 asks the OS for a free one; nothing here connects to it.
1642        let serving: tokio::task::JoinHandle<Result<(), WebServerError>> = tokio::spawn({
1643            let shutdown: Shutdown = shutdown.clone();
1644            async move {
1645                serve_on(
1646                    router,
1647                    "127.0.0.1",
1648                    0,
1649                    ConnectionLimits::new(),
1650                    shutdown,
1651                    async {},
1652                )
1653                .await
1654            }
1655        });
1656
1657        shutdown.trigger();
1658
1659        // Far below the drain window: an unconditional wait fails here, which
1660        // is the bug — the window is a ceiling, not a delay.
1661        timeout(Duration::from_secs(1), serving)
1662            .await
1663            .expect("the server returned as soon as the drain began")
1664            .expect("the serving task did not panic")
1665            .expect("serving ended cleanly");
1666    }
1667
1668    #[test]
1669    fn the_body_limit_accommodates_an_ordinary_form_post() {
1670        // 1 KiB — the previous default — rejected almost any real submission,
1671        // so every project had to override it.
1672        let expected: usize = 256 * 1024;
1673        let actual: usize = DEFAULT_BODY_LIMIT;
1674        assert_eq!(expected, actual);
1675    }
1676
1677    #[cfg(feature = "pages")]
1678    #[test]
1679    fn stripping_the_prefix_leaves_a_nestable_path() {
1680        let expected: String = String::from("/boggledygook-a3f2c1d8");
1681        let actual: String = super::strip_api_prefix("/api/v1/boggledygook-a3f2c1d8");
1682        assert_eq!(expected, actual);
1683    }
1684
1685    #[test]
1686    fn the_api_prefix_is_the_one_every_project_shares() {
1687        assert_eq!("/api/v1", API_PREFIX);
1688    }
1689}