footing 0.1.5

Feature-gated foundations for Rust backend services
Documentation
//! Rate-limit policy, decisions, and errors.

use std::time::Duration;

use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};

/// Default maximum rate limit buckets.
pub const DEFAULT_MAX_RATE_LIMIT_BUCKETS: usize = 10_000;
/// Maximum header bytes accepted as a rate-limit key source.
pub const MAX_RATE_LIMIT_HEADER_VALUE_BYTES: usize = 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling rate limit request.
pub enum RateLimitRequestPolicy {
    /// The capability is enabled.
    Enabled,
    /// The capability is disabled.
    Disabled,
}

impl RateLimitRequestPolicy {
    #[must_use]
    /// Returns the enabled.
    pub const fn enabled(self) -> bool {
        matches!(self, Self::Enabled)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Validated token-bucket rate-limit configuration.
pub struct RateLimitConfig {
    capacity: u32,
    refill_tokens: u32,
    refill_interval: Duration,
}

impl RateLimitConfig {
    /// Creates validated rate-limit configuration.
    pub fn new(
        capacity: u32,
        refill_tokens: u32,
        refill_interval: Duration,
    ) -> Result<Self, RateLimitError> {
        if capacity == 0 {
            return Err(RateLimitError::InvalidCapacity);
        }
        if refill_tokens == 0 {
            return Err(RateLimitError::InvalidRefillTokens);
        }
        if refill_interval.is_zero() {
            return Err(RateLimitError::InvalidRefillInterval);
        }
        Ok(Self {
            capacity,
            refill_tokens,
            refill_interval,
        })
    }

    #[must_use]
    /// Returns the capacity.
    pub const fn capacity(&self) -> u32 {
        self.capacity
    }

    #[must_use]
    /// Returns the refill tokens.
    pub const fn refill_tokens(&self) -> u32 {
        self.refill_tokens
    }

    #[must_use]
    /// Returns the refill interval.
    pub const fn refill_interval(&self) -> Duration {
        self.refill_interval
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Decision produced by rate limit.
pub struct RateLimitDecision {
    pub(super) kind: RateLimitDecisionKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RateLimitDecisionKind {
    Allowed { remaining: u32 },
    Denied { retry_after: Duration },
}

impl RateLimitDecision {
    #[must_use]
    /// Creates allowed.
    pub const fn allowed(remaining: u32) -> Self {
        Self {
            kind: RateLimitDecisionKind::Allowed { remaining },
        }
    }

    #[must_use]
    /// Creates denied.
    pub const fn denied(retry_after: Duration) -> Self {
        Self {
            kind: RateLimitDecisionKind::Denied { retry_after },
        }
    }

    #[must_use]
    /// Returns whether this value is allowed.
    pub const fn is_allowed(&self) -> bool {
        matches!(self.kind, RateLimitDecisionKind::Allowed { .. })
    }

    #[must_use]
    /// Returns the remaining.
    pub const fn remaining(&self) -> u32 {
        match self.kind {
            RateLimitDecisionKind::Allowed { remaining } => remaining,
            RateLimitDecisionKind::Denied { .. } => 0,
        }
    }

    #[must_use]
    /// Returns the retry after.
    pub const fn retry_after(&self) -> Option<Duration> {
        match self.kind {
            RateLimitDecisionKind::Allowed { .. } => None,
            RateLimitDecisionKind::Denied { retry_after } => Some(retry_after),
        }
    }
}

#[derive(Debug, Error)]
#[non_exhaustive]
/// Errors that can occur while handling rate limit.
pub enum RateLimitError {
    #[error("rate limit capacity must be greater than zero")]
    /// The capacity is invalid.
    InvalidCapacity,
    #[error("rate limit refill_tokens must be greater than zero")]
    /// The refill tokens is invalid.
    InvalidRefillTokens,
    #[error("rate limit refill_interval must be greater than zero")]
    /// The refill interval is invalid.
    InvalidRefillInterval,
    #[error("rate limit max buckets must be greater than zero")]
    /// The maximum buckets is invalid.
    InvalidMaxBuckets,
    #[error("rate limiter bucket capacity is exhausted")]
    /// Indicates capacity exceeded.
    CapacityExceeded,
    #[error("rate limiter state lock is poisoned")]
    /// Indicates lock poisoned.
    LockPoisoned,
    #[error("rate limit store is unavailable")]
    /// Indicates store unavailable.
    StoreUnavailable,
}

impl ClassifyError for RateLimitError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidCapacity
            | Self::InvalidRefillTokens
            | Self::InvalidRefillInterval
            | Self::InvalidMaxBuckets => ErrorKind::Validation,
            Self::CapacityExceeded | Self::LockPoisoned | Self::StoreUnavailable => {
                ErrorKind::Unavailable
            }
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidCapacity => "rate_limit_invalid_capacity",
            Self::InvalidRefillTokens => "rate_limit_invalid_refill_tokens",
            Self::InvalidRefillInterval => "rate_limit_invalid_refill_interval",
            Self::InvalidMaxBuckets => "rate_limit_invalid_max_buckets",
            Self::CapacityExceeded => "rate_limit_capacity_exceeded",
            Self::LockPoisoned => "rate_limit_lock_poisoned",
            Self::StoreUnavailable => "rate_limit_store_unavailable",
        })
    }
}