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