use axum::body::Body;
use axum::extract::Request;
use axum::http::header::{CACHE_CONTROL, ETAG, IF_NONE_MATCH, VARY};
use axum::http::{HeaderValue, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
const CACHE_DIRECTIVE: &str = "private, no-cache";
const VARY_ON: &str = "Cookie";
const MAX_ETAG_BODY: usize = 8 * 1024 * 1024;
pub async fn layer(req: Request, next: Next) -> Response {
let if_none_match = req
.headers()
.get(IF_NONE_MATCH)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
let resp = next.run(req).await;
let status = resp.status();
let (mut parts, body) = resp.into_parts();
parts.headers.insert(
CACHE_CONTROL,
HeaderValue::from_static(CACHE_DIRECTIVE),
);
append_vary(&mut parts.headers, VARY_ON);
if !status.is_success() {
return Response::from_parts(parts, body);
}
let bytes = match axum::body::to_bytes(body, MAX_ETAG_BODY).await {
Ok(b) => b,
Err(e) => {
tracing::warn!(target: "rustango_cms::api", error = %e, "could not buffer body for ETag");
return crate::api::error::ApiError::internal().into_response();
}
};
let etag = weak_etag(&bytes);
if let Ok(value) = HeaderValue::from_str(&etag) {
parts.headers.insert(ETAG, value);
}
if if_none_match.is_some_and(|h| if_none_match_matches(&h, &etag)) {
parts.status = StatusCode::NOT_MODIFIED;
parts.headers.remove(axum::http::header::CONTENT_LENGTH);
return Response::from_parts(parts, Body::empty());
}
Response::from_parts(parts, Body::from(bytes))
}
fn weak_etag(bytes: &[u8]) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for b in bytes {
hash ^= u64::from(*b);
hash = hash.wrapping_mul(0x100_0000_01b3);
}
format!("W/\"{hash:016x}-{}\"", bytes.len())
}
fn if_none_match_matches(header: &str, etag: &str) -> bool {
let strip = |s: &str| s.trim().trim_start_matches("W/").trim().to_owned();
let want = strip(etag);
header
.split(',')
.any(|candidate| candidate.trim() == "*" || strip(candidate) == want)
}
fn append_vary(headers: &mut axum::http::HeaderMap, value: &str) {
let existing = headers
.get(VARY)
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_owned();
if existing
.split(',')
.any(|v| v.trim().eq_ignore_ascii_case(value))
{
return;
}
let merged = if existing.is_empty() {
value.to_owned()
} else {
format!("{existing}, {value}")
};
if let Ok(v) = HeaderValue::from_str(&merged) {
headers.insert(VARY, v);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_etag_changes_with_the_body_and_not_otherwise() {
assert_eq!(weak_etag(b"hello"), weak_etag(b"hello"));
assert_ne!(weak_etag(b"hello"), weak_etag(b"hellp"));
assert_ne!(weak_etag(b"hello"), weak_etag(b"hello "));
}
#[test]
fn the_etag_is_marked_weak() {
assert!(weak_etag(b"x").starts_with("W/\""));
}
#[test]
fn if_none_match_compares_weakly() {
let tag = weak_etag(b"body");
assert!(if_none_match_matches(&tag, &tag));
let stripped = tag.trim_start_matches("W/").to_owned();
assert!(if_none_match_matches(&stripped, &tag));
}
#[test]
fn if_none_match_accepts_a_list_and_a_wildcard() {
let tag = weak_etag(b"body");
assert!(if_none_match_matches(&format!("W/\"other\", {tag}"), &tag));
assert!(if_none_match_matches("*", &tag));
assert!(!if_none_match_matches("W/\"other\"", &tag));
}
#[test]
fn append_vary_is_idempotent_and_additive() {
let mut h = axum::http::HeaderMap::new();
append_vary(&mut h, "Cookie");
append_vary(&mut h, "Cookie");
assert_eq!(h.get(VARY).unwrap(), "Cookie");
let mut h = axum::http::HeaderMap::new();
h.insert(VARY, HeaderValue::from_static("Accept"));
append_vary(&mut h, "Cookie");
assert_eq!(h.get(VARY).unwrap(), "Accept, Cookie");
}
#[test]
fn append_vary_matches_case_insensitively() {
let mut h = axum::http::HeaderMap::new();
h.insert(VARY, HeaderValue::from_static("cookie"));
append_vary(&mut h, "Cookie");
assert_eq!(h.get(VARY).unwrap(), "cookie");
}
}