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