Skip to main content

webserver_base/webserver/
server.rs

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