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