Lines
96 %
Functions
50 %
Branches
100 %
//! Static assets are served under a path carrying the build id, so a deploy
//! changes every asset URL and browsers never reuse a stale one.
use axum::{
Router,
extract::Request,
http::{HeaderValue, header::CACHE_CONTROL},
middleware::{self, Next},
response::Response,
};
use tower_http::services::ServeDir;
#[cfg(test)]
mod tests;
pub const BUILD_ID: &str = env!("NOMI_BUILD_ID");
const IMMUTABLE: &str = "public, max-age=31536000, immutable";
const REVALIDATE: &str = "no-cache";
fn versioned_prefix() -> String {
format!("/static/{BUILD_ID}/")
}
/// Serves `dir` at `/static/<build id>/` and, for pages cached before a deploy,
/// at the bare `/static/`.
pub fn static_files<S: Clone + Send + Sync + 'static>(dir: &str) -> Router<S> {
Router::new()
.nest_service(&format!("/static/{BUILD_ID}"), ServeDir::new(dir))
.nest_service("/static", ServeDir::new(dir))
async fn cache_policy(request: Request, next: Next) -> Response {
let versioned = request.uri().path().starts_with(&versioned_prefix());
let mut response = next.run(request).await;
if response.headers().contains_key(CACHE_CONTROL) {
return response;
let policy = match versioned && response.status().is_success() {
true => IMMUTABLE,
false => REVALIDATE,
response
.headers_mut()
.insert(CACHE_CONTROL, HeaderValue::from_static(policy));
/// Versioned assets are cached for good; every other response, pages included,
/// must be revalidated.
pub fn with_cache_policy(router: Router) -> Router {
router.layer(middleware::from_fn(cache_policy))