fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! The response cache, as the PHP package's `ResponseCache` middleware and `#[CacheResponse]`
//! attribute do it: a route opts in, its successful GET responses are kept in a Laravel cache
//! store, and later requests are answered from the store with `X-Response-Cache: hit`. Entries
//! are tagged, and [`flush`] drops every entry with any of the tags it is given.
//!
//! The cached body is the latest version's, from before the version changes run, so every
//! version shares an entry. Entries are scoped to the API client (`guest` without one) unless the
//! route marks them [`CacheResponse::shared`].
//!
//! A user signed in through Laravel's own guards (the session guard, or a `RequestGuard` run by
//! `Authenticate::via`) rather than as an API client has no client to scope an entry to, and the
//! framework says only that someone is signed in, not who. Such a request skips the cache unless
//! the route's entries are shared: it is neither answered from the guest entry nor stored in it.

use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use laravel::axum::body::{Body, to_bytes};
use laravel::axum::http::{HeaderName, HeaderValue, Method, StatusCode, header};
use laravel::cache::Repository;
use laravel::http::{Middleware, Next, Request, Response};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use crate::{Context, query_string};

/// The header that says whether the store answered the request.
pub const HEADER: &str = "x-response-cache";

const PREFIX: &str = "fusion-stack:response-cache:";

/// Headers that belong to one delivery of the response.
const UNSTORED_HEADERS: [&str; 5] = [
    "date",
    "x-request-id",
    "cache-control",
    HEADER,
    "set-cookie",
];

/// Query parameters whose comma-separated values are sets, so order does not matter.
const UNORDERED: [&str; 2] = ["include", "fields"];

/// How long tag generations last; they are replaced, never expired, as PHP keeps them forever.
const GENERATION_TTL: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60);

/// Route middleware that caches a route's successful GET responses, as `#[CacheResponse]` does in
/// PHP. Tags may name route parameters, such as `orders:{order}`.
///
/// A hit answers without running the middleware listed after this one, and this one only knows
/// about a user that earlier middleware signed in. List `RequiresScope` and `Authenticate` before
/// it, or a hit skips them and a signed-in user's response is stored for guests.
///
/// ```no_run
/// # use laravel::prelude::*;
/// # async fn show() -> &'static str { "{}" }
/// # fn routes(route: &mut laravel::routing::Router) {
/// route
///     .get("/orders/{order}", show)
///     .middleware(fusion_stack::CacheResponse::new(60).tags(["orders:{order}", "customers"]));
/// # }
/// ```
#[derive(Clone)]
pub struct CacheResponse {
    ttl: u64,
    tags: Vec<String>,
    shared: bool,
}

impl CacheResponse {
    /// Caches responses for `ttl` seconds.
    #[must_use]
    pub const fn new(ttl: u64) -> Self {
        Self {
            ttl,
            tags: Vec::new(),
            shared: false,
        }
    }

    /// The tags whose [`flush`] drops these entries.
    #[must_use]
    pub fn tags<I: IntoIterator<Item = S>, S: Into<String>>(mut self, tags: I) -> Self {
        self.tags = tags.into_iter().map(Into::into).collect();
        self
    }

    /// Shares entries between every client, for responses that are the same for everyone.
    #[must_use]
    pub const fn shared(mut self) -> Self {
        self.shared = true;
        self
    }
}

#[derive(Serialize, Deserialize)]
struct Cached {
    status: u16,
    headers: Vec<(String, String)>,
    body: String,
}

impl Middleware for CacheResponse {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let context = request.extension::<Context>().cloned();
        let method = request.method().clone();
        let enabled = context
            .as_ref()
            .is_some_and(|context| context.state.config.response_cache.enabled);
        if !enabled || (method != Method::GET && method != Method::HEAD) {
            return Ok(next.run(request).await);
        }
        let Some(context) = context else {
            return Ok(next.run(request).await);
        };
        // Someone is signed in, but not as a client: their response must not go in the guest
        // entry, and there is nothing else to key it by.
        if !self.shared && context.client.is_none() && request.authenticated().await? {
            return Ok(next.run(request).await);
        }
        let store = store(context.state.config.response_cache.store.as_deref())?;

        let account = if self.shared {
            None
        } else {
            Some(
                context
                    .client
                    .as_ref()
                    .map_or_else(|| "guest".to_owned(), |client| client.id.clone()),
            )
        };
        let key = key(&request, account.as_deref());
        let tags: Vec<String> = self.tags.iter().map(|tag| tag_for(tag, &request)).collect();
        let entry = entry_key(&store, &key, &tags).await?;

        if let Some(cached) = store.get::<Cached>(&entry).await? {
            return Ok(rebuild(cached));
        }

        let response = next.run(request).await.into_http();
        // A HEAD response may have no body to keep; the next GET stores it.
        if response.status() != StatusCode::OK
            || method == Method::HEAD
            || response.headers().contains_key(header::SET_COOKIE)
        {
            return Ok(Response::from_http(response));
        }
        let (mut parts, body) = response.into_parts();
        let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
        let cached = Cached {
            status: 200,
            headers: parts
                .headers
                .iter()
                .filter(|(name, _)| !UNSTORED_HEADERS.contains(&name.as_str()))
                .filter_map(|(name, value)| {
                    Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
                })
                .collect(),
            body: STANDARD.encode(&bytes),
        };
        store
            .put(&entry, &cached, Duration::from_secs(self.ttl))
            .await?;
        parts.headers.insert(
            HeaderName::from_static(HEADER),
            HeaderValue::from_static("miss"),
        );
        Ok(Response::from_http(
            laravel::axum::http::Response::from_parts(parts, Body::from(bytes)),
        ))
    }
}

/// Drops every cached response stored with any of the tags, such as `orders` and `orders:5`
/// after order 5 changes. Uses the default cache store, as the PHP package's `response_cache.store`
/// does when it is null; [`flush_in`] names another.
///
/// # Errors
///
/// When the cache store can't be written.
pub async fn flush<I: IntoIterator<Item = S>, S: AsRef<str>>(tags: I) -> laravel::Result<()> {
    flush_in(None, tags).await
}

/// [`flush`] in the named cache store.
///
/// # Errors
///
/// When the store isn't defined or can't be written.
pub async fn flush_in<I: IntoIterator<Item = S>, S: AsRef<str>>(
    store_name: Option<&str>,
    tags: I,
) -> laravel::Result<()> {
    let store = store(store_name)?;
    for tag in tags {
        store
            .put(
                &format!("{PREFIX}tag:{}", tag.as_ref()),
                laravel::str::random(16),
                GENERATION_TTL,
            )
            .await?;
    }
    Ok(())
}

fn store(name: Option<&str>) -> laravel::Result<Repository> {
    match name {
        Some(name) => laravel::cache::store(name),
        None => laravel::cache::manager().default_store(),
    }
}

fn rebuild(cached: Cached) -> Response {
    let mut response = laravel::axum::http::Response::new(Body::from(
        STANDARD.decode(cached.body).unwrap_or_default(),
    ));
    *response.status_mut() = StatusCode::from_u16(cached.status).unwrap_or(StatusCode::OK);
    let headers = response.headers_mut();
    for (name, value) in cached.headers {
        if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) {
            headers.append(name, value);
        }
    }
    headers.insert(
        HeaderName::from_static(HEADER),
        HeaderValue::from_static("hit"),
    );
    Response::from_http(response)
}

/// Fills in a tag's route parameters, such as `{order}` in `orders:{order}`.
fn tag_for(tag: &str, request: &Request) -> String {
    let Some(route) = request.current_route() else {
        return tag.to_owned();
    };
    let mut tag = tag.to_owned();
    for (name, value) in route.params() {
        tag = tag.replace(&format!("{{{name}}}"), value);
    }
    tag
}

/// The request's response cache key and what it is made of, as the PHP package's `CacheKey`
/// makes them: the method (HEAD as GET), path, pinned version, client (`guest` without one) and
/// query, with `include` and `fields` values in any order. The key is the same in both packages.
///
/// A user signed in through Laravel's own guards without being an API client gets the `guest` key,
/// which the PHP package scopes to the user instead. Before caching anything that is not the same
/// for every caller under this key, check `request.authenticated()`, as [`CacheResponse`] does.
#[must_use]
pub fn cache_key(request: &Request) -> (String, Value) {
    let context = request.extension::<Context>();
    let version = context
        .and_then(|context| context.version.as_ref())
        .map(|(version, _)| version.to_string());
    let account = context
        .and_then(|context| context.client.as_ref())
        .map_or_else(|| "guest".to_owned(), |client| client.id.clone());
    let parts = parts(request, version.as_deref(), Some(&account));
    (key_of(&parts), parts)
}

fn parts(request: &Request, version: Option<&str>, account: Option<&str>) -> Value {
    json!({
        "method": "GET",
        "path": format!("/{}", request.path().trim_start_matches('/')),
        "version": version,
        "account": account,
        "query": normalise(query_string::parse(request.uri().query().unwrap_or_default()), None),
    })
}

fn key_of(parts: &Value) -> String {
    format!(
        "fusion-stack:{:032x}",
        xxhash_rust::xxh3::xxh3_128(php_json(parts).as_bytes())
    )
}

/// The request's key without the version, so every version shares the latest-version entry.
fn key(request: &Request, account: Option<&str>) -> String {
    key_of(&parts(request, None, account))
}

/// JSON as PHP's `json_encode` writes it by default: `/` and non-ASCII characters escaped, and
/// an empty object as `[]`.
fn php_json(value: &Value) -> String {
    match value {
        Value::String(text) => {
            let mut out = String::from("\"");
            for unit in text.encode_utf16() {
                match unit {
                    0x22 => out.push_str("\\\""),
                    0x5C => out.push_str("\\\\"),
                    0x2F => out.push_str("\\/"),
                    0x08 => out.push_str("\\b"),
                    0x0C => out.push_str("\\f"),
                    0x0A => out.push_str("\\n"),
                    0x0D => out.push_str("\\r"),
                    0x09 => out.push_str("\\t"),
                    0x20..=0x7E => out.push(char::from(u8::try_from(unit).unwrap_or(b'?'))),
                    _ => out.push_str(&format!("\\u{unit:04x}")),
                }
            }
            out.push('"');
            out
        }
        Value::Array(items) => format!(
            "[{}]",
            items.iter().map(php_json).collect::<Vec<_>>().join(",")
        ),
        Value::Object(map) if map.is_empty() => "[]".to_owned(),
        Value::Object(map) => format!(
            "{{{}}}",
            map.iter()
                .map(|(key, value)| format!(
                    "{}:{}",
                    php_json(&Value::String(key.clone())),
                    php_json(value)
                ))
                .collect::<Vec<_>>()
                .join(",")
        ),
        other => other.to_string(),
    }
}

fn normalise(query: Map<String, Value>, parent: Option<&str>) -> Value {
    let mut entries: Vec<(String, Value)> = query.into_iter().collect();
    entries.sort_by(|a, b| a.0.cmp(&b.0));
    let mut sorted = Map::new();
    for (key, value) in entries {
        let set = parent.unwrap_or(&key).to_owned();
        let value = match value {
            Value::Object(map) => normalise(map, Some(&set)),
            Value::String(text) if UNORDERED.contains(&set.as_str()) => {
                let mut values: Vec<&str> = text.split(',').collect();
                values.sort_unstable();
                Value::String(values.join(","))
            }
            other => other,
        };
        sorted.insert(key, value);
    }
    Value::Object(sorted)
}

/// The store key for an entry: the request's key with the current generation of each tag, so
/// flushing a tag (giving it a new generation) leaves its old entries unread until they expire.
async fn entry_key(store: &Repository, key: &str, tags: &[String]) -> laravel::Result<String> {
    let mut tags = tags.to_vec();
    tags.sort();
    tags.dedup();
    let mut generations = Map::new();
    for tag in tags {
        let tag_key = format!("{PREFIX}tag:{tag}");
        let mut generation: Option<String> = store.get(&tag_key).await?;
        if generation.is_none() {
            store
                .add(&tag_key, laravel::str::random(16), GENERATION_TTL)
                .await?;
            generation = store.get(&tag_key).await?;
        }
        generations.insert(tag, Value::String(generation.unwrap_or_default()));
    }
    Ok(format!(
        "{PREFIX}{:032x}",
        xxhash_rust::xxh3::xxh3_128(format!("{key}\n{}", Value::Object(generations)).as_bytes())
    ))
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::{normalise, php_json};
    use crate::query_string;

    #[test]
    fn keys_ignore_parameter_and_set_order() {
        let a = normalise(
            query_string::parse("include=b,a&sort=-x,y&fields[o]=q,p"),
            None,
        );
        let b = normalise(
            query_string::parse("fields[o]=p,q&sort=-x,y&include=a,b"),
            None,
        );
        assert_eq!(a.to_string(), b.to_string());
        // Sorts are ordered, so their order still matters.
        let c = normalise(query_string::parse("sort=y,-x"), None);
        assert_eq!(c, json!({ "sort": "y,-x" }));
    }

    #[test]
    fn keys_hash_the_parts_as_php_encodes_them() {
        // php -r 'echo json_encode(["path" => "/v1/x", "q" => [], "n" => null, "u" => "é\"", "a" => [1]]);'
        let parts = json!({ "path": "/v1/x", "q": {}, "n": null, "u": "é\"", "a": [1] });
        assert_eq!(
            php_json(&parts),
            r#"{"path":"\/v1\/x","q":[],"n":null,"u":"\u00e9\"","a":[1]}"#
        );
    }
}