use std::{fmt, sync::Arc, time::Instant};
use async_trait::async_trait;
use axum::http::{HeaderName, Request};
use sha2::{Digest, Sha256};
use crate::{
clock::{SharedClock, system_clock},
http::RequestContext,
observability::MetricRecorder,
};
use super::memory::RateLimitStore;
use super::{
memory::{MemoryRateLimitStore, TokenBucketRateLimiter},
model::{
MAX_RATE_LIMIT_HEADER_VALUE_BYTES, RateLimitConfig, RateLimitDecision, RateLimitError,
},
};
#[derive(Clone)]
#[non_exhaustive]
pub struct RateLimitRuntime {
config: RateLimitConfig,
store: Arc<dyn RateLimitStore>,
key_source: RateLimitKeySource,
clock: SharedClock,
metrics: Option<Arc<dyn MetricRecorder>>,
}
impl fmt::Debug for RateLimitRuntime {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RateLimitRuntime")
.field("config", &self.config)
.field("key_source", &self.key_source)
.finish_non_exhaustive()
}
}
impl RateLimitRuntime {
#[must_use]
pub fn new(
config: RateLimitConfig,
key_source: RateLimitKeySource,
store: Arc<dyn RateLimitStore>,
) -> Self {
Self {
config,
store,
key_source,
clock: system_clock(),
metrics: None,
}
}
#[must_use]
pub fn in_memory(config: RateLimitConfig, key_source: RateLimitKeySource) -> Self {
Self::new(
config,
key_source,
Arc::new(MemoryRateLimitStore::new(config)),
)
}
#[must_use]
pub fn from_limiter(
limiter: Arc<TokenBucketRateLimiter<String>>,
key_source: RateLimitKeySource,
) -> Self {
Self {
config: limiter.config(),
store: Arc::new(TokenBucketRateLimiterStore { limiter }),
key_source,
clock: system_clock(),
metrics: None,
}
}
#[must_use]
pub fn with_clock(mut self, clock: SharedClock) -> Self {
self.clock = clock;
self
}
#[must_use]
pub fn with_metrics(mut self, metrics: Option<Arc<dyn MetricRecorder>>) -> Self {
self.metrics = metrics;
self
}
#[must_use]
pub const fn config(&self) -> RateLimitConfig {
self.config
}
#[must_use]
pub fn store(&self) -> &Arc<dyn RateLimitStore> {
&self.store
}
#[must_use]
pub const fn key_source(&self) -> &RateLimitKeySource {
&self.key_source
}
#[must_use]
pub fn clock(&self) -> &SharedClock {
&self.clock
}
#[must_use]
pub fn metrics(&self) -> Option<&Arc<dyn MetricRecorder>> {
self.metrics.as_ref()
}
}
#[derive(Debug)]
struct TokenBucketRateLimiterStore {
limiter: Arc<TokenBucketRateLimiter<String>>,
}
#[async_trait]
impl RateLimitStore for TokenBucketRateLimiterStore {
async fn check(
&self,
key: String,
config: RateLimitConfig,
now: Instant,
) -> Result<RateLimitDecision, RateLimitError> {
self.limiter.check_at_with_config(key, config, now)
}
async fn prune_idle(&self, older_than: Instant) -> Result<usize, RateLimitError> {
self.limiter.prune_idle(older_than)
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RateLimitKeySource {
ClientIp,
PrincipalId,
RequestId,
Header(HeaderName),
Fixed(String),
}
impl fmt::Debug for RateLimitKeySource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ClientIp => formatter.write_str("ClientIp"),
Self::PrincipalId => formatter.write_str("PrincipalId"),
Self::RequestId => formatter.write_str("RequestId"),
Self::Header(name) => formatter.debug_tuple("Header").field(name).finish(),
Self::Fixed(_) => formatter.debug_tuple("Fixed").field(&"[REDACTED]").finish(),
}
}
}
impl RateLimitKeySource {
#[must_use]
pub fn key_for<B>(&self, request: &Request<B>) -> Option<String> {
match self {
Self::ClientIp => request
.extensions()
.get::<RequestContext>()
.and_then(RequestContext::client_ip)
.map(ToOwned::to_owned),
Self::PrincipalId => request
.extensions()
.get::<RequestContext>()
.and_then(RequestContext::principal)
.map(|principal| principal.id().to_owned()),
Self::RequestId => request
.extensions()
.get::<RequestContext>()
.map(|context| context.request_id().to_string()),
Self::Header(name) => request
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
.filter(|value| value.len() <= MAX_RATE_LIMIT_HEADER_VALUE_BYTES)
.map(|value| hash_header_rate_limit_key(name, value)),
Self::Fixed(value) => Some(value.clone()),
}
}
}
fn hash_header_rate_limit_key(name: &HeaderName, value: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(b"footing-rate-limit-header-v1\0");
hash_rate_limit_part(&mut hasher, name.as_str().as_bytes());
hash_rate_limit_part(&mut hasher, value.as_bytes());
format!("header:{}", to_lower_hex(&hasher.finalize()))
}
fn hash_rate_limit_part(hasher: &mut Sha256, value: &[u8]) {
hasher.update(u64::try_from(value.len()).unwrap_or(u64::MAX).to_be_bytes());
hasher.update(value);
}
fn to_lower_hex(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut output = String::with_capacity(bytes.len() * 2);
for byte in bytes {
output.push(char::from(HEX[usize::from(byte >> 4)]));
output.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
output
}