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

            
4
use axum::{
5
    Router,
6
    extract::Request,
7
    http::{HeaderValue, header::CACHE_CONTROL},
8
    middleware::{self, Next},
9
    response::Response,
10
};
11
use tower_http::services::ServeDir;
12

            
13
#[cfg(test)]
14
mod tests;
15

            
16
pub const BUILD_ID: &str = env!("NOMI_BUILD_ID");
17

            
18
const IMMUTABLE: &str = "public, max-age=31536000, immutable";
19
const REVALIDATE: &str = "no-cache";
20

            
21
10
fn versioned_prefix() -> String {
22
10
    format!("/static/{BUILD_ID}/")
23
10
}
24

            
25
/// Serves `dir` at `/static/<build id>/` and, for pages cached before a deploy,
26
/// at the bare `/static/`.
27
2
pub fn static_files<S: Clone + Send + Sync + 'static>(dir: &str) -> Router<S> {
28
2
    Router::new()
29
2
        .nest_service(&format!("/static/{BUILD_ID}"), ServeDir::new(dir))
30
2
        .nest_service("/static", ServeDir::new(dir))
31
2
}
32

            
33
8
async fn cache_policy(request: Request, next: Next) -> Response {
34
8
    let versioned = request.uri().path().starts_with(&versioned_prefix());
35
8
    let mut response = next.run(request).await;
36
8
    if response.headers().contains_key(CACHE_CONTROL) {
37
        return response;
38
8
    }
39
8
    let policy = match versioned && response.status().is_success() {
40
2
        true => IMMUTABLE,
41
6
        false => REVALIDATE,
42
    };
43
8
    response
44
8
        .headers_mut()
45
8
        .insert(CACHE_CONTROL, HeaderValue::from_static(policy));
46
8
    response
47
8
}
48

            
49
/// Versioned assets are cached for good; every other response, pages included,
50
/// must be revalidated.
51
2
pub fn with_cache_policy(router: Router) -> Router {
52
2
    router.layer(middleware::from_fn(cache_policy))
53
2
}