http-handle 0.0.5

A fast and lightweight Rust library for handling HTTP requests and responses.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2023 - 2026 HTTP Handle

//! Distributed rate-limiting adapters and backend contracts.

use crate::error::ServerError;
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Backend trait for incrementing a rate-limit key in a time window.
///
/// # Examples
///
/// ```rust
/// use http_handle::distributed_rate_limit::RateLimitBackend;
/// # let _ = std::any::TypeId::of::<&dyn RateLimitBackend>();
/// assert_eq!(2 + 2, 4);
/// ```
///
/// # Panics
///
/// Trait usage does not panic by itself.
pub trait RateLimitBackend: Send + Sync + std::fmt::Debug {
    /// Increments key and returns current hit count for the active window.
    fn increment_and_get(
        &self,
        key: &str,
        window_secs: u64,
    ) -> Result<u64, ServerError>;
}

/// Shared rate limiter that works against pluggable backends.
///
/// # Examples
///
/// ```rust
/// use http_handle::distributed_rate_limit::{DistributedRateLimiter, InMemoryBackend};
/// let _limiter = DistributedRateLimiter::new(InMemoryBackend::default(), "ip", 100, 60);
/// assert_eq!(1, 1);
/// ```
///
/// # Panics
///
/// This type does not panic.
#[derive(Clone, Debug)]
pub struct DistributedRateLimiter<B: RateLimitBackend> {
    backend: Arc<B>,
    namespace: String,
    limit_per_window: u64,
    window_secs: u64,
}

impl<B: RateLimitBackend> DistributedRateLimiter<B> {
    /// Creates a distributed limiter with explicit namespace and limits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use http_handle::distributed_rate_limit::{DistributedRateLimiter, InMemoryBackend};
    /// let _ = DistributedRateLimiter::new(InMemoryBackend::default(), "ip", 10, 60);
    /// assert_eq!(1, 1);
    /// ```
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn new(
        backend: B,
        namespace: impl Into<String>,
        limit_per_window: u64,
        window_secs: u64,
    ) -> Self {
        Self {
            backend: Arc::new(backend),
            namespace: namespace.into(),
            limit_per_window: limit_per_window.max(1),
            window_secs: window_secs.max(1),
        }
    }

    /// Returns true when the source should be throttled.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use http_handle::distributed_rate_limit::{DistributedRateLimiter, InMemoryBackend};
    /// use std::net::IpAddr;
    /// let limiter = DistributedRateLimiter::new(InMemoryBackend::default(), "ip", 1, 60);
    /// let ip: IpAddr = "127.0.0.1".parse().expect("ip");
    /// let _ = limiter.is_limited(ip);
    /// assert_eq!(1, 1);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns backend errors when increment operations fail.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn is_limited(
        &self,
        source: IpAddr,
    ) -> Result<bool, ServerError> {
        let key = format!("{}:{}", self.namespace, source);
        let current =
            self.backend.increment_and_get(&key, self.window_secs)?;
        Ok(current > self.limit_per_window)
    }
}

/// In-memory backend useful for local fallback mode and tests.
///
/// # Examples
///
/// ```rust
/// use http_handle::distributed_rate_limit::InMemoryBackend;
/// let _backend = InMemoryBackend::default();
/// assert_eq!(1, 1);
/// ```
///
/// # Panics
///
/// This type does not panic.
#[derive(Debug, Default)]
pub struct InMemoryBackend {
    state: Mutex<HashMap<String, Vec<Instant>>>,
}

impl RateLimitBackend for InMemoryBackend {
    fn increment_and_get(
        &self,
        key: &str,
        window_secs: u64,
    ) -> Result<u64, ServerError> {
        let now = Instant::now();
        let mut state = self.state.lock().map_err(|_| {
            ServerError::Custom("rate state poisoned".into())
        })?;
        let hits = state.entry(key.to_string()).or_default();
        hits.retain(|ts| {
            now.duration_since(*ts) <= Duration::from_secs(window_secs)
        });
        hits.push(now);
        Ok(hits.len() as u64)
    }
}

/// Minimal Redis-like client contract.
///
/// # Examples
///
/// ```rust
/// use http_handle::distributed_rate_limit::RedisClient;
/// # let _ = std::any::TypeId::of::<&dyn RedisClient>();
/// assert_eq!(1, 1);
/// ```
///
/// # Panics
///
/// Trait usage does not panic by itself.
pub trait RedisClient: Send + Sync + std::fmt::Debug {
    /// Increments key, sets TTL as needed, and returns current count.
    fn incr_with_ttl(
        &self,
        key: &str,
        ttl_secs: u64,
    ) -> Result<u64, ServerError>;
}

/// Redis backend adapter.
///
/// # Examples
///
/// ```rust
/// use http_handle::distributed_rate_limit::{RedisBackend, RedisClient};
/// use http_handle::ServerError;
/// #[derive(Debug)]
/// struct Dummy;
/// impl RedisClient for Dummy {
///     fn incr_with_ttl(&self, _key: &str, _ttl_secs: u64) -> Result<u64, ServerError> { Ok(1) }
/// }
/// let _backend = RedisBackend::new(Dummy);
/// assert_eq!(1, 1);
/// ```
///
/// # Panics
///
/// This type does not panic.
#[derive(Debug)]
pub struct RedisBackend<C: RedisClient> {
    client: C,
}

impl<C: RedisClient> RedisBackend<C> {
    /// Creates a new Redis backend adapter.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use http_handle::distributed_rate_limit::{RedisBackend, RedisClient};
    /// use http_handle::ServerError;
    /// #[derive(Debug)]
    /// struct Dummy;
    /// impl RedisClient for Dummy {
    ///     fn incr_with_ttl(&self, _key: &str, _ttl_secs: u64) -> Result<u64, ServerError> { Ok(1) }
    /// }
    /// let _backend = RedisBackend::new(Dummy);
    /// assert_eq!(1, 1);
    /// ```
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn new(client: C) -> Self {
        Self { client }
    }
}

impl<C: RedisClient> RateLimitBackend for RedisBackend<C> {
    fn increment_and_get(
        &self,
        key: &str,
        window_secs: u64,
    ) -> Result<u64, ServerError> {
        self.client.incr_with_ttl(key, window_secs)
    }
}

/// Minimal Memcached-like client contract.
///
/// # Examples
///
/// ```rust
/// use http_handle::distributed_rate_limit::MemcachedClient;
/// # let _ = std::any::TypeId::of::<&dyn MemcachedClient>();
/// assert_eq!(1, 1);
/// ```
///
/// # Panics
///
/// Trait usage does not panic by itself.
pub trait MemcachedClient: Send + Sync + std::fmt::Debug {
    /// Increments key and returns current count.
    fn incr(
        &self,
        key: &str,
        initial: u64,
        ttl_secs: u32,
    ) -> Result<u64, ServerError>;
}

/// Memcached backend adapter.
///
/// # Examples
///
/// ```rust
/// use http_handle::distributed_rate_limit::{MemcachedBackend, MemcachedClient};
/// use http_handle::ServerError;
/// #[derive(Debug)]
/// struct Dummy;
/// impl MemcachedClient for Dummy {
///     fn incr(&self, _key: &str, _initial: u64, _ttl_secs: u32) -> Result<u64, ServerError> { Ok(1) }
/// }
/// let _backend = MemcachedBackend::new(Dummy);
/// assert_eq!(1, 1);
/// ```
///
/// # Panics
///
/// This type does not panic.
#[derive(Debug)]
pub struct MemcachedBackend<C: MemcachedClient> {
    client: C,
}

impl<C: MemcachedClient> MemcachedBackend<C> {
    /// Creates a new Memcached backend adapter.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use http_handle::distributed_rate_limit::{MemcachedBackend, MemcachedClient};
    /// use http_handle::ServerError;
    /// #[derive(Debug)]
    /// struct Dummy;
    /// impl MemcachedClient for Dummy {
    ///     fn incr(&self, _key: &str, _initial: u64, _ttl_secs: u32) -> Result<u64, ServerError> { Ok(1) }
    /// }
    /// let _backend = MemcachedBackend::new(Dummy);
    /// assert_eq!(1, 1);
    /// ```
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn new(client: C) -> Self {
        Self { client }
    }
}

impl<C: MemcachedClient> RateLimitBackend for MemcachedBackend<C> {
    fn increment_and_get(
        &self,
        key: &str,
        window_secs: u64,
    ) -> Result<u64, ServerError> {
        self.client.incr(key, 1, window_secs as u32)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Default)]
    struct MockRedis {
        counts: Mutex<HashMap<String, u64>>,
    }
    impl RedisClient for MockRedis {
        fn incr_with_ttl(
            &self,
            key: &str,
            _ttl_secs: u64,
        ) -> Result<u64, ServerError> {
            let mut counts = self
                .counts
                .lock()
                .map_err(|_| ServerError::Custom("poisoned".into()))?;
            let entry = counts.entry(key.to_string()).or_insert(0);
            *entry += 1;
            Ok(*entry)
        }
    }

    #[derive(Debug, Default)]
    struct MockMemcached {
        counts: Mutex<HashMap<String, u64>>,
    }
    impl MemcachedClient for MockMemcached {
        fn incr(
            &self,
            key: &str,
            initial: u64,
            _ttl_secs: u32,
        ) -> Result<u64, ServerError> {
            let mut counts = self
                .counts
                .lock()
                .map_err(|_| ServerError::Custom("poisoned".into()))?;
            if let Some(entry) = counts.get_mut(key) {
                *entry += 1;
                Ok(*entry)
            } else {
                let _ = counts.insert(key.to_string(), initial);
                Ok(initial)
            }
        }
    }

    #[test]
    fn in_memory_backend_enforces_limit() {
        let limiter = DistributedRateLimiter::new(
            InMemoryBackend::default(),
            "ip",
            2,
            60,
        );
        let ip: IpAddr = "127.0.0.1".parse().expect("ip");
        assert!(!limiter.is_limited(ip).expect("limit"));
        assert!(!limiter.is_limited(ip).expect("limit"));
        assert!(limiter.is_limited(ip).expect("limit"));
    }

    #[test]
    fn redis_adapter_routes_calls() {
        let backend = RedisBackend::new(MockRedis::default());
        let limiter = DistributedRateLimiter::new(backend, "ip", 1, 60);
        let ip: IpAddr = "127.0.0.2".parse().expect("ip");
        assert!(!limiter.is_limited(ip).expect("limit"));
        assert!(limiter.is_limited(ip).expect("limit"));
    }

    #[test]
    fn memcached_adapter_routes_calls() {
        let backend = MemcachedBackend::new(MockMemcached::default());
        let limiter = DistributedRateLimiter::new(backend, "ip", 1, 60);
        let ip: IpAddr = "127.0.0.3".parse().expect("ip");
        assert!(!limiter.is_limited(ip).expect("limit"));
        assert!(limiter.is_limited(ip).expect("limit"));
    }

    #[test]
    fn limiter_propagates_backend_errors() {
        #[derive(Debug)]
        struct FailingBackend;
        impl RateLimitBackend for FailingBackend {
            fn increment_and_get(
                &self,
                _key: &str,
                _window_secs: u64,
            ) -> Result<u64, ServerError> {
                Err(ServerError::Custom("backend down".into()))
            }
        }

        let limiter =
            DistributedRateLimiter::new(FailingBackend, "ip", 0, 0);
        let ip: IpAddr = "127.0.0.9".parse().expect("ip");
        let err = limiter.is_limited(ip).expect_err("must fail");
        assert!(err.to_string().contains("backend down"));
    }

    #[test]
    fn in_memory_backend_maps_poisoned_lock_to_error() {
        let backend = InMemoryBackend::default();
        let _ = std::panic::catch_unwind(|| {
            let _guard = backend.state.lock().expect("lock");
            panic!("poison lock");
        });
        let err = backend
            .increment_and_get("ip:127.0.0.1", 60)
            .expect_err("poisoned lock should error");
        assert!(err.to_string().contains("poisoned"));
    }
}