fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! 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`].

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}`.
///
/// ```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);
        };
        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.
#[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]}"#
        );
    }
}