1use std::time::Duration;
16
17use base64::Engine;
18use base64::engine::general_purpose::STANDARD;
19use laravel::axum::body::{Body, to_bytes};
20use laravel::axum::http::{HeaderName, HeaderValue, Method, StatusCode, header};
21use laravel::cache::Repository;
22use laravel::http::{Middleware, Next, Request, Response};
23use serde::{Deserialize, Serialize};
24use serde_json::{Map, Value, json};
25
26use crate::{Context, query_string};
27
28pub const HEADER: &str = "x-response-cache";
30
31const PREFIX: &str = "fusion-stack:response-cache:";
32
33const UNSTORED_HEADERS: [&str; 5] = [
35 "date",
36 "x-request-id",
37 "cache-control",
38 HEADER,
39 "set-cookie",
40];
41
42const UNORDERED: [&str; 2] = ["include", "fields"];
44
45const GENERATION_TTL: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60);
47
48#[derive(Clone)]
65pub struct CacheResponse {
66 ttl: u64,
67 tags: Vec<String>,
68 shared: bool,
69}
70
71impl CacheResponse {
72 #[must_use]
74 pub const fn new(ttl: u64) -> Self {
75 Self {
76 ttl,
77 tags: Vec::new(),
78 shared: false,
79 }
80 }
81
82 #[must_use]
84 pub fn tags<I: IntoIterator<Item = S>, S: Into<String>>(mut self, tags: I) -> Self {
85 self.tags = tags.into_iter().map(Into::into).collect();
86 self
87 }
88
89 #[must_use]
91 pub const fn shared(mut self) -> Self {
92 self.shared = true;
93 self
94 }
95}
96
97#[derive(Serialize, Deserialize)]
98struct Cached {
99 status: u16,
100 headers: Vec<(String, String)>,
101 body: String,
102}
103
104impl Middleware for CacheResponse {
105 async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
106 let context = request.extension::<Context>().cloned();
107 let method = request.method().clone();
108 let enabled = context
109 .as_ref()
110 .is_some_and(|context| context.state.config.response_cache.enabled);
111 if !enabled || (method != Method::GET && method != Method::HEAD) {
112 return Ok(next.run(request).await);
113 }
114 let Some(context) = context else {
115 return Ok(next.run(request).await);
116 };
117 if !self.shared && context.client.is_none() && request.authenticated().await? {
120 return Ok(next.run(request).await);
121 }
122 let store = store(context.state.config.response_cache.store.as_deref())?;
123
124 let account = if self.shared {
125 None
126 } else {
127 Some(
128 context
129 .client
130 .as_ref()
131 .map_or_else(|| "guest".to_owned(), |client| client.id.clone()),
132 )
133 };
134 let key = key(&request, account.as_deref());
135 let tags: Vec<String> = self.tags.iter().map(|tag| tag_for(tag, &request)).collect();
136 let entry = entry_key(&store, &key, &tags).await?;
137
138 if let Some(cached) = store.get::<Cached>(&entry).await? {
139 return Ok(rebuild(cached));
140 }
141
142 let response = next.run(request).await.into_http();
143 if response.status() != StatusCode::OK
145 || method == Method::HEAD
146 || response.headers().contains_key(header::SET_COOKIE)
147 {
148 return Ok(Response::from_http(response));
149 }
150 let (mut parts, body) = response.into_parts();
151 let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
152 let cached = Cached {
153 status: 200,
154 headers: parts
155 .headers
156 .iter()
157 .filter(|(name, _)| !UNSTORED_HEADERS.contains(&name.as_str()))
158 .filter_map(|(name, value)| {
159 Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
160 })
161 .collect(),
162 body: STANDARD.encode(&bytes),
163 };
164 store
165 .put(&entry, &cached, Duration::from_secs(self.ttl))
166 .await?;
167 parts.headers.insert(
168 HeaderName::from_static(HEADER),
169 HeaderValue::from_static("miss"),
170 );
171 Ok(Response::from_http(
172 laravel::axum::http::Response::from_parts(parts, Body::from(bytes)),
173 ))
174 }
175}
176
177pub async fn flush<I: IntoIterator<Item = S>, S: AsRef<str>>(tags: I) -> laravel::Result<()> {
185 flush_in(None, tags).await
186}
187
188pub async fn flush_in<I: IntoIterator<Item = S>, S: AsRef<str>>(
194 store_name: Option<&str>,
195 tags: I,
196) -> laravel::Result<()> {
197 let store = store(store_name)?;
198 for tag in tags {
199 store
200 .put(
201 &format!("{PREFIX}tag:{}", tag.as_ref()),
202 laravel::str::random(16),
203 GENERATION_TTL,
204 )
205 .await?;
206 }
207 Ok(())
208}
209
210fn store(name: Option<&str>) -> laravel::Result<Repository> {
211 match name {
212 Some(name) => laravel::cache::store(name),
213 None => laravel::cache::manager().default_store(),
214 }
215}
216
217fn rebuild(cached: Cached) -> Response {
218 let mut response = laravel::axum::http::Response::new(Body::from(
219 STANDARD.decode(cached.body).unwrap_or_default(),
220 ));
221 *response.status_mut() = StatusCode::from_u16(cached.status).unwrap_or(StatusCode::OK);
222 let headers = response.headers_mut();
223 for (name, value) in cached.headers {
224 if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) {
225 headers.append(name, value);
226 }
227 }
228 headers.insert(
229 HeaderName::from_static(HEADER),
230 HeaderValue::from_static("hit"),
231 );
232 Response::from_http(response)
233}
234
235fn tag_for(tag: &str, request: &Request) -> String {
237 let Some(route) = request.current_route() else {
238 return tag.to_owned();
239 };
240 let mut tag = tag.to_owned();
241 for (name, value) in route.params() {
242 tag = tag.replace(&format!("{{{name}}}"), value);
243 }
244 tag
245}
246
247#[must_use]
255pub fn cache_key(request: &Request) -> (String, Value) {
256 let context = request.extension::<Context>();
257 let version = context
258 .and_then(|context| context.version.as_ref())
259 .map(|(version, _)| version.to_string());
260 let account = context
261 .and_then(|context| context.client.as_ref())
262 .map_or_else(|| "guest".to_owned(), |client| client.id.clone());
263 let parts = parts(request, version.as_deref(), Some(&account));
264 (key_of(&parts), parts)
265}
266
267fn parts(request: &Request, version: Option<&str>, account: Option<&str>) -> Value {
268 json!({
269 "method": "GET",
270 "path": format!("/{}", request.path().trim_start_matches('/')),
271 "version": version,
272 "account": account,
273 "query": normalise(query_string::parse(request.uri().query().unwrap_or_default()), None),
274 })
275}
276
277fn key_of(parts: &Value) -> String {
278 format!(
279 "fusion-stack:{:032x}",
280 xxhash_rust::xxh3::xxh3_128(php_json(parts).as_bytes())
281 )
282}
283
284fn key(request: &Request, account: Option<&str>) -> String {
286 key_of(&parts(request, None, account))
287}
288
289fn php_json(value: &Value) -> String {
292 match value {
293 Value::String(text) => {
294 let mut out = String::from("\"");
295 for unit in text.encode_utf16() {
296 match unit {
297 0x22 => out.push_str("\\\""),
298 0x5C => out.push_str("\\\\"),
299 0x2F => out.push_str("\\/"),
300 0x08 => out.push_str("\\b"),
301 0x0C => out.push_str("\\f"),
302 0x0A => out.push_str("\\n"),
303 0x0D => out.push_str("\\r"),
304 0x09 => out.push_str("\\t"),
305 0x20..=0x7E => out.push(char::from(u8::try_from(unit).unwrap_or(b'?'))),
306 _ => out.push_str(&format!("\\u{unit:04x}")),
307 }
308 }
309 out.push('"');
310 out
311 }
312 Value::Array(items) => format!(
313 "[{}]",
314 items.iter().map(php_json).collect::<Vec<_>>().join(",")
315 ),
316 Value::Object(map) if map.is_empty() => "[]".to_owned(),
317 Value::Object(map) => format!(
318 "{{{}}}",
319 map.iter()
320 .map(|(key, value)| format!(
321 "{}:{}",
322 php_json(&Value::String(key.clone())),
323 php_json(value)
324 ))
325 .collect::<Vec<_>>()
326 .join(",")
327 ),
328 other => other.to_string(),
329 }
330}
331
332fn normalise(query: Map<String, Value>, parent: Option<&str>) -> Value {
333 let mut entries: Vec<(String, Value)> = query.into_iter().collect();
334 entries.sort_by(|a, b| a.0.cmp(&b.0));
335 let mut sorted = Map::new();
336 for (key, value) in entries {
337 let set = parent.unwrap_or(&key).to_owned();
338 let value = match value {
339 Value::Object(map) => normalise(map, Some(&set)),
340 Value::String(text) if UNORDERED.contains(&set.as_str()) => {
341 let mut values: Vec<&str> = text.split(',').collect();
342 values.sort_unstable();
343 Value::String(values.join(","))
344 }
345 other => other,
346 };
347 sorted.insert(key, value);
348 }
349 Value::Object(sorted)
350}
351
352async fn entry_key(store: &Repository, key: &str, tags: &[String]) -> laravel::Result<String> {
355 let mut tags = tags.to_vec();
356 tags.sort();
357 tags.dedup();
358 let mut generations = Map::new();
359 for tag in tags {
360 let tag_key = format!("{PREFIX}tag:{tag}");
361 let mut generation: Option<String> = store.get(&tag_key).await?;
362 if generation.is_none() {
363 store
364 .add(&tag_key, laravel::str::random(16), GENERATION_TTL)
365 .await?;
366 generation = store.get(&tag_key).await?;
367 }
368 generations.insert(tag, Value::String(generation.unwrap_or_default()));
369 }
370 Ok(format!(
371 "{PREFIX}{:032x}",
372 xxhash_rust::xxh3::xxh3_128(format!("{key}\n{}", Value::Object(generations)).as_bytes())
373 ))
374}
375
376#[cfg(test)]
377mod tests {
378 use serde_json::json;
379
380 use super::{normalise, php_json};
381 use crate::query_string;
382
383 #[test]
384 fn keys_ignore_parameter_and_set_order() {
385 let a = normalise(
386 query_string::parse("include=b,a&sort=-x,y&fields[o]=q,p"),
387 None,
388 );
389 let b = normalise(
390 query_string::parse("fields[o]=p,q&sort=-x,y&include=a,b"),
391 None,
392 );
393 assert_eq!(a.to_string(), b.to_string());
394 let c = normalise(query_string::parse("sort=y,-x"), None);
396 assert_eq!(c, json!({ "sort": "y,-x" }));
397 }
398
399 #[test]
400 fn keys_hash_the_parts_as_php_encodes_them() {
401 let parts = json!({ "path": "/v1/x", "q": {}, "n": null, "u": "é\"", "a": [1] });
403 assert_eq!(
404 php_json(&parts),
405 r#"{"path":"\/v1\/x","q":[],"n":null,"u":"\u00e9\"","a":[1]}"#
406 );
407 }
408}