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