Skip to main content

webserver_base/webserver/
server.rs

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