Skip to main content

webserver_base/webserver/
server.rs

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