Skip to main content

fusion_stack/
response_cache.rs

1//! The response cache, as the PHP package's `ResponseCache` middleware and `#[CacheResponse]`
2//! attribute do it: a route opts in, its successful GET responses are kept in a Laravel cache
3//! store, and later requests are answered from the store with `X-Response-Cache: hit`. Entries
4//! are tagged, and [`flush`] drops every entry with any of the tags it is given.
5//!
6//! The cached body is the latest version's, from before the version changes run, so every
7//! version shares an entry. Entries are scoped to the API client (`guest` without one) unless the
8//! route marks them [`CacheResponse::shared`].
9
10use 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
23/// The header that says whether the store answered the request.
24pub const HEADER: &str = "x-response-cache";
25
26const PREFIX: &str = "fusion-stack:response-cache:";
27
28/// Headers that belong to one delivery of the response.
29const UNSTORED_HEADERS: [&str; 5] = [
30    "date",
31    "x-request-id",
32    "cache-control",
33    HEADER,
34    "set-cookie",
35];
36
37/// Query parameters whose comma-separated values are sets, so order does not matter.
38const UNORDERED: [&str; 2] = ["include", "fields"];
39
40/// How long tag generations last; they are replaced, never expired, as PHP keeps them forever.
41const GENERATION_TTL: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60);
42
43/// Route middleware that caches a route's successful GET responses, as `#[CacheResponse]` does in
44/// PHP. Tags may name route parameters, such as `orders:{order}`.
45///
46/// ```no_run
47/// # use laravel::prelude::*;
48/// # async fn show() -> &'static str { "{}" }
49/// # fn routes(route: &mut laravel::routing::Router) {
50/// route
51///     .get("/orders/{order}", show)
52///     .middleware(fusion_stack::CacheResponse::new(60).tags(["orders:{order}", "customers"]));
53/// # }
54/// ```
55#[derive(Clone)]
56pub struct CacheResponse {
57    ttl: u64,
58    tags: Vec<String>,
59    shared: bool,
60}
61
62impl CacheResponse {
63    /// Caches responses for `ttl` seconds.
64    #[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    /// The tags whose [`flush`] drops these entries.
74    #[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    /// Shares entries between every client, for responses that are the same for everyone.
81    #[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        // A HEAD response may have no body to keep; the next GET stores it.
130        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
163/// Drops every cached response stored with any of the tags, such as `orders` and `orders:5`
164/// after order 5 changes. Uses the default cache store, as the PHP package's `response_cache.store`
165/// does when it is null; [`flush_in`] names another.
166///
167/// # Errors
168///
169/// When the cache store can't be written.
170pub async fn flush<I: IntoIterator<Item = S>, S: AsRef<str>>(tags: I) -> laravel::Result<()> {
171    flush_in(None, tags).await
172}
173
174/// [`flush`] in the named cache store.
175///
176/// # Errors
177///
178/// When the store isn't defined or can't be written.
179pub 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
221/// Fills in a tag's route parameters, such as `{order}` in `orders:{order}`.
222fn 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/// The request's response cache key and what it is made of, as the PHP package's `CacheKey`
234/// makes them: the method (HEAD as GET), path, pinned version, client (`guest` without one) and
235/// query, with `include` and `fields` values in any order. The key is the same in both packages.
236#[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
266/// The request's key without the version, so every version shares the latest-version entry.
267fn key(request: &Request, account: Option<&str>) -> String {
268    key_of(&parts(request, None, account))
269}
270
271/// JSON as PHP's `json_encode` writes it by default: `/` and non-ASCII characters escaped, and
272/// an empty object as `[]`.
273fn 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
334/// The store key for an entry: the request's key with the current generation of each tag, so
335/// flushing a tag (giving it a new generation) leaves its old entries unread until they expire.
336async 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        // Sorts are ordered, so their order still matters.
377        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        // php -r 'echo json_encode(["path" => "/v1/x", "q" => [], "n" => null, "u" => "é\"", "a" => [1]]);'
384        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}