Skip to main content

request_rate_limiter/
keyed.rs

1//! Keyed rate limiting functionality.
2//!
3//! This module provides rate limiting with per-key isolation, allowing independent
4//! rate limiting across different clients, users, or request types.
5
6use std::{fmt::Debug, hash::Hash, time::Duration};
7
8use async_trait::async_trait;
9use dashmap::{mapref::one::Ref, DashMap};
10
11use crate::{
12    algorithms::RateLimitAlgorithm,
13    limiter::{DefaultRateLimiter, RateLimiter, RequestOutcome, Token},
14};
15
16/// Controls the rate of requests over time with per-key rate limiting.
17///
18/// Each key maintains its own rate limit state, allowing for independent
19/// rate limiting across different clients, users, or request types.
20#[async_trait]
21pub trait RateLimiterKeyed<K>: Sync
22where
23    K: Hash + Eq + Send + Sync,
24{
25    /// Acquire permission to make a request for a specific key. Waits until a token is available.
26    async fn acquire(&self, key: &K) -> Token;
27
28    /// Acquire permission to make a request for a specific key with a timeout.
29    /// Returns a token if successful.
30    async fn acquire_timeout(&self, key: &K, duration: Duration) -> Option<Token>;
31
32    /// Release the token and record the outcome of the request for the specific key.
33    /// The response time is calculated from when the token was acquired.
34    async fn release(&self, key: &K, token: Token, outcome: Option<RequestOutcome>);
35}
36
37/// A keyed rate limiter that maintains separate rate limiters for each key.
38///
39/// Uses DashMap for efficient concurrent access to per-key rate limiters.
40/// Each key gets its own independent rate limiter instance.
41#[derive(Debug)]
42pub struct DefaultRateLimiterKeyed<T, K>
43where
44    T: RateLimitAlgorithm + Debug + Clone,
45    K: Hash + Eq + Send + Sync,
46{
47    limiters: DashMap<K, DefaultRateLimiter<T>>,
48    algorithm: T,
49}
50
51impl<T, K> DefaultRateLimiterKeyed<T, K>
52where
53    T: RateLimitAlgorithm + Debug + Clone,
54    K: Hash + Eq + Clone + Send + Sync,
55{
56    /// Create a new keyed rate limiter with the given algorithm factory function.
57    /// Each key will get a fresh instance of the algorithm created by calling the factory.
58    pub fn new(algorithm: T) -> Self {
59        Self {
60            limiters: DashMap::new(),
61            algorithm,
62        }
63    }
64
65    /// Get or create a rate limiter for the given key.
66    /// Uses entry API for better performance and reduced contention.
67    fn get_or_create_limiter(&self, key: &K) -> Ref<'_, K, DefaultRateLimiter<T>> {
68        // Use entry API to avoid double lookup
69        self.limiters
70            .entry(key.clone())
71            .or_insert_with(|| DefaultRateLimiter::new(self.algorithm.clone()));
72
73        // This unwrap is safe because we just inserted the key if it didn't exist
74        self.limiters.get(key).unwrap()
75    }
76
77    /// Get the number of active keys being tracked.
78    pub fn active_keys(&self) -> usize {
79        self.limiters.len()
80    }
81
82    /// Remove a key and its associated rate limiter.
83    /// Returns true if the key existed and was removed.
84    pub fn remove_key(&self, key: &K) -> bool {
85        self.limiters.remove(key).is_some()
86    }
87
88    /// Clear all keys and their associated rate limiters.
89    pub fn clear(&self) {
90        self.limiters.clear();
91    }
92}
93
94#[async_trait]
95impl<T, K> RateLimiterKeyed<K> for DefaultRateLimiterKeyed<T, K>
96where
97    T: RateLimitAlgorithm + Send + Clone + Sync + Debug,
98    K: Hash + Eq + Clone + Send + Sync,
99{
100    async fn acquire(&self, key: &K) -> Token {
101        let limiter = self.get_or_create_limiter(key);
102        limiter.acquire().await
103    }
104
105    async fn acquire_timeout(&self, key: &K, duration: Duration) -> Option<Token> {
106        let limiter = self.get_or_create_limiter(key);
107        limiter.acquire_timeout(duration).await
108    }
109
110    async fn release(&self, key: &K, token: Token, outcome: Option<RequestOutcome>) {
111        let limiter = self.get_or_create_limiter(key);
112        limiter.release(token, outcome).await
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use crate::{
119        algorithms::Fixed,
120        keyed::{DefaultRateLimiterKeyed, RateLimiterKeyed},
121        limiter::RequestOutcome,
122    };
123
124    #[tokio::test]
125    async fn keyed_rate_limiter_works_independently_per_key() {
126        let limiter = DefaultRateLimiterKeyed::<_, String>::new(Fixed::new(1));
127
128        let key1 = "key1".to_string();
129        let key2 = "key2".to_string();
130        // Acquire tokens for different keys - should work independently
131        let token1 = limiter.acquire(&key1).await;
132        let token2 = limiter.acquire(&key2).await;
133
134        // Both should succeed because they're different keys
135        limiter
136            .release(&key1, token1, Some(RequestOutcome::Success))
137            .await;
138        limiter
139            .release(&key2, token2, Some(RequestOutcome::Success))
140            .await;
141
142        assert_eq!(limiter.active_keys(), 2);
143    }
144
145    #[tokio::test]
146    async fn keyed_rate_limiter_manages_keys() {
147        let limiter = DefaultRateLimiterKeyed::<_, String>::new(Fixed::new(10));
148
149        // Create limiters for multiple keys
150        let _token1 = limiter.acquire(&"user1".to_string()).await;
151        let _token2 = limiter.acquire(&"user2".to_string()).await;
152        let _token3 = limiter.acquire(&"user3".to_string()).await;
153
154        assert_eq!(limiter.active_keys(), 3);
155
156        // Remove one key
157        assert!(limiter.remove_key(&"user2".to_string()));
158        assert_eq!(limiter.active_keys(), 2);
159
160        // Try to remove non-existent key
161        assert!(!limiter.remove_key(&"nonexistent".to_string()));
162
163        // Clear all keys
164        limiter.clear();
165        assert_eq!(limiter.active_keys(), 0);
166    }
167}