Skip to main content

web/
assets.rs

1//! Static assets are served under a path carrying the build id, so a deploy
2//! changes every asset URL and browsers never reuse a stale one.
3
4use axum::{
5    Router,
6    extract::Request,
7    http::{HeaderValue, header::CACHE_CONTROL},
8    middleware::{self, Next},
9    response::Response,
10};
11use tower_http::services::ServeDir;
12
13#[cfg(test)]
14mod tests;
15
16pub const BUILD_ID: &str = env!("NOMI_BUILD_ID");
17
18const IMMUTABLE: &str = "public, max-age=31536000, immutable";
19const REVALIDATE: &str = "no-cache";
20
21fn versioned_prefix() -> String {
22    format!("/static/{BUILD_ID}/")
23}
24
25/// Serves `dir` at `/static/<build id>/` and, for pages cached before a deploy,
26/// at the bare `/static/`.
27pub fn static_files<S: Clone + Send + Sync + 'static>(dir: &str) -> Router<S> {
28    Router::new()
29        .nest_service(&format!("/static/{BUILD_ID}"), ServeDir::new(dir))
30        .nest_service("/static", ServeDir::new(dir))
31}
32
33async fn cache_policy(request: Request, next: Next) -> Response {
34    let versioned = request.uri().path().starts_with(&versioned_prefix());
35    let mut response = next.run(request).await;
36    if response.headers().contains_key(CACHE_CONTROL) {
37        return response;
38    }
39    let policy = match versioned && response.status().is_success() {
40        true => IMMUTABLE,
41        false => REVALIDATE,
42    };
43    response
44        .headers_mut()
45        .insert(CACHE_CONTROL, HeaderValue::from_static(policy));
46    response
47}
48
49/// Versioned assets are cached for good; every other response, pages included,
50/// must be revalidated.
51pub fn with_cache_policy(router: Router) -> Router {
52    router.layer(middleware::from_fn(cache_policy))
53}