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        #[cfg(feature = "pages")]
354        let mut frontend_runtime: Option<crate::templates::FrontendRuntime> = None;
355        #[cfg(feature = "pages")]
356        let mut base: Option<crate::templates::BaseTemplateData> = None;
357        #[cfg(feature = "pages")]
358        let mut templates: Option<crate::templates::TemplateRegistry<'static>> = None;
359        #[cfg(feature = "pages")]
360        let mut not_found: Option<super::not_found::NotFound<S>> = None;
361        #[cfg(feature = "pages")]
362        let mut proxy_scripts: Option<Router<WebServerState<S>>> = None;
363        #[cfg(feature = "pages")]
364        let mut feed_router: Option<Router<WebServerState<S>>> = None;
365
366        log_immutable_assets(&cache_buster);
367
368        #[cfg(feature = "pages")]
369        if let Some(params) = frontend {
370            let assembled: AssembledFrontend<S> =
371                assemble_frontend(params, feed, &cache_buster, environment)?;
372
373            untraced.extend(assembled.untraced);
374            untraced_exact.extend(assembled.redirects);
375            no_cache = no_cache.merge(assembled.routes);
376            built_in = built_in.merge(assembled.api);
377            proxy_scripts = Some(assembled.proxy_scripts);
378            feed_router = assembled.feeds;
379            not_found = Some(assembled.not_found);
380            frontend_runtime = Some(assembled.runtime);
381            base = Some(assembled.base);
382            templates = Some(assembled.templates);
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,
414            #[cfg(feature = "templates")]
415            templates,
416            cache_buster: Some(cache_buster),
417            #[cfg(feature = "templates")]
418            frontend: frontend_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/// A server ready to bind: what [`WebServer::run`] serves and what it cleans
534/// up afterwards.
535struct Assembled<S> {
536    router: Router,
537    /// Kept beside the router because `with_state` consumes it, and the
538    /// shutdown hook runs after serving ends.
539    state: WebServerState<S>,
540    host: String,
541    port: u16,
542    environment: Environment,
543}
544
545/// Attaches the 404 fallback.
546///
547/// A frontend renders its own page at the requested URL with a real 404 status;
548/// a service with no pages answers with a bare body. Split out of `run` because
549/// it is the one branch there that is about a single route rather than about
550/// assembling the router.
551#[cfg(feature = "pages")]
552fn attach_not_found<S>(
553    router: Router<WebServerState<S>>,
554    not_found: Option<super::not_found::NotFound<S>>,
555) -> Router<WebServerState<S>>
556where
557    S: Clone + Send + Sync + 'static,
558{
559    match not_found {
560        Some(not_found) => router.fallback(
561            move |axum::extract::State(state): axum::extract::State<WebServerState<S>>,
562                  uri: axum::http::Uri| {
563                let not_found: super::not_found::NotFound<S> = not_found.clone();
564                async move {
565                    let data: serde_json::Value = not_found.data(state.clone(), uri).await;
566                    state.not_found(data)
567                }
568            },
569        ),
570        None => router.fallback(plain_not_found),
571    }
572}
573
574/// Binds and serves until the last connection closes, or the drain window
575/// shuts, whichever comes first.
576///
577/// `on_shutdown` is the application's own cleanup. It is only ever awaited if a
578/// shutdown signal actually arrives — a server that dies on a bind error drops
579/// it unrun, rather than hanging on cleanup nobody asked for.
580async fn serve_on<F>(
581    router: Router,
582    host: &str,
583    port: u16,
584    shutdown: Shutdown,
585    on_shutdown: F,
586) -> Result<(), WebServerError>
587where
588    F: Future<Output = ()> + Send,
589{
590    let ip: IpAddr = IpAddr::from_str(host).map_err(|source| WebServerError::Bind {
591        addr: SocketAddr::from(([0, 0, 0, 0], port)),
592        source: std::io::Error::new(std::io::ErrorKind::InvalidInput, source),
593    })?;
594    let address: SocketAddr = SocketAddr::new(ip, port);
595    let listener: TcpListener =
596        TcpListener::bind(address)
597            .await
598            .map_err(|source| WebServerError::Bind {
599                addr: address,
600                source,
601            })?;
602
603    info!("listening on http://{address}");
604
605    // The one binding in the crate with no written type: `WithGracefulShutdown`
606    // is generic over the listener, the make-service, the service and the
607    // shutdown future, and rustc itself elides it when printing.
608    let serving = serve(
609        listener,
610        router.into_make_service_with_connect_info::<SocketAddr>(),
611    )
612    .with_graceful_shutdown(shutdown.clone().recv())
613    .into_future();
614    tokio::pin!(serving);
615
616    // The drain window is a ceiling on the wait, not the wait itself, so the
617    // clock cannot start until the drain does — and `serving` resolves the
618    // moment the last connection closes, which for an idle server is at once.
619    tokio::select! {
620        result = &mut serving => return result.map_err(WebServerError::Serve),
621        () = shutdown.recv() => {}
622    }
623
624    // Two ceilings started at one instant, not one after the other: the drain
625    // and the cleanup are independent, so the process leaves in the longer of
626    // the two rather than their sum — which is what keeps the whole shutdown
627    // inside a single orchestrator kill window.
628    let (served, cleaned) = tokio::join!(
629        tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, &mut serving),
630        tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, on_shutdown),
631    );
632
633    // The hook's own reporting never runs when it is cancelled from out here,
634    // so the overrun has to be reported from out here too, or the work it
635    // failed to finish is lost silently.
636    if cleaned.is_err() {
637        error!(
638            "app shutdown hook exceeded {DEFAULT_DRAIN_TIMEOUT:?}; cleanup was cancelled part-way"
639        );
640    }
641
642    match served {
643        Ok(result) => result.map_err(WebServerError::Serve),
644        // Expected of anything holding a socket open, not a misconfiguration:
645        // the ceiling exists precisely because such a connection never ends.
646        Err(_elapsed) => {
647            warn!("drain window elapsed after {DEFAULT_DRAIN_TIMEOUT:?}; closing what remained");
648            Ok(())
649        }
650    }
651}
652
653/// The two cache policies: nothing outside `/static` is cached unless its
654/// handler set `Cache-Control` itself, and everything inside it is immutable
655/// because its URL carries a content hash.
656fn apply_cache_policy<S>(
657    router: Router<WebServerState<S>>,
658    cache_buster: &crate::assets::CacheBuster,
659) -> Router<WebServerState<S>>
660where
661    S: Clone + Send + Sync + 'static,
662{
663    let router: Router<WebServerState<S>> = router.layer(axum::middleware::from_fn(
664        crate::assets::CacheBuster::never_cache_middleware,
665    ));
666
667    if cache_buster.is_empty() {
668        return router;
669    }
670
671    router.merge(
672        Router::new()
673            .nest_service(
674                "/static",
675                tower_http::services::ServeDir::new(
676                    cache_buster.root().join(crate::assets::STATIC_DIRECTORY),
677                ),
678            )
679            .layer(axum::middleware::from_fn(reject_unservable_static_path))
680            .layer(axum::middleware::from_fn(
681                crate::assets::CacheBuster::forever_cache_middleware,
682            )),
683    )
684}
685
686/// Linux's longest file name (`NAME_MAX`), in bytes.
687const MAX_FILE_NAME_BYTES: usize = 255;
688
689/// True when a segment of the (still percent-encoded) path is longer than any
690/// file name can be. Decoding only shortens a segment, so a raw segment within
691/// the limit always decodes within it too.
692fn has_overlong_segment(path: &str) -> bool {
693    path.split('/')
694        .any(|segment: &str| segment.len() > MAX_FILE_NAME_BYTES)
695}
696
697/// A plain 404 for a `/static` path no file can have, before `ServeDir` tries
698/// it: the file system answers such a name with ENAMETOOLONG, which `ServeDir`
699/// logs as an error and turns into a 500. Only scanners send these.
700async fn reject_unservable_static_path(
701    request: axum::extract::Request,
702    next: axum::middleware::Next,
703) -> Response {
704    if has_overlong_segment(request.uri().path()) {
705        return plain_not_found_response();
706    }
707    next.run(request).await
708}
709
710/// `GET /api/v1/health`. Always routed: every deployment target expects one,
711/// and a bool to switch it off was surface for nothing.
712async fn health() -> StatusCode {
713    StatusCode::OK
714}
715
716/// The fallback for a server with no 404 page of its own.
717async fn plain_not_found() -> Response {
718    plain_not_found_response()
719}
720
721/// A bare 404, for a server that has no page to render one with.
722pub(super) fn plain_not_found_response() -> Response {
723    let mut response: Response = (StatusCode::NOT_FOUND, "404").into_response();
724    crate::assets::mark_never_cached(response.headers_mut());
725    response
726}
727
728/// Serves the generated and embedded documents from memory.
729///
730/// None of these is a file. Sitemaps need the route table, so they are built at
731/// boot; `robots.txt` and the manifest are derived from site data; humans.txt is
732/// compiled in. All are served at fixed never-cached routes where a content hash
733/// would mean nothing — which is also why the server needs no writable disk.
734#[cfg(feature = "pages")]
735fn well_known_routes<S>(well_known: &super::frontend::WellKnown) -> Router<WebServerState<S>>
736where
737    S: Clone + Send + Sync + 'static,
738{
739    use axum::http::header;
740
741    fn text<S>(
742        router: Router<WebServerState<S>>,
743        path: &str,
744        content_type: &'static str,
745        body: String,
746    ) -> Router<WebServerState<S>>
747    where
748        S: Clone + Send + Sync + 'static,
749    {
750        router.route(
751            path,
752            get(move || {
753                let body: String = body.clone();
754                async move { ([(header::CONTENT_TYPE, content_type)], body) }
755            }),
756        )
757    }
758
759    let mut router: Router<WebServerState<S>> = Router::new();
760    router = text(
761        router,
762        "/robots.txt",
763        "text/plain; charset=utf-8",
764        well_known.robots_txt.clone(),
765    );
766    router = text(
767        router,
768        "/humans.txt",
769        "text/plain; charset=utf-8",
770        well_known.humans_txt.clone(),
771    );
772    router = text(
773        router,
774        "/site.webmanifest",
775        "application/manifest+json",
776        well_known.webmanifest.clone(),
777    );
778    router = text(
779        router,
780        crate::sitemap::SITEMAP_INDEX_PATH,
781        "application/xml",
782        well_known.sitemaps.index().to_string(),
783    );
784    for (index, chunk) in well_known.sitemaps.chunks().iter().enumerate() {
785        router = text(
786            router,
787            &format!("/sitemap-{}.xml", index + 1),
788            "application/xml",
789            chunk.clone(),
790        );
791    }
792    router
793}
794
795/// Each icon's root route and the file it resolves to.
796///
797/// Only a project whose art is vector has an SVG one to serve.
798#[cfg(feature = "pages")]
799fn icon_sources(has_svg_icon: bool) -> Vec<(&'static str, &'static str)> {
800    let mut icons: Vec<(&str, &str)> = vec![
801        ("/favicon.ico", "static/image/favicon/favicon.ico"),
802        (
803            "/apple-touch-icon.png",
804            "static/image/favicon/apple-touch-icon.png",
805        ),
806        ("/icon-192.png", "static/image/favicon/icon-192.png"),
807        ("/icon-512.png", "static/image/favicon/icon-512.png"),
808    ];
809    if has_svg_icon {
810        icons.push(("/favicon.svg", "static/image/favicon/favicon.svg"));
811    }
812    icons
813}
814
815/// Serves the icon set at the well-known root paths browsers actually request.
816///
817/// Each one resolves through the manifest to its hashed file under `/static`,
818/// so the same bytes are reachable both ways: immutable at the hashed URL, and
819/// never-cached here where the URL cannot change.
820#[cfg(feature = "pages")]
821fn icon_routes<S>(
822    cache_buster: &crate::assets::CacheBuster,
823    has_svg_icon: bool,
824) -> Router<WebServerState<S>>
825where
826    S: Clone + Send + Sync + 'static,
827{
828    use tower_http::services::ServeFile;
829
830    let mut router: Router<WebServerState<S>> = Router::new();
831    for (route, original) in icon_sources(has_svg_icon) {
832        // Existence was proved at boot, so this is a resolution, not a check.
833        router = router.nest_service(route, ServeFile::new(cache_buster.file(original)));
834    }
835    router
836}
837
838/// The feed routes, with the conditional-GET handling the rest of the site has
839/// no use for.
840///
841/// A feed is polled relentlessly — a few hundred subscribers across Feedly,
842/// Inoreader and `NetNewsWire` is tens of thousands of requests a day for a
843/// document that changes twice a year. A strong validator computed at boot
844/// turns all but the first of those into a bodiless `304`.
845///
846/// These routes never see [`CacheBuster::never_cache_middleware`], which
847/// removes `ETag` and `If-None-Match` outright.
848#[cfg(feature = "pages")]
849fn feed_routes<S>(feeds: &crate::feed::FeedSet) -> Router<WebServerState<S>>
850where
851    S: Clone + Send + Sync + 'static,
852{
853    use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
854
855    // Parsed once, at boot: a header value that cannot be built is a
856    // programming error, and discovering it per request would mean either a
857    // panic in a handler or a feed served without its validators.
858    let last_modified: HeaderValue = HeaderValue::from_str(
859        &feeds
860            .last_modified()
861            .format("%a, %d %b %Y %H:%M:%S GMT")
862            .to_string(),
863    )
864    .unwrap_or_else(|_| HeaderValue::from_static(""));
865    let cache_control: HeaderValue = HeaderValue::from_str(&format!(
866        "public, max-age={}",
867        crate::feed::FEED_MAX_AGE_SECONDS
868    ))
869    .unwrap_or_else(|_| HeaderValue::from_static("public"));
870
871    let mut router: Router<WebServerState<S>> = Router::new();
872    for document in feeds.documents() {
873        let body: String = String::from(document.body());
874        let etag_text: String = String::from(document.etag());
875        let etag: HeaderValue =
876            HeaderValue::from_str(&etag_text).unwrap_or_else(|_| HeaderValue::from_static(""));
877        let content_type: HeaderValue = HeaderValue::from_static(document.content_type());
878        let last_modified: HeaderValue = last_modified.clone();
879        let cache_control: HeaderValue = cache_control.clone();
880
881        router = router.route(
882            document.path(),
883            get(move |headers: HeaderMap| {
884                let body: String = body.clone();
885                let etag_text: String = etag_text.clone();
886                let etag: HeaderValue = etag.clone();
887                let content_type: HeaderValue = content_type.clone();
888                let last_modified: HeaderValue = last_modified.clone();
889                let cache_control: HeaderValue = cache_control.clone();
890                async move {
891                    let fresh: bool = if_none_match(&headers, &etag_text);
892
893                    // Built rather than tupled so the headers are *inserted*:
894                    // appending leaves axum's own `text/plain` for the string
895                    // body in place ahead of ours, and a reader that reads the
896                    // first `Content-Type` then treats the feed as plain text.
897                    let mut response: Response = if fresh {
898                        StatusCode::NOT_MODIFIED.into_response()
899                    } else {
900                        (StatusCode::OK, body).into_response()
901                    };
902
903                    let headers: &mut HeaderMap = response.headers_mut();
904                    headers.insert(header::CACHE_CONTROL, cache_control);
905                    headers.insert(header::ETAG, etag);
906                    headers.insert(header::LAST_MODIFIED, last_modified);
907                    if !fresh {
908                        headers.insert(header::CONTENT_TYPE, content_type);
909                    }
910
911                    response
912                }
913            }),
914        );
915    }
916
917    router
918}
919
920/// Whether the request already holds this exact document.
921///
922/// `If-None-Match` is a comma-separated list, entries may be weak (`W/"…"`),
923/// and `*` matches anything that exists — so a bare string comparison against
924/// the header would 200 on requests that should 304.
925#[cfg(feature = "pages")]
926fn if_none_match(headers: &axum::http::HeaderMap, etag: &str) -> bool {
927    let Some(header) = headers
928        .get(axum::http::header::IF_NONE_MATCH)
929        .and_then(|value| value.to_str().ok())
930    else {
931        return false;
932    };
933
934    header.split(',').any(|candidate| {
935        let candidate: &str = candidate.trim();
936        candidate == "*" || candidate.trim_start_matches("W/") == etag
937    })
938}
939
940/// Names every immutable asset and the URL it is actually served at, once per
941/// boot.
942///
943/// Per-request logging cannot answer the question this exists for: a request
944/// for an immutable asset reaching the origin is indistinguishable from a first
945/// visit, a bot, a hard refresh or an evicted entry, and only one of those is a
946/// fault. What *is* checkable is whether the tier was wired up at all, and that
947/// is decided once, here. The hashed path is printed because it is the URL to
948/// `curl` when verifying the edge.
949fn log_immutable_assets(cache_buster: &crate::assets::CacheBuster) {
950    for (original, hashed) in cache_buster.cache() {
951        info!("immutable 1y  /{original} -> /{hashed}");
952    }
953}
954
955/// Names the generated documents and the tier each is served under.
956#[cfg(feature = "pages")]
957fn log_served_documents(well_known: &super::frontend::WellKnown) {
958    for path in ["/robots.txt", "/humans.txt", "/site.webmanifest"] {
959        info!("uncached      {path}");
960    }
961    for path in well_known.sitemaps.paths() {
962        info!("uncached      {path}");
963    }
964
965    if let Some(feeds) = well_known.feeds.as_ref() {
966        for document in feeds.documents() {
967            info!(
968                "cached {}m    {} (etag {})",
969                crate::feed::FEED_MAX_AGE_SECONDS / 60,
970                document.path(),
971                document.etag()
972            );
973        }
974    }
975}
976
977/// Everything a frontend contributes to the router, assembled.
978///
979/// A struct rather than a tuple of eight: `run` merges these into differently
980/// cached layers, and two routers transposed would put the analytics script
981/// behind `no-store`.
982#[cfg(feature = "pages")]
983struct AssembledFrontend<S> {
984    /// Pages, icons and the never-cached well-known documents.
985    routes: Router<WebServerState<S>>,
986    /// Endpoints to nest under the API prefix.
987    api: Router<WebServerState<S>>,
988    /// Vendor scripts, which carry their own cache policy.
989    proxy_scripts: Router<WebServerState<S>>,
990    /// Feed documents, which carry theirs.
991    feeds: Option<Router<WebServerState<S>>>,
992    runtime: crate::templates::FrontendRuntime,
993    base: crate::templates::BaseTemplateData,
994    templates: crate::templates::TemplateRegistry<'static>,
995    not_found: super::not_found::NotFound<S>,
996    /// Every route the library itself serves, which is never traced.
997    untraced: Vec<String>,
998    /// The pages' trailing-slash redirect patterns, never traced.
999    redirects: Vec<String>,
1000}
1001
1002/// Builds the frontend and sorts its routes by the cache policy each needs.
1003#[cfg(feature = "pages")]
1004fn assemble_frontend<S>(
1005    mut params: super::frontend::FrontendParams<S>,
1006    feed: Option<crate::feed::Feed>,
1007    cache_buster: &crate::assets::CacheBuster,
1008    environment: Environment,
1009) -> Result<AssembledFrontend<S>, WebServerError>
1010where
1011    S: Clone + Send + Sync + 'static,
1012{
1013    let mut templates: crate::templates::TemplateRegistry<'static> =
1014        crate::templates::TemplateRegistry::from_dir(
1015            cache_buster.root().join(crate::templates::TEMPLATE_ROOT),
1016        )?;
1017    for (name, helper) in std::mem::take(&mut params.helpers) {
1018        templates.register_project_helper(&name, helper)?;
1019    }
1020
1021    let built: super::frontend::Frontend<S> =
1022        super::frontend::Frontend::build(params, feed, cache_buster, environment)?;
1023
1024    log_served_documents(&built.well_known);
1025
1026    // Feeds are deliberately kept out of the never-cache layer: it strips
1027    // conditional headers and stamps `no-store`, which on the most-polled
1028    // document a site serves means re-sending every byte on every poll.
1029    let feeds: Option<Router<WebServerState<S>>> = built.well_known.feeds.as_ref().map(feed_routes);
1030
1031    let mut routes: Router<WebServerState<S>> = well_known_routes(&built.well_known);
1032    routes = routes.merge(icon_routes(cache_buster, built.has_svg_icon));
1033
1034    // The vendor scripts are likewise kept out: they carry the vendor's own
1035    // cache policy, and stamping `no-store` over it would re-download the
1036    // analytics script on every page view.
1037    let (proxy_scripts, api) = proxy_routes(&built);
1038    let untraced: Vec<String> = library_routes(&built);
1039
1040    let redirects: Vec<String> = built.pages.redirect_routes();
1041    routes = routes.merge(built.pages.into_router()?);
1042
1043    Ok(AssembledFrontend {
1044        routes,
1045        api,
1046        proxy_scripts,
1047        feeds,
1048        runtime: built.runtime,
1049        base: built.base,
1050        templates,
1051        not_found: built.not_found,
1052        untraced,
1053        redirects,
1054    })
1055}
1056
1057/// The route patterns the library serves itself: the documents, icons, feeds
1058/// and proxies of [`assemble_frontend`]. None is traced.
1059#[cfg(feature = "pages")]
1060pub(super) fn library_routes<S>(frontend: &super::frontend::Frontend<S>) -> Vec<String>
1061where
1062    S: Clone + Send + Sync + 'static,
1063{
1064    let mut routes: Vec<String> = vec![
1065        String::from("/robots.txt"),
1066        String::from("/humans.txt"),
1067        String::from("/site.webmanifest"),
1068        frontend.runtime.sentry_browser.script_path.clone(),
1069        frontend.runtime.sentry_browser.tunnel_path.clone(),
1070    ];
1071    routes.extend(frontend.well_known.sitemaps.paths());
1072    routes.extend(
1073        icon_sources(frontend.has_svg_icon)
1074            .into_iter()
1075            .map(|(route, _original)| String::from(route)),
1076    );
1077    if let Some(feeds) = &frontend.well_known.feeds {
1078        routes.extend(
1079            feeds
1080                .documents()
1081                .iter()
1082                .map(|document| String::from(document.path())),
1083        );
1084    }
1085    if let Some(analytics) = frontend.runtime.analytics.as_ref() {
1086        routes.push(analytics.script_path.clone());
1087        routes.push(analytics.event_path.clone());
1088    }
1089    routes
1090}
1091
1092/// The first-party proxy routes.
1093///
1094/// Split in two because the scripts sit at the root — where they read as
1095/// ordinary bundler output — while the endpoints they post to belong under the
1096/// API prefix.
1097#[cfg(feature = "pages")]
1098fn proxy_routes<S>(
1099    frontend: &super::frontend::Frontend<S>,
1100) -> (Router<WebServerState<S>>, Router<WebServerState<S>>)
1101where
1102    S: Clone + Send + Sync + 'static,
1103{
1104    use crate::analytics::{AnalyticsConfig, ScriptRelay, SentryDsn, relay_envelope, relay_event};
1105    use axum::body::Bytes;
1106    use axum::extract::ConnectInfo;
1107    use axum::http::HeaderMap;
1108    use axum::routing::post;
1109
1110    let client: reqwest::Client = reqwest::Client::new();
1111    let paths: &crate::templates::FrontendRuntime = &frontend.runtime;
1112
1113    let analytics_event_upstream: String = AnalyticsConfig::upstream_event_url();
1114    let sentry_envelope_upstream: String = frontend.sentry_dsn.upstream_envelope_url();
1115
1116    let script_route = |relay: ScriptRelay| {
1117        get(move |headers: HeaderMap| {
1118            let relay: ScriptRelay = relay.clone();
1119            async move { relay.respond(&headers).await }
1120        })
1121    };
1122    let mut scripts: Router<WebServerState<S>> = Router::new();
1123    // Analytics disabled (local, or no id): the routes are not mounted, so they
1124    // 404 and nothing ever reaches Plausible.
1125    if let (Some(analytics_paths), Some(upstream)) = (
1126        paths.analytics.as_ref(),
1127        frontend.analytics.upstream_script_url_if_enabled(),
1128    ) {
1129        scripts = scripts.route(
1130            &analytics_paths.script_path,
1131            script_route(ScriptRelay::new(client.clone(), upstream)),
1132        );
1133    }
1134    let scripts: Router<WebServerState<S>> = scripts.route(
1135        &paths.sentry_browser.script_path,
1136        script_route(ScriptRelay::new(
1137            client.clone(),
1138            SentryDsn::upstream_bundle_url(frontend.browser_traces_sample_rate.is_on()),
1139        )),
1140    );
1141
1142    // Nested under the API prefix, so the paths registered here are relative.
1143    let tunnel_path: String = strip_api_prefix(&paths.sentry_browser.tunnel_path);
1144
1145    let mut endpoints: Router<WebServerState<S>> = Router::new();
1146    if let Some(analytics_paths) = paths
1147        .analytics
1148        .as_ref()
1149        .filter(|_| frontend.analytics.is_enabled())
1150    {
1151        let event_path: String = strip_api_prefix(&analytics_paths.event_path);
1152        endpoints = endpoints.route(
1153            &event_path,
1154            post({
1155                let client: reqwest::Client = client.clone();
1156                let upstream: std::sync::Arc<str> =
1157                    std::sync::Arc::from(analytics_event_upstream.as_str());
1158                move |ConnectInfo(peer): ConnectInfo<SocketAddr>,
1159                      headers: HeaderMap,
1160                      body: Bytes| {
1161                    let client: reqwest::Client = client.clone();
1162                    let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1163                    async move { relay_event(&client, &upstream, &headers, peer, body).await }
1164                }
1165            }),
1166        );
1167    }
1168    let endpoints: Router<WebServerState<S>> = endpoints.route(
1169        &tunnel_path,
1170        post({
1171            let upstream: std::sync::Arc<str> =
1172                std::sync::Arc::from(sentry_envelope_upstream.as_str());
1173            move |body: Bytes| {
1174                let client: reqwest::Client = client.clone();
1175                let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1176                async move { relay_envelope(&client, &upstream, body).await }
1177            }
1178        }),
1179    );
1180
1181    (scripts, endpoints)
1182}
1183
1184/// `/api/v1/thing` → `/thing`, for a router that will be nested under the
1185/// prefix.
1186#[cfg(feature = "pages")]
1187fn strip_api_prefix(path: &str) -> String {
1188    path.strip_prefix(API_PREFIX)
1189        .map_or_else(|| path.to_string(), String::from)
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194
1195    mod static_paths {
1196        use crate::webserver::server::has_overlong_segment;
1197
1198        #[test]
1199        fn a_hashed_asset_name_is_servable() {
1200            let expected: bool = false;
1201            let actual: bool = has_overlong_segment("/css/main.0123456789abcdef.css");
1202            assert_eq!(expected, actual);
1203        }
1204
1205        #[test]
1206        fn a_segment_at_the_file_name_limit_is_still_tried() {
1207            let expected: bool = false;
1208            let actual: bool = has_overlong_segment(&format!("/js/{}", "a".repeat(255)));
1209            assert_eq!(expected, actual);
1210        }
1211
1212        #[test]
1213        fn a_segment_past_the_file_name_limit_is_a_404() {
1214            let expected: bool = true;
1215            let actual: bool = has_overlong_segment(&format!("/js/{}", "a".repeat(256)));
1216            assert_eq!(expected, actual);
1217        }
1218    }
1219
1220    #[cfg(all(feature = "analytics", feature = "observability"))]
1221    mod upstream_failures {
1222        use std::net::SocketAddr;
1223        use std::sync::Arc;
1224
1225        use axum::Router;
1226        use axum::body::Bytes;
1227        use axum::http::{HeaderMap, StatusCode};
1228        use axum::routing::post;
1229        use sentry::protocol::EnvelopeItem;
1230        use sentry::test::TestTransport;
1231        use sentry::{Client, ClientOptions, Hub, HubSwitchGuard};
1232        use tower::ServiceExt;
1233        use tracing_subscriber::Layer;
1234
1235        use crate::analytics::relay_event;
1236        use crate::webserver::server::with_middleware;
1237        use crate::webserver::telemetry::TraceRoutes;
1238
1239        /// How many Sentry events a POST to each of `paths` files, through the
1240        /// real middleware, with a proxy that relays a 503 upstream and a
1241        /// handler of the site's own that fails with a 500.
1242        async fn events_filed(path: &str) -> (StatusCode, usize) {
1243            let upstream: tokio::net::TcpListener = tokio::net::TcpListener::bind("127.0.0.1:0")
1244                .await
1245                .expect("a free port");
1246            let url: String = format!("http://{}/", upstream.local_addr().expect("an address"));
1247            tokio::spawn(async move {
1248                let app: Router =
1249                    Router::new().fallback(|| async { StatusCode::SERVICE_UNAVAILABLE });
1250                axum::serve(upstream, app).await.expect("serves");
1251            });
1252            let client: reqwest::Client = reqwest::Client::new();
1253            let router: Router = with_middleware(
1254                Router::new()
1255                    .route(
1256                        "/proxy",
1257                        post(move |headers: HeaderMap, body: Bytes| {
1258                            let client: reqwest::Client = client.clone();
1259                            let url: String = url.clone();
1260                            async move {
1261                                let peer: SocketAddr = "203.0.113.7:1".parse().expect("an address");
1262                                relay_event(&client, &url, &headers, peer, body).await
1263                            }
1264                        }),
1265                    )
1266                    .route(
1267                        "/boom",
1268                        post(|| async { StatusCode::INTERNAL_SERVER_ERROR }),
1269                    ),
1270                1024,
1271                false,
1272                TraceRoutes::new(Vec::new()),
1273            );
1274
1275            let transport: Arc<TestTransport> = TestTransport::new();
1276            let mut options: ClientOptions = ClientOptions::default();
1277            options.dsn = Some("https://public@sentry.invalid/1".parse().expect("a DSN"));
1278            options.transport = Some(Arc::new(transport.clone()));
1279            let hub: Arc<Hub> = Arc::new(Hub::new(
1280                Some(Arc::new(Client::from(options))),
1281                Arc::new(sentry::Scope::default()),
1282            ));
1283            let _hub: HubSwitchGuard = HubSwitchGuard::new(hub);
1284            let _subscriber: tracing::subscriber::DefaultGuard =
1285                tracing::subscriber::set_default(tracing_subscriber::layer::SubscriberExt::with(
1286                    tracing_subscriber::registry(),
1287                    // The production layer that turns `error!` into an event.
1288                    sentry::integrations::tracing::ErrorLayer::new()
1289                        .with_filter(tracing_subscriber::filter::LevelFilter::ERROR),
1290                ));
1291
1292            let response = router
1293                .oneshot(
1294                    axum::http::Request::builder()
1295                        .method("POST")
1296                        .uri(path)
1297                        .body(axum::body::Body::empty())
1298                        .expect("a valid request"),
1299                )
1300                .await
1301                .expect("a router never fails");
1302            let status: StatusCode = response.status();
1303            let events: usize = transport
1304                .fetch_and_clear_envelopes()
1305                .iter()
1306                .flat_map(|envelope| envelope.items())
1307                .filter(|item| matches!(item, EnvelopeItem::Event(_)))
1308                .count();
1309            (status, events)
1310        }
1311
1312        #[tokio::test(flavor = "current_thread")]
1313        async fn an_upstream_503_through_a_proxy_reaches_the_visitor_but_files_no_sentry_event() {
1314            let expected: (StatusCode, usize) = (StatusCode::SERVICE_UNAVAILABLE, 0);
1315            let actual: (StatusCode, usize) = events_filed("/proxy").await;
1316            assert_eq!(expected, actual);
1317        }
1318
1319        #[tokio::test(flavor = "current_thread")]
1320        async fn a_500_from_a_sites_own_handler_still_files_a_sentry_event() {
1321            let expected: (StatusCode, usize) = (StatusCode::INTERNAL_SERVER_ERROR, 1);
1322            let actual: (StatusCode, usize) = events_filed("/boom").await;
1323            assert_eq!(expected, actual);
1324        }
1325    }
1326
1327    #[cfg(feature = "pages")]
1328    mod conditional_get {
1329        use axum::http::{HeaderMap, HeaderValue, header};
1330
1331        use crate::webserver::server::if_none_match;
1332
1333        const ETAG: &str = "\"abc123\"";
1334
1335        fn headers(value: &str) -> HeaderMap {
1336            let mut headers: HeaderMap = HeaderMap::new();
1337            headers.insert(
1338                header::IF_NONE_MATCH,
1339                HeaderValue::from_str(value).expect("a valid header"),
1340            );
1341            headers
1342        }
1343
1344        #[test]
1345        fn a_request_without_the_header_always_gets_the_body() {
1346            let expected: bool = false;
1347            let actual: bool = if_none_match(&HeaderMap::new(), ETAG);
1348            assert_eq!(expected, actual);
1349        }
1350
1351        #[test]
1352        fn the_same_validator_means_the_reader_already_has_this_feed() {
1353            let expected: bool = true;
1354            let actual: bool = if_none_match(&headers(ETAG), ETAG);
1355            assert_eq!(expected, actual);
1356        }
1357
1358        #[test]
1359        fn a_weak_validator_still_matches_because_feeds_need_no_byte_equality() {
1360            let expected: bool = true;
1361            let actual: bool = if_none_match(&headers("W/\"abc123\""), ETAG);
1362            assert_eq!(expected, actual);
1363        }
1364
1365        #[test]
1366        fn a_star_matches_anything_that_exists() {
1367            let expected: bool = true;
1368            let actual: bool = if_none_match(&headers("*"), ETAG);
1369            assert_eq!(expected, actual);
1370        }
1371
1372        #[test]
1373        fn one_match_anywhere_in_the_list_is_enough() {
1374            // The header is a comma-separated list, so a naive string compare
1375            // against the whole value would re-send the body to a reader that
1376            // already holds it.
1377            let expected: bool = true;
1378            let actual: bool = if_none_match(&headers("\"other\", \"abc123\""), ETAG);
1379            assert_eq!(expected, actual);
1380        }
1381
1382        #[test]
1383        fn a_stale_validator_gets_the_new_document() {
1384            let expected: bool = false;
1385            let actual: bool = if_none_match(&headers("\"stale\""), ETAG);
1386            assert_eq!(expected, actual);
1387        }
1388    }
1389    use std::sync::Arc;
1390    use std::sync::atomic::{AtomicBool, Ordering};
1391    use std::time::Duration;
1392
1393    use axum::Router;
1394    use axum::routing::get;
1395    use tokio::time::timeout;
1396
1397    use super::super::shutdown::Shutdown;
1398    use super::{
1399        API_PREFIX, AppShutdown, DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_TIMEOUT, WebServerError, health,
1400        serve_on,
1401    };
1402
1403    /// Records whether cleanup ran, and can be made slow enough to overrun the
1404    /// drain window.
1405    #[derive(Clone)]
1406    struct RecordingState {
1407        ran: Arc<AtomicBool>,
1408        linger: Option<Duration>,
1409    }
1410
1411    impl RecordingState {
1412        fn instant() -> Self {
1413            Self {
1414                ran: Arc::new(AtomicBool::new(false)),
1415                linger: None,
1416            }
1417        }
1418    }
1419
1420    impl AppShutdown for RecordingState {
1421        async fn on_shutdown(&self) {
1422            if let Some(linger) = self.linger {
1423                tokio::time::sleep(linger).await;
1424            }
1425            self.ran.store(true, Ordering::SeqCst);
1426        }
1427    }
1428
1429    /// Serves `state` on an ephemeral port and returns once serving has ended.
1430    async fn serve_until_shutdown(
1431        state: RecordingState,
1432        shutdown: Shutdown,
1433    ) -> Result<(), WebServerError> {
1434        let router: Router = Router::new().route("/health", get(health));
1435        let cleanup: RecordingState = state.clone();
1436        // Port 0 asks the OS for a free one; nothing here connects to it.
1437        serve_on(router, "127.0.0.1", 0, shutdown, async move {
1438            cleanup.on_shutdown().await;
1439        })
1440        .await
1441    }
1442
1443    #[tokio::test]
1444    async fn app_cleanup_runs_when_the_shutdown_signal_arrives() {
1445        let shutdown: Shutdown = Shutdown::manual();
1446        let state: RecordingState = RecordingState::instant();
1447        let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1448
1449        shutdown.trigger();
1450        timeout(
1451            Duration::from_secs(1),
1452            serve_until_shutdown(state, shutdown.clone()),
1453        )
1454        .await
1455        .expect("serving ended promptly")
1456        .expect("serving ended cleanly");
1457
1458        let expected: bool = true;
1459        let actual: bool = ran.load(Ordering::SeqCst);
1460        assert_eq!(expected, actual);
1461    }
1462
1463    #[tokio::test]
1464    async fn app_cleanup_never_runs_when_the_server_dies_before_any_signal() {
1465        // An unparseable host fails before the listener binds, so no signal is
1466        // ever sent — the hook must be dropped unrun rather than awaited, or a
1467        // failed boot would hang until the drain window closed.
1468        let shutdown: Shutdown = Shutdown::manual();
1469        let state: RecordingState = RecordingState::instant();
1470        let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1471        let cleanup: RecordingState = state.clone();
1472
1473        let router: Router = Router::new().route("/health", get(health));
1474        let result: Result<(), WebServerError> = timeout(
1475            Duration::from_secs(1),
1476            serve_on(router, "not-an-ip", 0, shutdown, async move {
1477                cleanup.on_shutdown().await;
1478            }),
1479        )
1480        .await
1481        .expect("a bind failure returns immediately, it does not wait for cleanup");
1482
1483        assert!(result.is_err(), "an unparseable host is a bind error");
1484
1485        let expected: bool = false;
1486        let actual: bool = ran.load(Ordering::SeqCst);
1487        assert_eq!(expected, actual);
1488    }
1489
1490    #[tokio::test(start_paused = true)]
1491    async fn a_cleanup_that_overruns_the_window_is_cancelled_rather_than_awaited() {
1492        // Longer than the ceiling, so the hook cannot finish. With a paused
1493        // clock this costs no real time; the assertion is that serving still
1494        // returns, which it cannot do if the hook is awaited to completion.
1495        let shutdown: Shutdown = Shutdown::manual();
1496        let state: RecordingState = RecordingState {
1497            ran: Arc::new(AtomicBool::new(false)),
1498            linger: Some(DEFAULT_DRAIN_TIMEOUT * 2),
1499        };
1500        let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1501
1502        shutdown.trigger();
1503        serve_until_shutdown(state, shutdown.clone())
1504            .await
1505            .expect("serving still ends cleanly when cleanup is cancelled");
1506
1507        let expected: bool = false;
1508        let actual: bool = ran.load(Ordering::SeqCst);
1509        assert_eq!(
1510            expected, actual,
1511            "the hook was cancelled at its await, so it never reached its final store"
1512        );
1513    }
1514
1515    #[tokio::test]
1516    async fn a_server_with_nothing_in_flight_stops_at_once_instead_of_waiting_out_the_window() {
1517        let shutdown: Shutdown = Shutdown::manual();
1518        let router: Router = Router::new().route("/health", get(health));
1519
1520        // Port 0 asks the OS for a free one; nothing here connects to it.
1521        let serving: tokio::task::JoinHandle<Result<(), WebServerError>> = tokio::spawn({
1522            let shutdown: Shutdown = shutdown.clone();
1523            async move { serve_on(router, "127.0.0.1", 0, shutdown, async {}).await }
1524        });
1525
1526        shutdown.trigger();
1527
1528        // Far below the drain window: an unconditional wait fails here, which
1529        // is the bug — the window is a ceiling, not a delay.
1530        timeout(Duration::from_secs(1), serving)
1531            .await
1532            .expect("the server returned as soon as the drain began")
1533            .expect("the serving task did not panic")
1534            .expect("serving ended cleanly");
1535    }
1536
1537    #[test]
1538    fn the_body_limit_accommodates_an_ordinary_form_post() {
1539        // 1 KiB — the previous default — rejected almost any real submission,
1540        // so every project had to override it.
1541        let expected: usize = 256 * 1024;
1542        let actual: usize = DEFAULT_BODY_LIMIT;
1543        assert_eq!(expected, actual);
1544    }
1545
1546    #[cfg(feature = "pages")]
1547    #[test]
1548    fn stripping_the_prefix_leaves_a_nestable_path() {
1549        let expected: String = String::from("/boggledygook-a3f2c1d8");
1550        let actual: String = super::strip_api_prefix("/api/v1/boggledygook-a3f2c1d8");
1551        assert_eq!(expected, actual);
1552    }
1553
1554    #[test]
1555    fn the_api_prefix_is_the_one_every_project_shares() {
1556        assert_eq!("/api/v1", API_PREFIX);
1557    }
1558}