glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! A rate limiter shared by every process that shares the cache, as
//! Laravel's `RateLimiter`: `limit` attempts per `period` for each key,
//! counted in fixed windows in the cache (`cache::increment`).
//!
//! ```ignore
//! if !RateLimit::attempt(&format!("login:{email}"), 5, 1.minutes()).await? {
//!     let wait = RateLimit::available_in(&format!("login:{email}"), 1.minutes());
//!     return Err(Error::too_many_requests(wait));
//! }
//! ```
//!
//! With `[cache] store = "database"` the counts are shared across servers;
//! with the default memory store they're per process. `Throttle` counts
//! with it.

use chrono::TimeDelta;

use crate::error::Result;
use crate::jobs::Delay;

/// See the [module docs](self).
pub struct RateLimit;

/// The cache key of `key`'s current window, and when that window ends.
fn window(key: &str, period: TimeDelta) -> (String, TimeDelta) {
    let seconds = period.num_seconds().max(1);
    let now = crate::time::now().timestamp();
    let window = now.div_euclid(seconds);
    let ends_in = TimeDelta::seconds((window + 1) * seconds - now);
    (format!("glacier:rate:{key}:{seconds}:{window}"), ends_in)
}

impl RateLimit {
    /// Counts an attempt for `key`; whether it's within `limit` per
    /// `period`. Attempts over the limit are counted too.
    ///
    /// # Errors
    ///
    /// When the cache can't be written.
    pub async fn attempt(key: &str, limit: u32, period: impl Delay) -> Result<bool> {
        let (cache_key, ends_in) = window(key, period.delay());
        let count = crate::cache::increment(&cache_key, 1, ends_in).await?;
        Ok(count <= i64::from(limit))
    }

    /// Whether `key` has used up its `limit` for this `period`, without
    /// counting an attempt.
    ///
    /// # Errors
    ///
    /// When the cache can't be read.
    pub async fn too_many(key: &str, limit: u32, period: impl Delay) -> Result<bool> {
        Ok(Self::remaining(key, limit, period).await? == 0)
    }

    /// How many attempts `key` has left in this window.
    ///
    /// # Errors
    ///
    /// When the cache can't be read.
    pub async fn remaining(key: &str, limit: u32, period: impl Delay) -> Result<u32> {
        let (cache_key, _) = window(key, period.delay());
        let used: i64 = crate::cache::read(&cache_key).await?.unwrap_or(0);
        Ok(u32::try_from((i64::from(limit) - used).max(0)).unwrap_or(0))
    }

    /// Forgets `key`'s attempts in this window: after a successful sign-in,
    /// say.
    ///
    /// # Errors
    ///
    /// When the cache can't be written.
    pub async fn clear(key: &str, period: impl Delay) -> Result<()> {
        let (cache_key, _) = window(key, period.delay());
        crate::cache::delete(&cache_key).await
    }

    /// How long until `key`'s window ends and its count starts again, for
    /// a `Retry-After` header.
    pub fn available_in(key: &str, period: impl Delay) -> TimeDelta {
        window(key, period.delay()).1
    }
}

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

    #[tokio::test]
    async fn counts_attempts_in_fixed_windows() {
        crate::cache::with_test_store(async {
            let minute = TimeDelta::minutes(1);
            assert!(RateLimit::attempt("login:ada", 2, minute).await.unwrap());
            assert_eq!(
                RateLimit::remaining("login:ada", 2, minute).await.unwrap(),
                1
            );
            assert!(RateLimit::attempt("login:ada", 2, minute).await.unwrap());
            assert!(!RateLimit::attempt("login:ada", 2, minute).await.unwrap());
            assert!(RateLimit::too_many("login:ada", 2, minute).await.unwrap());
            // Another key has its own count.
            assert!(RateLimit::attempt("login:bo", 2, minute).await.unwrap());
            RateLimit::clear("login:ada", minute).await.unwrap();
            assert_eq!(
                RateLimit::remaining("login:ada", 2, minute).await.unwrap(),
                2
            );
            let wait = RateLimit::available_in("login:ada", minute);
            assert!(wait > TimeDelta::zero() && wait <= minute);
        })
        .await;
    }
}