footing 0.4.4

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

use std::{fmt, time::Duration};

use serde::{Deserialize, Serialize};
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;

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Policy controlling rate limit request.
pub enum RateLimitRequestPolicy {
    /// The capability is enabled.
    Enabled,
    #[default]
    /// The capability is disabled.
    Disabled,
}

impl RateLimitRequestPolicy {
    /// Returns the policy name used in settings and endpoint contracts.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Enabled => "enabled",
            Self::Disabled => "disabled",
        }
    }

    #[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]
/// The outcome of consuming a rate-limit token.
pub enum RateLimitDecision {
    /// The request may proceed.
    Allowed {
        /// Tokens remaining after this request.
        remaining: u32,
    },
    /// The request must wait for more tokens.
    Denied {
        /// The delay before retrying.
        retry_after: Duration,
    },
}

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

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

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

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

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

#[derive(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 limit configuration differs from the store policy")]
    /// The requested policy differs from the store's immutable configuration.
    ConfigMismatch,
    #[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")]
    /// An external backend failed; its source is retained but not formatted.
    Store(#[source] crate::result::BoxError),
}

impl fmt::Debug for RateLimitError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RateLimitError")
            .field("code", &self.error_code())
            .finish_non_exhaustive()
    }
}

impl ClassifyError for RateLimitError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidCapacity
            | Self::InvalidRefillTokens
            | Self::InvalidRefillInterval
            | Self::InvalidMaxBuckets
            | Self::ConfigMismatch => ErrorKind::Validation,
            Self::CapacityExceeded | Self::LockPoisoned | Self::Store(_) => 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::ConfigMismatch => "rate_limit_config_mismatch",
            Self::CapacityExceeded => "rate_limit_capacity_exceeded",
            Self::LockPoisoned => "rate_limit_lock_poisoned",
            Self::Store(_) => "rate_limit_store_unavailable",
        })
    }
}