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};
pub const HEADER: &str = "x-response-cache";
const PREFIX: &str = "fusion-stack:response-cache:";
const UNSTORED_HEADERS: [&str; 5] = [
"date",
"x-request-id",
"cache-control",
HEADER,
"set-cookie",
];
const UNORDERED: [&str; 2] = ["include", "fields"];
const GENERATION_TTL: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60);
#[derive(Clone)]
pub struct CacheResponse {
ttl: u64,
tags: Vec<String>,
shared: bool,
}
impl CacheResponse {
#[must_use]
pub const fn new(ttl: u64) -> Self {
Self {
ttl,
tags: Vec::new(),
shared: false,
}
}
#[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
}
#[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);
};
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();
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)),
))
}
}
pub async fn flush<I: IntoIterator<Item = S>, S: AsRef<str>>(tags: I) -> laravel::Result<()> {
flush_in(None, tags).await
}
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)
}
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
}
#[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())
)
}
fn key(request: &Request, account: Option<&str>) -> String {
key_of(&parts(request, None, account))
}
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)
}
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());
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() {
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]}"#
);
}
}