Skip to main content

serenade_rate_limiter/
storage.rs

1//! Storage contract for limiter windows.
2
3use std::time::{Duration, Instant};
4
5use crate::{Policy, RateLimit, RateLimiterError};
6
7/// Persisted window for one limiter subject.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum WindowState {
10    /// Token-bucket snapshot (scaled integer tokens).
11    TokenBucket {
12        /// Available tokens multiplied by the internal scale factor.
13        tokens_scaled: u128,
14        /// Last refill timestamp.
15        updated_at: Instant,
16    },
17    /// Fixed-window snapshot.
18    FixedWindow {
19        /// Tokens consumed in the current window.
20        count: u32,
21        /// Instant the current window started.
22        window_start: Instant,
23    },
24}
25
26/// Persists per-subject limiter windows.
27pub trait RateLimiterStorage: Send + Sync {
28    /// Atomically applies `policy.consume` for `id`.
29    ///
30    /// # Errors
31    ///
32    /// Propagates policy and storage failures.
33    fn consume(
34        &self,
35        id: &str,
36        policy: &Policy,
37        tokens: u32,
38        now: Instant,
39        ttl: Option<Duration>,
40    ) -> Result<RateLimit, RateLimiterError>;
41
42    /// Deletes any stored window for `id`.
43    ///
44    /// # Errors
45    ///
46    /// Propagates storage failures.
47    fn reset(&self, id: &str) -> Result<(), RateLimiterError>;
48}