Skip to main content

webserver_base/webserver/
server.rs

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