Skip to main content

agentmux_srv/server/
ui_cache.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How the served web UI is cached by a browser. A headless server serves the built UI from a folder, and the
5//! package's files carried one fixed modification date, no validator and no `Cache-Control`: a browser then kept the
6//! old shell (`index.html`) for weeks, and a revalidation by that date was answered "not modified" after the server was
7//! upgraded, so a normal reload kept showing the old version.
8//!
9//! The rules, by file:
10//! - `/assets/*` (Vite names each by its content hash): cached for a year and immutable. `private`, because the
11//!   server answers on the person's own address only.
12//! - every other file (`index.html`, which also answers any path no file claims, `early-boot.js`, `/fonts/*` and
13//!   `/fontawesome/*`, none of which carry a hash): `no-cache`, so the browser asks again each time, with an `ETag` of
14//!   the file's content, so a file that did not change costs a `304` and one that did is sent whole.
15//! - no file is ever dated: `Last-Modified` is dropped, and an `If-Modified-Since` is not heard, because a browser that
16//!   cached an older server's file holds only that date to ask with, and the answer to it must be the file.
17
18use axum::body::Body;
19use axum::extract::Request;
20use axum::http::{header, HeaderValue, StatusCode};
21use axum::middleware::Next;
22use axum::response::Response;
23use sha2::{Digest, Sha256};
24
25/// The longest file given an `ETag` (it is read whole to hash it): the largest un-hashed file is a font.
26const MAX_HASHED_BYTES: usize = 16 * 1024 * 1024;
27
28const IMMUTABLE: &str = "private, max-age=31536000, immutable";
29const REVALIDATE: &str = "no-cache";
30
31/// Middleware for the served UI's files; see the module's rules.
32pub(crate) async fn ui_cache(mut req: Request, next: Next) -> Response {
33    let path = req.uri().path().to_string();
34    let is_get = req.method() == axum::http::Method::GET;
35    let if_none_match = req.headers().get(header::IF_NONE_MATCH).cloned();
36    req.headers_mut().remove(header::IF_MODIFIED_SINCE);
37    let mut response = next.run(req).await;
38    response.headers_mut().remove(header::LAST_MODIFIED);
39    if !response.status().is_success() {
40        return response;
41    }
42    // A name under /assets/ that is no file is answered with the app's page (a single-page app's fallback): that is
43    // not a hashed file, and a year of caching it would pin the page as the script.
44    let is_page = response.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
45    if path.starts_with("/assets/") && !is_page {
46        response.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(IMMUTABLE));
47        return response;
48    }
49    response.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(REVALIDATE));
50    if response.status() != StatusCode::OK || !is_get {
51        // A range of a file (206) has no validator of its own here, and a HEAD is answered with no body to hash: a tag
52        // made of nothing would be the same for every file and differ from the GET's.
53        return response;
54    }
55    let (mut parts, body) = response.into_parts();
56    let Ok(bytes) = axum::body::to_bytes(body, MAX_HASHED_BYTES).await else {
57        return Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Body::empty()).unwrap_or_default();
58    };
59    let etag = format!("\"{}\"", hex::encode(&Sha256::digest(&bytes)[..16]));
60    if let Ok(value) = HeaderValue::from_str(&etag) {
61        parts.headers.insert(header::ETAG, value);
62    }
63    if if_none_match.as_ref().and_then(|v| v.to_str().ok()).is_some_and(|v| matches(v, &etag)) {
64        parts.status = StatusCode::NOT_MODIFIED;
65        parts.headers.remove(header::CONTENT_LENGTH);
66        parts.headers.remove(header::CONTENT_TYPE);
67        return Response::from_parts(parts, Body::empty());
68    }
69    Response::from_parts(parts, Body::from(bytes))
70}
71
72/// Does an `If-None-Match` value name this tag (any of a list, or `*`; a weak tag counts as its strong form)?
73fn matches(header: &str, etag: &str) -> bool {
74    header.split(',').map(str::trim).any(|t| t == "*" || t.strip_prefix("W/").unwrap_or(t) == etag)
75}
76
77#[cfg(test)]
78#[path = "tests/ui_cache_tests.rs"]
79mod tests;