Skip to main content

serenade_rate_limiter/
memory.rs

1//! Process-local [`RateLimiterStorage`].
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5use std::time::{Duration, Instant};
6
7use crate::{Policy, RateLimit, RateLimiterError, RateLimiterStorage, WindowState, validate_key};
8
9#[derive(Debug)]
10struct Entry {
11    state: Option<WindowState>,
12    expires_at: Option<Instant>,
13}
14
15impl Entry {
16    fn is_expired(&self, now: Instant) -> bool {
17        self.expires_at.is_some_and(|at| at <= now)
18    }
19}
20
21/// In-process rate-limiter storage backed by a [`Mutex`] + [`HashMap`].
22#[derive(Debug, Default)]
23pub struct InMemoryRateLimiterStorage {
24    inner: Mutex<HashMap<String, Entry>>,
25}
26
27impl InMemoryRateLimiterStorage {
28    /// Empty storage.
29    #[must_use]
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    fn with_map<T>(&self, f: impl FnOnce(&mut HashMap<String, Entry>) -> T) -> T {
35        let mut guard = self
36            .inner
37            .lock()
38            .expect("serenade-rate-limiter InMemoryRateLimiterStorage mutex poisoned");
39        f(&mut guard)
40    }
41}
42
43impl RateLimiterStorage for InMemoryRateLimiterStorage {
44    fn consume(
45        &self,
46        id: &str,
47        policy: &Policy,
48        tokens: u32,
49        now: Instant,
50        ttl: Option<Duration>,
51    ) -> Result<RateLimit, RateLimiterError> {
52        validate_key(id)?;
53        self.with_map(|map| {
54            let entry = map.entry(id.to_owned()).or_insert_with(|| Entry {
55                state: None,
56                expires_at: None,
57            });
58            if entry.is_expired(now) {
59                entry.state = None;
60                entry.expires_at = None;
61            }
62            let result = policy.consume(&mut entry.state, tokens, now)?;
63            entry.expires_at = ttl.map(|duration| now + duration);
64            Ok(result)
65        })
66    }
67
68    fn reset(&self, id: &str) -> Result<(), RateLimiterError> {
69        validate_key(id)?;
70        self.with_map(|map| {
71            map.remove(id);
72            Ok(())
73        })
74    }
75}