capy-auth 0.7.2

Optional database-backed browser sessions and explicit authorization for Capy.
Documentation
use capy_core::{AppError, Result};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};

// Bounded fixed windows. No user identifiers are retained in plaintext.
#[derive(Clone, Default)]
pub(crate) struct Throttle(Arc<Mutex<HashMap<String, (Instant, u32)>>>);
impl Throttle {
    pub fn check(&self, key: String, limit: u32) -> Result<()> {
        let mut entries = self.0.lock().map_err(|_| AppError::TooManyRequests)?;
        let now = Instant::now();
        entries.retain(|_, (start, _)| now.duration_since(*start) < Duration::from_secs(60));
        if !entries.contains_key(&key) && entries.len() >= 10_000 {
            return Err(AppError::TooManyRequests);
        }
        let (_, count) = entries.entry(key).or_insert((now, 0));
        if *count >= limit {
            return Err(AppError::TooManyRequests);
        }
        *count += 1;
        Ok(())
    }
}