armature_ratelimit/algorithms/mod.rs
1//! Rate limiting algorithms
2//!
3//! This module provides different rate limiting algorithms:
4//!
5//! - **Token Bucket**: Smooth rate limiting with burst capacity
6//! - **Sliding Window Log**: Precise rate limiting with individual request tracking
7//! - **Fixed Window**: Simple rate limiting with fixed time windows
8
9mod fixed_window;
10mod sliding_window;
11mod token_bucket;
12
13pub use fixed_window::FixedWindow;
14pub use sliding_window::SlidingWindowLog;
15pub use token_bucket::TokenBucket;
16
17use dashmap::DashMap;
18use std::time::{Duration, Instant};
19
20/// Fraction of the key cap reclaimed by a single eviction pass: `max_keys / 64`.
21///
22/// Evicting exactly one entry per new key means every request past the cap pays
23/// a full scan of the map — the key-rotating client the cap exists to stop turns
24/// a memory-exhaustion attempt into a CPU-exhaustion one. Reclaiming a batch
25/// amortises that scan over the next `max_keys / 64` insertions, so the
26/// per-request cost is bounded by a small constant while the map stays capped.
27pub(crate) const EVICTION_BATCH_DIVISOR: usize = 64;
28
29/// Number of entries a single eviction pass reclaims for a given key cap.
30pub(crate) fn eviction_batch_size(max_keys: usize) -> usize {
31 (max_keys / EVICTION_BATCH_DIVISOR).max(1)
32}
33
34/// Evict the `batch` least-recently-active entries from `map`.
35///
36/// `last_active` reports an entry's most recent activity; entries for which it
37/// yields `None` (an empty request log, say) carry no usable age and are evicted
38/// first, since they hold state nothing is relying on.
39///
40/// The candidate list is materialised before any removal so no shard lock is
41/// held across a mutation, and the batch boundary is found with a linear
42/// selection rather than a full sort.
43pub(crate) fn evict_oldest_batch<V>(
44 map: &DashMap<String, V>,
45 batch: usize,
46 last_active: impl Fn(&V) -> Option<Instant>,
47) {
48 if batch == 0 {
49 return;
50 }
51
52 let mut entries: Vec<(String, Option<Instant>)> = map
53 .iter()
54 .map(|e| (e.key().clone(), last_active(e.value())))
55 .collect();
56
57 if entries.is_empty() {
58 return;
59 }
60
61 // `None` sorts before `Some`, so ageless entries lead.
62 let batch = batch.min(entries.len());
63 if batch < entries.len() {
64 entries.select_nth_unstable_by_key(batch - 1, |(_, t)| *t);
65 }
66
67 for (key, _) in entries.into_iter().take(batch) {
68 map.remove(&key);
69 }
70}
71
72/// Rate limiting algorithm configuration
73#[derive(Debug, Clone)]
74pub enum Algorithm {
75 /// Token bucket algorithm
76 ///
77 /// Tokens are added at a fixed rate and consumed on each request.
78 /// Allows bursts up to the bucket capacity.
79 TokenBucket {
80 /// Maximum number of tokens (burst capacity)
81 capacity: u64,
82 /// Tokens added per second
83 refill_rate: f64,
84 },
85
86 /// Sliding window log algorithm
87 ///
88 /// Tracks individual request timestamps within a sliding window.
89 /// Most accurate but requires more storage.
90 SlidingWindowLog {
91 /// Maximum requests allowed in the window
92 max_requests: u64,
93 /// Window duration
94 window: Duration,
95 },
96
97 /// Fixed window algorithm
98 ///
99 /// Divides time into fixed windows and counts requests per window.
100 /// Simple but can allow bursts at window boundaries.
101 FixedWindow {
102 /// Maximum requests allowed per window
103 max_requests: u64,
104 /// Window duration
105 window: Duration,
106 },
107}
108
109impl Algorithm {
110 /// Create a token bucket algorithm with default values (100 capacity, 10/sec refill)
111 pub fn token_bucket_default() -> Self {
112 Self::TokenBucket {
113 capacity: 100,
114 refill_rate: 10.0,
115 }
116 }
117
118 /// Create a sliding window algorithm with default values (100 requests per minute)
119 pub fn sliding_window_default() -> Self {
120 Self::SlidingWindowLog {
121 max_requests: 100,
122 window: Duration::from_secs(60),
123 }
124 }
125
126 /// Create a fixed window algorithm with default values (100 requests per minute)
127 pub fn fixed_window_default() -> Self {
128 Self::FixedWindow {
129 max_requests: 100,
130 window: Duration::from_secs(60),
131 }
132 }
133
134 /// Get the effective limit for this algorithm
135 pub fn limit(&self) -> u64 {
136 match self {
137 Algorithm::TokenBucket { capacity, .. } => *capacity,
138 Algorithm::SlidingWindowLog { max_requests, .. } => *max_requests,
139 Algorithm::FixedWindow { max_requests, .. } => *max_requests,
140 }
141 }
142
143 /// Get a human-readable description of the algorithm
144 pub fn description(&self) -> String {
145 match self {
146 Algorithm::TokenBucket {
147 capacity,
148 refill_rate,
149 } => format!(
150 "Token bucket: {} capacity, {:.2} tokens/sec refill",
151 capacity, refill_rate
152 ),
153 Algorithm::SlidingWindowLog {
154 max_requests,
155 window,
156 } => format!("Sliding window: {} requests per {:?}", max_requests, window),
157 Algorithm::FixedWindow {
158 max_requests,
159 window,
160 } => format!("Fixed window: {} requests per {:?}", max_requests, window),
161 }
162 }
163}
164
165/// Trait for rate limiting algorithm implementations
166pub trait RateLimitAlgorithm: Send + Sync {
167 /// Check if a request is allowed
168 /// Returns (allowed, remaining_count)
169 fn check(&self, key: &str) -> (bool, u64);
170
171 /// Reset the state for a key
172 fn reset(&self, key: &str);
173
174 /// Get the current remaining count for a key
175 fn remaining(&self, key: &str) -> u64;
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn test_algorithm_limit() {
184 assert_eq!(
185 Algorithm::TokenBucket {
186 capacity: 50,
187 refill_rate: 5.0
188 }
189 .limit(),
190 50
191 );
192 assert_eq!(
193 Algorithm::SlidingWindowLog {
194 max_requests: 100,
195 window: Duration::from_secs(60)
196 }
197 .limit(),
198 100
199 );
200 assert_eq!(
201 Algorithm::FixedWindow {
202 max_requests: 200,
203 window: Duration::from_secs(30)
204 }
205 .limit(),
206 200
207 );
208 }
209
210 #[test]
211 fn test_algorithm_description() {
212 let algo = Algorithm::TokenBucket {
213 capacity: 100,
214 refill_rate: 10.0,
215 };
216 assert!(algo.description().contains("Token bucket"));
217 assert!(algo.description().contains("100"));
218 }
219
220 #[test]
221 fn test_default_algorithms() {
222 let tb = Algorithm::token_bucket_default();
223 assert!(matches!(
224 tb,
225 Algorithm::TokenBucket {
226 capacity: 100,
227 refill_rate: _
228 }
229 ));
230
231 let sw = Algorithm::sliding_window_default();
232 assert!(matches!(
233 sw,
234 Algorithm::SlidingWindowLog {
235 max_requests: 100,
236 ..
237 }
238 ));
239
240 let fw = Algorithm::fixed_window_default();
241 assert!(matches!(
242 fw,
243 Algorithm::FixedWindow {
244 max_requests: 100,
245 ..
246 }
247 ));
248 }
249}