oluso 0.2.0

AI-powered error monitoring for Rust applications: automatic panic reporting, breadcrumb tracking, and intelligent error grouping.
Documentation
use std::sync::Mutex;
use std::time::{Duration, Instant};

/// Sliding-window limiter over the last 60 seconds, used to stop a crash
/// loop from flooding the ingestion API. `Client` is shared across threads
/// (`Arc<Client>`), so this needs interior mutability that's actually
/// thread-safe, not just `Cell`/`RefCell`.
pub struct RateLimiter {
    max_per_minute: u32,
    timestamps: Mutex<Vec<Instant>>,
}

impl RateLimiter {
    pub fn new(max_per_minute: u32) -> Self {
        Self {
            max_per_minute,
            timestamps: Mutex::new(Vec::new()),
        }
    }

    /// Returns true and records the attempt if under the limit; returns
    /// false (recording nothing) once the limit's been hit for this window.
    pub fn can_send(&self) -> bool {
        let now = Instant::now();
        let one_minute_ago = now - Duration::from_secs(60);

        let mut timestamps = self.timestamps.lock().unwrap_or_else(|e| e.into_inner());
        timestamps.retain(|&ts| ts > one_minute_ago);

        if (timestamps.len() as u32) < self.max_per_minute {
            timestamps.push(now);
            true
        } else {
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn allows_up_to_the_configured_limit() {
        let limiter = RateLimiter::new(3);
        assert!(limiter.can_send());
        assert!(limiter.can_send());
        assert!(limiter.can_send());
        assert!(!limiter.can_send());
    }

    #[test]
    fn zero_limit_never_allows_sending() {
        let limiter = RateLimiter::new(0);
        assert!(!limiter.can_send());
    }
}