footing 0.5.4

Feature-gated foundations for Rust backend services
Documentation
//! Backend-independent rate-limit storage contract.

use std::time::Duration;

use async_trait::async_trait;

use super::{RateLimitConfig, RateLimitDecision, RateLimitError};

/// Atomic token-bucket decisions using a clock owned by the store.
///
/// Local stores use a monotonic clock. Shared stores must use one authoritative
/// backend clock for checks and cleanup, never persist a process-local
/// `std::time::Instant` or translate it into a wall-clock timestamp. For a
/// PostgreSQL adapter, sample `clock_timestamp()` after locking the relevant
/// row; `CURRENT_TIMESTAMP` is the transaction start time and can be stale after
/// waiting for a lock. Clamp a backwards clock to the bucket's last observed
/// time so that a later recovery cannot refill the same interval twice.
///
/// A shared backend needs a stable namespace and atomic per-key serialization
/// across all instances. Persist its policy or policy fingerprint and reject
/// incompatible configurations without changing balances. Refilling, consuming
/// a token, and recording activity form one atomic operation; return success
/// only after it commits. Unknown commit outcomes must fail closed rather than
/// silently fall back to a fresh local bucket. Retained balances survive client
/// restarts. Pool size, query deadlines and storage quotas belong to the backend.
#[async_trait]
pub trait RateLimitStore: Send + Sync {
    /// Consumes one token for `key`, or reports when a token will be available.
    ///
    /// `config` must match the policy associated with this store or namespace;
    /// reject mismatches with [`RateLimitError::ConfigMismatch`]. Sample time at
    /// the atomic decision point, after any lock wait. One full refill interval
    /// adds `refill_tokens`, capped at `capacity`; preserve partial intervals.
    async fn check(
        &self,
        key: String,
        config: RateLimitConfig,
    ) -> Result<RateLimitDecision, RateLimitError>;

    /// Removes buckets idle for at least `max_idle` **and** fully replenished
    /// according to the store's clock, returning the number of tracked keys removed.
    ///
    /// Activity includes denied checks. A zero duration permits immediate cleanup
    /// of full buckets. Deleting a bucket must never restore tokens earlier than
    /// its policy allows; elapsed idle time alone is insufficient. Cleanup must
    /// serialize with checks so it cannot delete a concurrently consumed bucket.
    async fn prune_idle(&self, max_idle: Duration) -> Result<usize, RateLimitError>;
}