fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! HTTP caching, as the PHP package's `HttpCache` middleware does it: GET and HEAD responses carry
//! `Vary`, successful ones `Cache-Control` and a weak `ETag`, and an `If-None-Match` that matches
//! gets a `304 Not Modified` without a body. Every other response gets Symfony's default
//! `Cache-Control: no-cache, private`.

use laravel::axum::body::{Body, to_bytes};
use laravel::axum::http::{HeaderValue, Method, StatusCode, header};
use laravel::http::{Middleware, Next, Request, Response};

use crate::Config;

/// Route middleware that sets a route's `Cache-Control` for its successful GET responses, in
/// place of [`Config::cache_control`], as `cache-control:` route middleware does in PHP:
///
/// ```no_run
/// # use laravel::prelude::*;
/// # async fn index() -> &'static str { "[]" }
/// # fn routes(route: &mut laravel::routing::Router) {
/// route.get("/customers", index).middleware(fusion_stack::CacheControl::new("private, max-age=10"));
/// # }
/// ```
#[derive(Clone)]
pub struct CacheControl(String);

impl CacheControl {
    /// Directives as `Cache-Control` writes them, such as `public, max-age=60`.
    #[must_use]
    pub fn new(directives: &str) -> Self {
        Self(directives.to_owned())
    }
}

/// The route's own `Cache-Control`, carried on the response to the Fusion Stack middleware.
#[derive(Clone)]
struct RouteCacheControl(String);

impl Middleware for CacheControl {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let mut response = next.run(request).await.into_http();
        response
            .extensions_mut()
            .insert(RouteCacheControl(self.0.clone()));
        Ok(Response::from_http(response))
    }
}

/// Global middleware that gives every response without a `Cache-Control` Symfony's default.
pub(crate) struct DefaultCacheControl;

impl Middleware for DefaultCacheControl {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let mut response = next.run(request).await.into_http();
        let headers = response.headers_mut();
        if !headers.contains_key(header::CACHE_CONTROL) {
            let value = if headers.contains_key(header::LAST_MODIFIED)
                || headers.contains_key(header::EXPIRES)
            {
                "must-revalidate, private"
            } else {
                "no-cache, private"
            };
            headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(value));
        }
        Ok(Response::from_http(response))
    }
}

/// Writes `Cache-Control` as Symfony does: `private` added when neither `public`, `private` nor
/// `s-maxage` is set, and the directives sorted by name.
fn normalize(value: &str) -> String {
    let mut directives: Vec<(String, Option<String>)> = value
        .split(',')
        .map(str::trim)
        .filter(|directive| !directive.is_empty())
        .map(|directive| match directive.split_once('=') {
            Some((name, value)) => (
                name.trim().to_ascii_lowercase(),
                Some(value.trim().to_owned()),
            ),
            None => (directive.to_ascii_lowercase(), None),
        })
        .collect();
    if !directives
        .iter()
        .any(|(name, _)| matches!(name.as_str(), "public" | "private" | "s-maxage"))
    {
        directives.push(("private".to_owned(), None));
    }
    directives.sort_by(|a, b| a.0.cmp(&b.0));
    directives.dedup_by(|a, b| a.0 == b.0);
    directives
        .into_iter()
        .map(|(name, value)| value.map_or_else(|| name.clone(), |value| format!("{name}={value}")))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Whether an `If-None-Match` value matches an entity tag, comparing weakly.
fn matches(if_none_match: &str, etag: &str) -> bool {
    let opaque = |tag: &str| tag.trim().trim_start_matches("W/").to_owned();
    let etag = opaque(etag);
    if_none_match
        .split(',')
        .map(str::trim)
        .any(|tag| tag == "*" || opaque(tag) == etag)
}

/// The caching step: `variant` names the version and the changes newer than it, so each version
/// has its own `ETag`. Runs on the response the handler wrote, before the version changes
/// transform it, so a 304 skips them.
pub(crate) async fn apply(
    config: &Config,
    method: &Method,
    if_none_match: Option<&str>,
    variant: &str,
    response: Response,
) -> Response {
    if method != Method::GET && method != Method::HEAD {
        return response;
    }
    let mut http = response.into_http();

    // One header line: some proxies read only the first Vary line.
    let mut vary: Vec<String> = http
        .headers()
        .get_all(header::VARY)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .flat_map(|value| value.split(',').map(|name| name.trim().to_owned()))
        .filter(|name| !name.is_empty())
        .collect();
    for name in config.vary_headers() {
        if !vary.iter().any(|known| known.eq_ignore_ascii_case(&name)) {
            vary.push(name);
        }
    }
    if let Ok(value) = HeaderValue::try_from(vary.join(", ")) {
        http.headers_mut().insert(header::VARY, value);
    }

    if http.status() != StatusCode::OK {
        return Response::from_http(http);
    }

    let cache_control = http
        .extensions()
        .get::<RouteCacheControl>()
        .map(|route| route.0.clone())
        .or_else(|| config.http_cache.cache_control.clone())
        .filter(|value| !value.is_empty());
    if let Some(value) = cache_control
        && let Ok(value) = HeaderValue::try_from(normalize(&value))
    {
        http.headers_mut().insert(header::CACHE_CONTROL, value);
    }

    if !config.http_cache.etags {
        return Response::from_http(http);
    }

    if !http.headers().contains_key(header::ETAG) {
        // PHP hashes the body it sends, and a HEAD response has none.
        if method == Method::HEAD {
            return Response::from_http(http);
        }
        let (mut parts, body) = http.into_parts();
        let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default();
        if bytes.is_empty() {
            return Response::from_http(laravel::axum::http::Response::from_parts(
                parts,
                Body::empty(),
            ));
        }
        let mut input = format!("{variant}\n").into_bytes();
        input.extend_from_slice(&bytes);
        let hash = xxhash_rust::xxh3::xxh3_128(&input);
        if let Ok(value) = HeaderValue::try_from(format!("W/\"{hash:032x}\"")) {
            parts.headers.insert(header::ETAG, value);
        }
        http = laravel::axum::http::Response::from_parts(parts, Body::from(bytes));
    }

    let etag = http
        .headers()
        .get(header::ETAG)
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default();
    if !if_none_match.is_some_and(|value| matches(value, etag)) {
        return Response::from_http(http);
    }

    // A fresh response, so the transforms and other steps see no body to work on.
    let (mut parts, _) = http.into_parts();
    parts.status = StatusCode::NOT_MODIFIED;
    parts.headers.remove(header::CONTENT_TYPE);
    parts.headers.remove(header::CONTENT_LENGTH);
    Response::from_http(laravel::axum::http::Response::from_parts(
        parts,
        Body::empty(),
    ))
}

#[cfg(test)]
mod tests {
    use super::{matches, normalize};

    #[test]
    fn cache_control_is_written_as_symfony_writes_it() {
        assert_eq!(normalize("private, max-age=10"), "max-age=10, private");
        assert_eq!(normalize("private, no-cache"), "no-cache, private");
        assert_eq!(normalize("max-age=60"), "max-age=60, private");
        assert_eq!(normalize("public, max-age=60"), "max-age=60, public");
        assert_eq!(normalize("s-maxage=60"), "s-maxage=60");
    }

    #[test]
    fn if_none_match_compares_weakly() {
        assert!(matches("W/\"abc\"", "W/\"abc\""));
        assert!(matches("\"abc\"", "W/\"abc\""));
        assert!(matches("W/\"x\", W/\"abc\"", "W/\"abc\""));
        assert!(matches("*", "W/\"abc\""));
        assert!(!matches("W/\"abcd\"", "W/\"abc\""));
    }
}