cloudiful-rate-limiter 0.1.0

Reusable async resource throttling with local and Valkey-backed backends.
Documentation
//! Async resource throttling by explicit key.
//!
//! This crate decides whether a keyed access is allowed now and how long the
//! caller must wait otherwise. It does not schedule jobs, retry requests, or
//! infer business scopes.

mod error;
mod local;
mod policy;
#[cfg(feature = "valkey")]
mod valkey;
#[cfg(feature = "valkey")]
mod valkey_scripts;

#[cfg(feature = "valkey")]
pub use error::ValkeyError;
pub use error::{InvalidPolicyError, InvalidPolicyKind, RateLimitError, RateLimitErrorKind};
pub use local::LocalRateLimiter;
pub use policy::RateLimitPolicy;
#[cfg(feature = "valkey")]
pub use valkey::ValkeyRateLimiter;

use async_trait::async_trait;
use std::time::Duration;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcquireResult {
    pub key: String,
    pub waited: Duration,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TryAcquireResult {
    Acquired,
    Limited { wait_duration: Duration },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeekResult {
    pub allowed: bool,
    pub wait_duration: Duration,
}

#[async_trait]
pub trait RateLimiter: Send + Sync {
    async fn acquire(&self, key: &str) -> Result<AcquireResult, RateLimitError>;
    async fn try_acquire(&self, key: &str) -> Result<TryAcquireResult, RateLimitError>;
    async fn peek(&self, key: &str) -> Result<PeekResult, RateLimitError>;
}