use laravel::axum::body::{Body, to_bytes};
use laravel::axum::http::{HeaderValue, Method, StatusCode, header};
use laravel::http::{Middleware, Next, Request, Response};
use crate::Config;
#[derive(Clone)]
pub struct CacheControl(String);
impl CacheControl {
#[must_use]
pub fn new(directives: &str) -> Self {
Self(directives.to_owned())
}
}
#[derive(Clone)]
struct RouteCacheControl(String);
impl Middleware for CacheControl {
async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
let mut response = next.run(request).await.into_http();
response
.extensions_mut()
.insert(RouteCacheControl(self.0.clone()));
Ok(Response::from_http(response))
}
}
pub(crate) struct DefaultCacheControl;
impl Middleware for DefaultCacheControl {
async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
let mut response = next.run(request).await.into_http();
let headers = response.headers_mut();
if !headers.contains_key(header::CACHE_CONTROL) {
let value = if headers.contains_key(header::LAST_MODIFIED)
|| headers.contains_key(header::EXPIRES)
{
"must-revalidate, private"
} else {
"no-cache, private"
};
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(value));
}
Ok(Response::from_http(response))
}
}
fn normalize(value: &str) -> String {
let mut directives: Vec<(String, Option<String>)> = value
.split(',')
.map(str::trim)
.filter(|directive| !directive.is_empty())
.map(|directive| match directive.split_once('=') {
Some((name, value)) => (
name.trim().to_ascii_lowercase(),
Some(value.trim().to_owned()),
),
None => (directive.to_ascii_lowercase(), None),
})
.collect();
if !directives
.iter()
.any(|(name, _)| matches!(name.as_str(), "public" | "private" | "s-maxage"))
{
directives.push(("private".to_owned(), None));
}
directives.sort_by(|a, b| a.0.cmp(&b.0));
directives.dedup_by(|a, b| a.0 == b.0);
directives
.into_iter()
.map(|(name, value)| value.map_or_else(|| name.clone(), |value| format!("{name}={value}")))
.collect::<Vec<_>>()
.join(", ")
}
fn matches(if_none_match: &str, etag: &str) -> bool {
let opaque = |tag: &str| tag.trim().trim_start_matches("W/").to_owned();
let etag = opaque(etag);
if_none_match
.split(',')
.map(str::trim)
.any(|tag| tag == "*" || opaque(tag) == etag)
}
pub(crate) async fn apply(
config: &Config,
method: &Method,
if_none_match: Option<&str>,
variant: &str,
response: Response,
) -> Response {
if method != Method::GET && method != Method::HEAD {
return response;
}
let mut http = response.into_http();
let mut vary: Vec<String> = http
.headers()
.get_all(header::VARY)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(',').map(|name| name.trim().to_owned()))
.filter(|name| !name.is_empty())
.collect();
for name in config.vary_headers() {
if !vary.iter().any(|known| known.eq_ignore_ascii_case(&name)) {
vary.push(name);
}
}
if let Ok(value) = HeaderValue::try_from(vary.join(", ")) {
http.headers_mut().insert(header::VARY, value);
}
if http.status() != StatusCode::OK {
return Response::from_http(http);
}
let cache_control = http
.extensions()
.get::<RouteCacheControl>()
.map(|route| route.0.clone())
.or_else(|| config.http_cache.cache_control.clone())
.filter(|value| !value.is_empty());
if let Some(value) = cache_control
&& let Ok(value) = HeaderValue::try_from(normalize(&value))
{
http.headers_mut().insert(header::CACHE_CONTROL, value);
}
if !config.http_cache.etags {
return Response::from_http(http);
}
if !http.headers().contains_key(header::ETAG) {
if method == Method::HEAD {
return Response::from_http(http);
}
let (mut parts, body) = http.into_parts();
let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
if bytes.is_empty() {
return Response::from_http(laravel::axum::http::Response::from_parts(
parts,
Body::empty(),
));
}
let mut input = format!("{variant}\n").into_bytes();
input.extend_from_slice(&bytes);
let hash = xxhash_rust::xxh3::xxh3_128(&input);
if let Ok(value) = HeaderValue::try_from(format!("W/\"{hash:032x}\"")) {
parts.headers.insert(header::ETAG, value);
}
http = laravel::axum::http::Response::from_parts(parts, Body::from(bytes));
}
let etag = http
.headers()
.get(header::ETAG)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
if !if_none_match.is_some_and(|value| matches(value, etag)) {
return Response::from_http(http);
}
let (mut parts, _) = http.into_parts();
parts.status = StatusCode::NOT_MODIFIED;
parts.headers.remove(header::CONTENT_TYPE);
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_http(laravel::axum::http::Response::from_parts(
parts,
Body::empty(),
))
}
#[cfg(test)]
mod tests {
use super::{matches, normalize};
#[test]
fn cache_control_is_written_as_symfony_writes_it() {
assert_eq!(normalize("private, max-age=10"), "max-age=10, private");
assert_eq!(normalize("private, no-cache"), "no-cache, private");
assert_eq!(normalize("max-age=60"), "max-age=60, private");
assert_eq!(normalize("public, max-age=60"), "max-age=60, public");
assert_eq!(normalize("s-maxage=60"), "s-maxage=60");
}
#[test]
fn if_none_match_compares_weakly() {
assert!(matches("W/\"abc\"", "W/\"abc\""));
assert!(matches("\"abc\"", "W/\"abc\""));
assert!(matches("W/\"x\", W/\"abc\"", "W/\"abc\""));
assert!(matches("*", "W/\"abc\""));
assert!(!matches("W/\"abcd\"", "W/\"abc\""));
}
}