Skip to main content

rust_web_server/rate_limit/
mod.rs

1#[cfg(test)]
2mod tests;
3
4use std::collections::{HashMap, VecDeque};
5use std::sync::{Mutex, OnceLock};
6#[cfg(not(target_arch = "wasm32"))]
7use std::sync::Arc;
8use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
9use std::time::{Duration, Instant};
10
11/// A sliding-window per-key rate limiter.
12///
13/// Each call to [`RateLimiter::check`] records a timestamp for the given key
14/// and returns `true` when the number of calls within the current window is
15/// still below `max_requests`. Returns `false` once the limit is exceeded.
16///
17/// Thread-safe: the internal state is behind a `Mutex` so it can be shared
18/// across threads via [`global`] or wrapped in an `Arc`.
19///
20/// # Example
21///
22/// ```rust,no_run
23/// use rust_web_server::rate_limit::RateLimiter;
24///
25/// let limiter = RateLimiter::new(100, 60); // 100 req / 60 s
26///
27/// if limiter.check("192.168.1.1") {
28///     // process request
29/// } else {
30///     // return 429 Too Many Requests
31/// }
32/// ```
33pub struct RateLimiter {
34    state: Mutex<HashMap<String, VecDeque<Instant>>>,
35    max_requests: AtomicU32,
36    window_secs: AtomicU64,
37}
38
39impl RateLimiter {
40    /// Create a new limiter allowing `max_requests` per `window_secs`-second window.
41    pub fn new(max_requests: u32, window_secs: u64) -> Self {
42        RateLimiter {
43            state: Mutex::new(HashMap::new()),
44            max_requests: AtomicU32::new(max_requests),
45            window_secs: AtomicU64::new(window_secs),
46        }
47    }
48
49    /// Update the limits on a live limiter without restarting.
50    ///
51    /// Changes take effect on the next call to [`check`] or [`remaining`].
52    /// Called automatically by [`crate::config_reload::reload`] on SIGHUP.
53    pub fn set_limits(&self, max_requests: u32, window_secs: u64) {
54        self.max_requests.store(max_requests, Ordering::Relaxed);
55        self.window_secs.store(window_secs, Ordering::Relaxed);
56    }
57
58    /// The current `(max_requests, window_secs)`.
59    pub fn limits(&self) -> (u32, u64) {
60        (self.max_requests.load(Ordering::Relaxed), self.window_secs.load(Ordering::Relaxed))
61    }
62
63    fn window(&self) -> Duration {
64        Duration::from_secs(self.window_secs.load(Ordering::Relaxed))
65    }
66
67    fn max(&self) -> u32 {
68        self.max_requests.load(Ordering::Relaxed)
69    }
70
71    /// Returns `true` if `key` (typically a client IP) is within the rate limit,
72    /// or `false` if the limit has been exceeded.
73    ///
74    /// A permitted call is always recorded so it counts toward future limits.
75    pub fn check(&self, key: &str) -> bool {
76        let now = Instant::now();
77        let window = self.window();
78        let max = self.max();
79        let mut guard = self.state.lock().unwrap();
80        let timestamps = guard.entry(key.to_string()).or_default();
81
82        // Drop timestamps older than the window.
83        while timestamps.front().map(|t| now.duration_since(*t) > window).unwrap_or(false) {
84            timestamps.pop_front();
85        }
86
87        if (timestamps.len() as u32) < max {
88            timestamps.push_back(now);
89            true
90        } else {
91            false
92        }
93    }
94
95    /// Seconds a rejected `key` should wait before trying again.
96    ///
97    /// The window length, a safe upper bound: the oldest request in the
98    /// window may expire sooner, so a client that waits this long is never
99    /// rejected again for the same burst — it may only wait longer than
100    /// strictly needed.
101    pub fn retry_after(&self, _key: &str) -> u64 {
102        self.window_secs.load(Ordering::Relaxed)
103    }
104
105    /// Number of remaining requests `key` may make within the current window.
106    pub fn remaining(&self, key: &str) -> u32 {
107        let now = Instant::now();
108        let window = self.window();
109        let max = self.max();
110        let mut guard = self.state.lock().unwrap();
111        let timestamps = guard.entry(key.to_string()).or_default();
112        while timestamps.front().map(|t| now.duration_since(*t) > window).unwrap_or(false) {
113            timestamps.pop_front();
114        }
115        max.saturating_sub(timestamps.len() as u32)
116    }
117
118    /// Remove all tracked state for `key`. Useful in tests.
119    pub fn reset(&self, key: &str) {
120        self.state.lock().unwrap().remove(key);
121    }
122}
123
124// ── RedisRateLimiter ──────────────────────────────────────────────────────────
125
126#[cfg(not(target_arch = "wasm32"))]
127use crate::redis_protocol::{RespConn, RespReply};
128
129/// A distributed, fixed-window rate limiter backed by a Redis server.
130///
131/// [`RateLimiter`] only protects a single process: two `rws` instances behind
132/// a load balancer each track their own in-memory counters, so the effective
133/// limit for a client doubles (or worse) as replicas scale out. `RedisRateLimiter`
134/// keys the counter on a shared Redis server instead, so every instance enforces
135/// the same budget.
136///
137/// Unlike [`RateLimiter`]'s sliding window (a deque of timestamps), this uses a
138/// fixed-window counter: `key`'s count lives under one Redis key with a TTL equal
139/// to the window length, incremented atomically via `INCR`. This is the standard
140/// distributed rate-limiting pattern — Redis guarantees `INCR` is atomic across
141/// concurrent callers, so counters stay correct even under heavy concurrent load
142/// from multiple `rws` processes. The tradeoff versus a sliding window: a client
143/// can burst up to `2x max_requests` across a window boundary (once near the end
144/// of one window, once at the start of the next).
145///
146/// Cloning is cheap — all clones share the same underlying TCP connection (one
147/// persistent connection per `RedisRateLimiter` instance).
148///
149/// # Example
150///
151/// ```rust,no_run
152/// use rust_web_server::rate_limit::RedisRateLimiter;
153///
154/// let limiter = RedisRateLimiter::new("127.0.0.1:6379", None, 100, 60); // 100 req / 60s
155///
156/// match limiter.check("192.168.1.1") {
157///     Ok(true) => { /* process request */ }
158///     Ok(false) => { /* return 429 Too Many Requests */ }
159///     Err(e) => { /* Redis unreachable — decide fail-open vs fail-closed */ }
160/// }
161/// ```
162#[cfg(not(target_arch = "wasm32"))]
163pub struct RedisRateLimiter {
164    conn: Arc<RespConn>,
165    max_requests: AtomicU32,
166    window_secs: AtomicU64,
167}
168
169#[cfg(not(target_arch = "wasm32"))]
170impl Clone for RedisRateLimiter {
171    fn clone(&self) -> Self {
172        RedisRateLimiter {
173            conn: Arc::clone(&self.conn),
174            max_requests: AtomicU32::new(self.max()),
175            window_secs: AtomicU64::new(self.window().as_secs()),
176        }
177    }
178}
179
180#[cfg(not(target_arch = "wasm32"))]
181impl RedisRateLimiter {
182    /// Create a limiter that connects to `addr` (e.g. `"127.0.0.1:6379"`),
183    /// allowing `max_requests` per `window_secs`-second window.
184    /// `password` is passed to Redis `AUTH` if `Some`.
185    pub fn new(addr: impl Into<String>, password: Option<String>, max_requests: u32, window_secs: u64) -> Self {
186        RedisRateLimiter {
187            conn: Arc::new(RespConn::new(addr, password)),
188            max_requests: AtomicU32::new(max_requests),
189            window_secs: AtomicU64::new(window_secs),
190        }
191    }
192
193    /// Build a limiter from environment variables:
194    /// - `RWS_REDIS_HOST` (default `127.0.0.1`)
195    /// - `RWS_REDIS_PORT` (default `6379`)
196    /// - `RWS_REDIS_PASSWORD` (optional)
197    /// - `RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS` (default `1000`)
198    /// - `RWS_CONFIG_RATE_LIMIT_WINDOW_SECS` (default `60`)
199    pub fn from_env() -> Self {
200        let host = std::env::var("RWS_REDIS_HOST").unwrap_or_else(|_| "127.0.0.1".into());
201        let port = std::env::var("RWS_REDIS_PORT").unwrap_or_else(|_| "6379".into());
202        let addr = format!("{}:{}", host, port);
203        let password = std::env::var("RWS_REDIS_PASSWORD").ok();
204        let max: u32 = std::env::var("RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS")
205            .ok()
206            .and_then(|v| v.parse().ok())
207            .unwrap_or(1000);
208        let window: u64 = std::env::var("RWS_CONFIG_RATE_LIMIT_WINDOW_SECS")
209            .ok()
210            .and_then(|v| v.parse().ok())
211            .unwrap_or(60);
212        Self::new(addr, password, max, window)
213    }
214
215    /// Update the limits on a live limiter without restarting.
216    pub fn set_limits(&self, max_requests: u32, window_secs: u64) {
217        self.max_requests.store(max_requests, Ordering::Relaxed);
218        self.window_secs.store(window_secs, Ordering::Relaxed);
219    }
220
221    fn window(&self) -> Duration {
222        Duration::from_secs(self.window_secs.load(Ordering::Relaxed))
223    }
224
225    fn max(&self) -> u32 {
226        self.max_requests.load(Ordering::Relaxed)
227    }
228
229    /// Seconds a rejected `key` should wait before trying again: the window
230    /// length, a safe upper bound.
231    pub fn retry_after(&self, _key: &str) -> u64 {
232        self.window_secs.load(Ordering::Relaxed)
233    }
234
235    fn redis_key(key: &str) -> Vec<u8> {
236        format!("rws:ratelimit:{}", key).into_bytes()
237    }
238
239    /// Returns `Ok(true)` if `key` (typically a client IP) is within the rate
240    /// limit, `Ok(false)` if the limit has been exceeded, or `Err` if the
241    /// Redis server could not be reached.
242    ///
243    /// A call always increments the shared counter, whether permitted or not,
244    /// so callers must decide for themselves whether to fail open (allow the
245    /// request) or fail closed (deny it) on `Err` — this limiter does not
246    /// silently pick one.
247    pub fn check(&self, key: &str) -> std::io::Result<bool> {
248        let redis_key = Self::redis_key(key);
249        let window = self.window().as_secs().to_string();
250        // Atomically create the key with a TTL the first time it's seen. If
251        // it already exists, `SET ... NX` is a no-op — this only races once,
252        // at creation, and `SET NX` is itself atomic on the Redis server.
253        self.conn.cmd(&[b"SET", &redis_key, b"0", b"EX", window.as_bytes(), b"NX"])?;
254        let count = match self.conn.cmd(&[b"INCR", &redis_key])? {
255            RespReply::Int(n) => n,
256            _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "unexpected INCR reply")),
257        };
258        Ok(count as u32 <= self.max())
259    }
260
261    /// Number of remaining requests `key` may make within the current window,
262    /// or `Err` if the Redis server could not be reached.
263    pub fn remaining(&self, key: &str) -> std::io::Result<u32> {
264        match self.conn.cmd(&[b"GET", &Self::redis_key(key)])? {
265            RespReply::Bulk(Some(bytes)) => {
266                let count: u32 = String::from_utf8_lossy(&bytes).parse().unwrap_or(0);
267                Ok(self.max().saturating_sub(count))
268            }
269            _ => Ok(self.max()),
270        }
271    }
272
273    /// Remove all tracked state for `key`. Useful in tests.
274    pub fn reset(&self, key: &str) -> std::io::Result<()> {
275        self.conn.cmd(&[b"DEL", &Self::redis_key(key)])?;
276        Ok(())
277    }
278}
279
280static GLOBAL_LIMITER: OnceLock<RateLimiter> = OnceLock::new();
281
282/// `true` when the operator set a global rate limit
283/// (`RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS`, e.g. `[rate_limit] max_requests` in
284/// `rws.config.toml`) to a positive number. The `rws` binary enforces
285/// [`global()`] only then — an unset limit means "no global limit", not
286/// "the 1000/60s default".
287pub fn is_configured() -> bool {
288    std::env::var("RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS")
289        .ok()
290        .and_then(|v| v.trim().parse::<u32>().ok())
291        .map_or(false, |max| max > 0)
292}
293
294/// Return the process-wide rate limiter, initialized from environment variables.
295///
296/// | Variable | Default | Meaning |
297/// |---|---|---|
298/// | `RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS` | `1000` | Requests allowed per window |
299/// | `RWS_CONFIG_RATE_LIMIT_WINDOW_SECS` | `60` | Window length in seconds |
300///
301/// Returns `None` when rate limiting is disabled (`RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS=0`).
302pub fn global() -> &'static RateLimiter {
303    GLOBAL_LIMITER.get_or_init(|| {
304        let max: u32 = std::env::var("RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS")
305            .ok()
306            .and_then(|v| v.parse().ok())
307            .unwrap_or(1000);
308        let window: u64 = std::env::var("RWS_CONFIG_RATE_LIMIT_WINDOW_SECS")
309            .ok()
310            .and_then(|v| v.parse().ok())
311            .unwrap_or(60);
312        RateLimiter::new(max, window)
313    })
314}