use capy_core::{AppError, AuthThrottleLimit, Result};
use std::{
collections::HashMap,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
#[derive(Clone, Default)]
pub(crate) struct Throttle(Arc<Mutex<HashMap<String, (Instant, u32)>>>);
impl Throttle {
pub fn check(&self, key: String, budget: &AuthThrottleLimit) -> Result<()> {
self.check_at(key, budget, Instant::now())
}
fn check_at(&self, key: String, budget: &AuthThrottleLimit, now: Instant) -> Result<()> {
let mut entries = self.0.lock().map_err(|_| AppError::TooManyRequests)?;
entries.retain(|_, (expires, _)| *expires > now);
if !entries.contains_key(&key) && entries.len() >= 10_000 {
return Err(AppError::TooManyRequests);
}
let (_, count) = entries
.entry(key)
.or_insert((now + Duration::from_secs(budget.window_seconds), 0));
if *count >= budget.limit {
return Err(AppError::TooManyRequests);
}
*count += 1;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn independent_windows_expire_at_their_exact_boundary_without_sleeping() {
let throttle = Throttle::default();
let short = AuthThrottleLimit {
limit: 1,
window_seconds: 2,
};
let long = AuthThrottleLimit {
limit: 1,
window_seconds: 10,
};
let now = Instant::now();
throttle.check_at("ip".into(), &short, now).unwrap();
throttle.check_at("account".into(), &long, now).unwrap();
assert!(throttle
.check_at("ip".into(), &short, now + Duration::from_secs(1))
.is_err());
throttle
.check_at("ip".into(), &short, now + Duration::from_secs(2))
.unwrap();
assert!(throttle
.check_at("account".into(), &long, now + Duration::from_secs(2))
.is_err());
throttle
.check_at("account".into(), &long, now + Duration::from_secs(10))
.unwrap();
}
#[test]
fn entry_capacity_fails_closed_but_existing_buckets_still_work() {
let throttle = Throttle::default();
let budget = AuthThrottleLimit {
limit: 2,
window_seconds: 60,
};
let now = Instant::now();
for i in 0..10_000 {
throttle.check_at(i.to_string(), &budget, now).unwrap();
}
assert!(throttle.check_at("overflow".into(), &budget, now).is_err());
throttle.check_at("0".into(), &budget, now).unwrap();
throttle
.check_at("overflow".into(), &budget, now + Duration::from_secs(60))
.unwrap();
}
}