use std::time::Duration;
use laravel::axum::http::{HeaderName, HeaderValue};
use laravel::cache::Repository;
use laravel::http::Response;
use sha2::{Digest, Sha256};
use crate::auth::ApiClient;
use crate::errors::{ApiError, ApiErrorCode};
use crate::{Config, time};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tier {
pub limit: Option<u64>,
pub per_seconds: u64,
}
impl Tier {
#[must_use]
pub const fn new(limit: u64, per_seconds: u64) -> Self {
Self {
limit: Some(limit),
per_seconds,
}
}
#[must_use]
pub const fn unlimited() -> Self {
Self {
limit: None,
per_seconds: 60,
}
}
}
pub(crate) struct Counted {
key: String,
limit: u64,
}
fn tier<'a>(config: &'a Config, client: Option<&ApiClient>) -> Option<&'a Tier> {
let tiers = &config.rate_limit.tiers;
let named = match client {
None => Some("guest"),
Some(client) => client.rate_limit_tier.as_deref(),
};
named
.and_then(|name| tiers.iter().find(|(known, _)| known == name))
.or_else(|| tiers.iter().find(|(known, _)| known == "default"))
.map(|(_, tier)| tier)
}
pub(crate) async fn hit(
config: &Config,
client: Option<&ApiClient>,
ip: &str,
) -> Result<Option<Counted>, Box<ApiError>> {
if !config.rate_limit.enabled {
return Ok(None);
}
let Some(&Tier {
limit: Some(limit),
per_seconds,
}) = tier(config, client)
else {
return Ok(None);
};
let Ok(store) = laravel::cache::manager().default_store() else {
return Ok(None);
};
let who = client.map_or_else(
|| format!("ip:{ip}"),
|client| format!("client:{}", client.id),
);
let key = format!(
"fusion-stack:rate-limit:{}",
Sha256::digest(who.as_bytes())
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>()
);
if too_many_attempts(&store, &key, limit).await {
let retry_after = available_in(&store, &key).await.max(1);
let mut error = ApiError::new(
ApiErrorCode::RateLimited,
format!(
"This client is limited to {limit} requests per {per_seconds} seconds. Retry in {retry_after} seconds."
),
)
.meta("limit", limit)
.meta("retry_after", retry_after);
for (name, value) in headers(limit, 0, retry_after) {
error = error.header(name, value);
}
return Err(Box::new(
error.header("Retry-After", retry_after.to_string()),
));
}
let decay = Duration::from_secs(per_seconds);
let _ = store
.add(&timer(&key), time::now() + to_i64(per_seconds), decay)
.await;
let added = store.add(&key, 0_i64, decay).await.unwrap_or(false);
let hits = store.increment(&key, 1).await.ok().flatten();
if !added && hits == Some(1) {
let _ = store.put(&key, 1_i64, decay).await;
}
Ok(Some(Counted { key, limit }))
}
pub(crate) async fn add_headers(counted: Option<Counted>, response: Response) -> Response {
let Some(Counted { key, limit }) = counted else {
return response;
};
let Ok(store) = laravel::cache::manager().default_store() else {
return response;
};
let attempts = attempts(&store, &key).await;
let reset = available_in(&store, &key).await;
let mut http = response.into_http();
for (name, value) in headers(limit, limit.saturating_sub(attempts), reset) {
if let Ok(value) = HeaderValue::try_from(value) {
http.headers_mut()
.append(HeaderName::from_static(name), value);
}
}
Response::from_http(http)
}
fn headers(limit: u64, remaining: u64, reset: u64) -> [(&'static str, String); 3] {
[
("ratelimit-limit", limit.to_string()),
("ratelimit-remaining", remaining.to_string()),
("ratelimit-reset", reset.to_string()),
]
}
fn timer(key: &str) -> String {
format!("{key}:timer")
}
fn to_i64(value: u64) -> i64 {
i64::try_from(value).unwrap_or(i64::MAX)
}
async fn attempts(store: &Repository, key: &str) -> u64 {
store
.get::<i64>(key)
.await
.ok()
.flatten()
.and_then(|attempts| u64::try_from(attempts).ok())
.unwrap_or(0)
}
async fn too_many_attempts(store: &Repository, key: &str, limit: u64) -> bool {
if attempts(store, key).await < limit {
return false;
}
if store.has(&timer(key)).await.unwrap_or(false) {
return true;
}
let _ = store.forget(key).await;
false
}
async fn available_in(store: &Repository, key: &str) -> u64 {
let ends = store.get::<i64>(&timer(key)).await.ok().flatten();
ends.map_or(0, |ends| u64::try_from(ends - time::now()).unwrap_or(0))
}
#[cfg(test)]
mod tests {
use super::{Tier, tier};
use crate::Config;
use crate::auth::ApiClient;
#[test]
fn unknown_tiers_fall_back_to_default() {
let config = Config::new().rate_limit_tier("sandbox", Tier::new(3, 60));
let limit = |client: Option<&ApiClient>| tier(&config, client).and_then(|tier| tier.limit);
assert_eq!(limit(None), Some(60));
assert_eq!(limit(Some(&ApiClient::new("a"))), Some(300));
let sandbox = ApiClient::new("b").rate_limit_tier(Some("sandbox"));
assert_eq!(limit(Some(&sandbox)), Some(3));
let typo = ApiClient::new("c").rate_limit_tier(Some("sandbx"));
assert_eq!(limit(Some(&typo)), Some(300));
}
#[test]
fn guests_fall_back_to_default_without_a_guest_tier() {
let config = Config::new().rate_limit_tier("guest", None);
assert_eq!(tier(&config, None).and_then(|tier| tier.limit), Some(300));
}
}