Skip to main content

serenade_rate_limiter/
limiter.rs

1//! User-facing [`RateLimiter`] handle.
2
3use std::sync::Arc;
4use std::time::Instant;
5
6use crate::{Policy, RateLimit, RateLimiterError, RateLimiterStorage};
7
8/// Named limiter bound to one subject key and a [`RateLimiterStorage`].
9#[derive(Clone)]
10pub struct RateLimiter {
11    id: String,
12    policy: Policy,
13    storage: Arc<dyn RateLimiterStorage>,
14}
15
16impl RateLimiter {
17    pub(crate) fn new(id: String, policy: Policy, storage: Arc<dyn RateLimiterStorage>) -> Self {
18        Self {
19            id,
20            policy,
21            storage,
22        }
23    }
24
25    /// Storage id (`{limiterName}-{key}`).
26    #[must_use]
27    pub fn id(&self) -> &str {
28        &self.id
29    }
30
31    /// Policy used by this limiter.
32    #[must_use]
33    pub const fn policy(&self) -> &Policy {
34        &self.policy
35    }
36
37    /// Consumes `tokens` from the budget.
38    ///
39    /// # Errors
40    ///
41    /// Propagates invalid token counts and storage failures.
42    pub fn consume(&self, tokens: u32) -> Result<RateLimit, RateLimiterError> {
43        self.storage.consume(
44            &self.id,
45            &self.policy,
46            tokens,
47            Instant::now(),
48            Some(self.policy.storage_ttl()),
49        )
50    }
51
52    /// Clears stored state for this subject.
53    ///
54    /// # Errors
55    ///
56    /// Propagates storage failures.
57    pub fn reset(&self) -> Result<(), RateLimiterError> {
58        self.storage.reset(&self.id)
59    }
60}