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//!
10//! A user signed in through Laravel's own guards (the session guard, or a `RequestGuard` run by
11//! `Authenticate::via`) rather than as an API client has no client to scope an entry to, and the
12//! framework says only that someone is signed in, not who. Such a request skips the cache unless
13//! the route's entries are shared: it is neither answered from the guest entry nor stored in it.
14
15use 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
28/// The header that says whether the store answered the request.
29pub const HEADER: &str = "x-response-cache";
30
31const PREFIX: &str = "fusion-stack:response-cache:";
32
33/// Headers that belong to one delivery of the response.
34const UNSTORED_HEADERS: [&str; 5] = [
35    "date",
36    "x-request-id",
37    "cache-control",
38    HEADER,
39    "set-cookie",
40];
41
42/// Query parameters whose comma-separated values are sets, so order does not matter.
43const UNORDERED: [&str; 2] = ["include", "fields"];
44
45/// How long tag generations last; they are replaced, never expired, as PHP keeps them forever.
46const GENERATION_TTL: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60);
47
48/// Route middleware that caches a route's successful GET responses, as `#[CacheResponse]` does in
49/// PHP. Tags may name route parameters, such as `orders:{order}`.
50///
51/// A hit answers without running the middleware listed after this one, and this one only knows
52/// about a user that earlier middleware signed in. List `RequiresScope` and `Authenticate` before
53/// it, or a hit skips them and a signed-in user's response is stored for guests.
54///
55/// ```no_run
56/// # use laravel::prelude::*;
57/// # async fn show() -> &'static str { "{}" }
58/// # fn routes(route: &mut laravel::routing::Router) {
59/// route
60///     .get("/orders/{order}", show)
61///     .middleware(fusion_stack::CacheResponse::new(60).tags(["orders:{order}", "customers"]));
62/// # }
63/// ```
64#[derive(Clone)]
65pub struct CacheResponse {
66    ttl: u64,
67    tags: Vec<String>,
68    shared: bool,
69}
70
71impl CacheResponse {
72    /// Caches responses for `ttl` seconds.
73    #[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    /// The tags whose [`flush`] drops these entries.
83    #[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    /// Shares entries between every client, for responses that are the same for everyone.
90    #[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        // Someone is signed in, but not as a client: their response must not go in the guest
118        // entry, and there is nothing else to key it by.
119        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        // A HEAD response may have no body to keep; the next GET stores it.
144        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
177/// Drops every cached response stored with any of the tags, such as `orders` and `orders:5`
178/// after order 5 changes. Uses the default cache store, as the PHP package's `response_cache.store`
179/// does when it is null; [`flush_in`] names another.
180///
181/// # Errors
182///
183/// When the cache store can't be written.
184pub async fn flush<I: IntoIterator<Item = S>, S: AsRef<str>>(tags: I) -> laravel::Result<()> {
185    flush_in(None, tags).await
186}
187
188/// [`flush`] in the named cache store.
189///
190/// # Errors
191///
192/// When the store isn't defined or can't be written.
193pub 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
235/// Fills in a tag's route parameters, such as `{order}` in `orders:{order}`.
236fn 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/// The request's response cache key and what it is made of, as the PHP package's `CacheKey`
248/// makes them: the method (HEAD as GET), path, pinned version, client (`guest` without one) and
249/// query, with `include` and `fields` values in any order. The key is the same in both packages.
250///
251/// A user signed in through Laravel's own guards without being an API client gets the `guest` key,
252/// which the PHP package scopes to the user instead. Before caching anything that is not the same
253/// for every caller under this key, check `request.authenticated()`, as [`CacheResponse`] does.
254#[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
284/// The request's key without the version, so every version shares the latest-version entry.
285fn key(request: &Request, account: Option<&str>) -> String {
286    key_of(&parts(request, None, account))
287}
288
289/// JSON as PHP's `json_encode` writes it by default: `/` and non-ASCII characters escaped, and
290/// an empty object as `[]`.
291fn 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
352/// The store key for an entry: the request's key with the current generation of each tag, so
353/// flushing a tag (giving it a new generation) leaves its old entries unread until they expire.
354async 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        // Sorts are ordered, so their order still matters.
395        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        // php -r 'echo json_encode(["path" => "/v1/x", "q" => [], "n" => null, "u" => "é\"", "a" => [1]]);'
402        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}