fusion_stack/
http_cache.rs1use laravel::axum::body::{Body, to_bytes};
7use laravel::axum::http::{HeaderValue, Method, StatusCode, header};
8use laravel::http::{Middleware, Next, Request, Response};
9
10use crate::Config;
11
12#[derive(Clone)]
23pub struct CacheControl(String);
24
25impl CacheControl {
26 #[must_use]
28 pub fn new(directives: &str) -> Self {
29 Self(directives.to_owned())
30 }
31}
32
33#[derive(Clone)]
35struct RouteCacheControl(String);
36
37impl Middleware for CacheControl {
38 async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
39 let mut response = next.run(request).await.into_http();
40 response
41 .extensions_mut()
42 .insert(RouteCacheControl(self.0.clone()));
43 Ok(Response::from_http(response))
44 }
45}
46
47pub(crate) struct DefaultCacheControl;
49
50impl Middleware for DefaultCacheControl {
51 async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
52 let mut response = next.run(request).await.into_http();
53 let headers = response.headers_mut();
54 if !headers.contains_key(header::CACHE_CONTROL) {
55 let value = if headers.contains_key(header::LAST_MODIFIED)
56 || headers.contains_key(header::EXPIRES)
57 {
58 "must-revalidate, private"
59 } else {
60 "no-cache, private"
61 };
62 headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(value));
63 }
64 Ok(Response::from_http(response))
65 }
66}
67
68fn normalize(value: &str) -> String {
71 let mut directives: Vec<(String, Option<String>)> = value
72 .split(',')
73 .map(str::trim)
74 .filter(|directive| !directive.is_empty())
75 .map(|directive| match directive.split_once('=') {
76 Some((name, value)) => (
77 name.trim().to_ascii_lowercase(),
78 Some(value.trim().to_owned()),
79 ),
80 None => (directive.to_ascii_lowercase(), None),
81 })
82 .collect();
83 if !directives
84 .iter()
85 .any(|(name, _)| matches!(name.as_str(), "public" | "private" | "s-maxage"))
86 {
87 directives.push(("private".to_owned(), None));
88 }
89 directives.sort_by(|a, b| a.0.cmp(&b.0));
90 directives.dedup_by(|a, b| a.0 == b.0);
91 directives
92 .into_iter()
93 .map(|(name, value)| value.map_or_else(|| name.clone(), |value| format!("{name}={value}")))
94 .collect::<Vec<_>>()
95 .join(", ")
96}
97
98fn matches(if_none_match: &str, etag: &str) -> bool {
100 let opaque = |tag: &str| tag.trim().trim_start_matches("W/").to_owned();
101 let etag = opaque(etag);
102 if_none_match
103 .split(',')
104 .map(str::trim)
105 .any(|tag| tag == "*" || opaque(tag) == etag)
106}
107
108pub(crate) async fn apply(
112 config: &Config,
113 method: &Method,
114 if_none_match: Option<&str>,
115 variant: &str,
116 response: Response,
117) -> Response {
118 if method != Method::GET && method != Method::HEAD {
119 return response;
120 }
121 let mut http = response.into_http();
122
123 let mut vary: Vec<String> = http
125 .headers()
126 .get_all(header::VARY)
127 .iter()
128 .filter_map(|value| value.to_str().ok())
129 .flat_map(|value| value.split(',').map(|name| name.trim().to_owned()))
130 .filter(|name| !name.is_empty())
131 .collect();
132 for name in config.vary_headers() {
133 if !vary.iter().any(|known| known.eq_ignore_ascii_case(&name)) {
134 vary.push(name);
135 }
136 }
137 if let Ok(value) = HeaderValue::try_from(vary.join(", ")) {
138 http.headers_mut().insert(header::VARY, value);
139 }
140
141 if http.status() != StatusCode::OK {
142 return Response::from_http(http);
143 }
144
145 let cache_control = http
146 .extensions()
147 .get::<RouteCacheControl>()
148 .map(|route| route.0.clone())
149 .or_else(|| config.http_cache.cache_control.clone())
150 .filter(|value| !value.is_empty());
151 if let Some(value) = cache_control
152 && let Ok(value) = HeaderValue::try_from(normalize(&value))
153 {
154 http.headers_mut().insert(header::CACHE_CONTROL, value);
155 }
156
157 if !config.http_cache.etags {
158 return Response::from_http(http);
159 }
160
161 if !http.headers().contains_key(header::ETAG) {
162 if method == Method::HEAD {
164 return Response::from_http(http);
165 }
166 let (mut parts, body) = http.into_parts();
167 let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
168 if bytes.is_empty() {
169 return Response::from_http(laravel::axum::http::Response::from_parts(
170 parts,
171 Body::empty(),
172 ));
173 }
174 let mut input = format!("{variant}\n").into_bytes();
175 input.extend_from_slice(&bytes);
176 let hash = xxhash_rust::xxh3::xxh3_128(&input);
177 if let Ok(value) = HeaderValue::try_from(format!("W/\"{hash:032x}\"")) {
178 parts.headers.insert(header::ETAG, value);
179 }
180 http = laravel::axum::http::Response::from_parts(parts, Body::from(bytes));
181 }
182
183 let etag = http
184 .headers()
185 .get(header::ETAG)
186 .and_then(|value| value.to_str().ok())
187 .unwrap_or_default();
188 if !if_none_match.is_some_and(|value| matches(value, etag)) {
189 return Response::from_http(http);
190 }
191
192 let (mut parts, _) = http.into_parts();
194 parts.status = StatusCode::NOT_MODIFIED;
195 parts.headers.remove(header::CONTENT_TYPE);
196 parts.headers.remove(header::CONTENT_LENGTH);
197 Response::from_http(laravel::axum::http::Response::from_parts(
198 parts,
199 Body::empty(),
200 ))
201}
202
203#[cfg(test)]
204mod tests {
205 use super::{matches, normalize};
206
207 #[test]
208 fn cache_control_is_written_as_symfony_writes_it() {
209 assert_eq!(normalize("private, max-age=10"), "max-age=10, private");
210 assert_eq!(normalize("private, no-cache"), "no-cache, private");
211 assert_eq!(normalize("max-age=60"), "max-age=60, private");
212 assert_eq!(normalize("public, max-age=60"), "max-age=60, public");
213 assert_eq!(normalize("s-maxage=60"), "s-maxage=60");
214 }
215
216 #[test]
217 fn if_none_match_compares_weakly() {
218 assert!(matches("W/\"abc\"", "W/\"abc\""));
219 assert!(matches("\"abc\"", "W/\"abc\""));
220 assert!(matches("W/\"x\", W/\"abc\"", "W/\"abc\""));
221 assert!(matches("*", "W/\"abc\""));
222 assert!(!matches("W/\"abcd\"", "W/\"abc\""));
223 }
224}