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
//! Rate limiting plugin using token bucket algorithm for controlling request frequency.
//!
//! This module provides rate limiting functionality to protect Tako applications from abuse
//! and ensure fair resource usage. It implements a token bucket algorithm with per-IP tracking,
//! configurable burst sizes, and automatic token replenishment. The plugin maintains state
//! using a concurrent hash map and spawns a background task for token replenishment and
//! cleanup of inactive buckets.
//!
//! The rate limiter plugin can be applied at both router-level (all routes) and route-level
//! (specific routes), allowing different rate limits for different endpoints.
//!
//! # Examples
//!
//! ```rust
//! use tako::plugins::rate_limiter::{RateLimiterPlugin, RateLimiterBuilder};
//! use tako::plugins::TakoPlugin;
//! use tako::router::Router;
//! use tako::Method;
//! use http::StatusCode;
//!
//! async fn handler(_req: tako::types::Request) -> &'static str {
//! "Response"
//! }
//!
//! async fn api_handler(_req: tako::types::Request) -> &'static str {
//! "API response"
//! }
//!
//! let mut router = Router::new();
//!
//! // Router-level: Basic rate limiting (50 req/sec, burst 100)
//! let global_limiter = RateLimiterBuilder::new()
//! .max_requests(100)
//! .refill_rate(50)
//! .refill_interval_ms(1000)
//! .build();
//! router.plugin(global_limiter);
//!
//! // Route-level: Stricter rate limiting for API (5 req/sec, burst 10)
//! let api_route = router.route(Method::POST, "/api/sensitive", api_handler);
//! let api_limiter = RateLimiterBuilder::new()
//! .max_requests(10)
//! .refill_rate(5)
//! .refill_interval_ms(1000)
//! .status(StatusCode::TOO_MANY_REQUESTS)
//! .build();
//! api_route.plugin(api_limiter);
//! ```
use IpAddr;
use SocketAddr;
use Arc;
use AtomicBool;
use Ordering;
use Duration;
use Instant;
use Result;
use StatusCode;
use HashMap as SccHashMap;
use crateTakoBody;
use crateNext;
use crateTakoPlugin;
use crateResponder;
use crateRouter;
use crateRequest;
/// Rate limiter configuration parameters.
///
/// `Config` defines the behavior of the rate limiter including the maximum
/// number of requests allowed (capacity), request quota replenishment rate,
/// update frequency, and HTTP status code for rate limit violations. The rate limiter
/// allows for burst traffic up to the max capacity while maintaining an average rate over time.
///
/// # Examples
///
/// ```rust
/// use tako::plugins::rate_limiter::Config;
/// use http::StatusCode;
///
/// // Allow 100 requests per second with burst up to 200
/// let config = Config {
/// max_requests: 200,
/// refill_rate: 100,
/// refill_interval_ms: 1000,
/// status_on_limit: StatusCode::TOO_MANY_REQUESTS,
/// };
/// ```
/// Builder for configuring rate limiter settings with a fluent API.
///
/// `RateLimiterBuilder` provides a convenient way to construct rate limiter configurations
/// using method chaining. The rate limiter works by maintaining a quota of available requests where:
/// - `max_requests`: Maximum burst capacity (how many requests can be made at once)
/// - `refill_rate`: Number of requests allowed per refill interval
/// - `refill_interval_ms`: How often to refill the request quota (in milliseconds)
///
/// # Examples
///
/// ```rust
/// use tako::plugins::rate_limiter::RateLimiterBuilder;
/// use http::StatusCode;
///
/// // Allow 100 requests per second with burst up to 1000
/// let high_traffic = RateLimiterBuilder::new()
/// .max_requests(1000)
/// .refill_rate(100)
/// .refill_interval_ms(1000)
/// .build();
///
/// // Allow 5 requests per second, max 10 burst
/// let conservative = RateLimiterBuilder::new()
/// .max_requests(10)
/// .refill_rate(5)
/// .refill_interval_ms(1000)
/// .build();
///
/// // Allow 1 request per 500ms (2 per second)
/// let strict = RateLimiterBuilder::new()
/// .max_requests(1)
/// .refill_rate(1)
/// .refill_interval_ms(500)
/// .build();
/// ```
;
/// Request quota tracker for rate limiting per IP address.
///
/// `Bucket` represents the state of request quota for a single IP address including
/// the current number of available requests and last access time. Each IP address
/// gets its own bucket for tracking rate limits independently.
///
/// # Examples
///
/// ```rust
/// use std::time::Instant;
///
/// # struct Bucket {
/// # available: f64,
/// # last_seen: Instant,
/// # }
/// let bucket = Bucket {
/// available: 60.0,
/// last_seen: Instant::now(),
/// };
/// ```
/// Rate limiting plugin with per-IP request quota tracking.
///
/// `RateLimiterPlugin` provides comprehensive rate limiting functionality by tracking
/// request quotas per IP address. It maintains per-IP state in a concurrent hash map,
/// spawns a background task for quota replenishment and cleanup, and integrates with
/// Tako's middleware system to enforce rate limits on incoming requests.
///
/// # Examples
///
/// ```rust
/// use tako::plugins::rate_limiter::{RateLimiterPlugin, RateLimiterBuilder};
/// use tako::plugins::TakoPlugin;
/// use tako::router::Router;
///
/// // Create and configure rate limiter: 50 requests/sec, max 100 burst
/// let limiter = RateLimiterBuilder::new()
/// .max_requests(100)
/// .refill_rate(50)
/// .refill_interval_ms(1000)
/// .build();
///
/// // Apply to router
/// let mut router = Router::new();
/// router.plugin(limiter);
/// ```
/// Middleware function that enforces rate limiting per IP address.
///
/// This function extracts the client IP address from the request, checks if they have
/// available request quota remaining, and either allows the request to proceed or
/// returns a rate limit error response. It updates quota state atomically and handles
/// new clients by creating buckets with full quota.
///
/// # Examples
///
/// ```rust,no_run
/// use tako::plugins::rate_limiter::{retain, Config};
/// use tako::middleware::Next;
/// use tako::types::Request;
/// use std::sync::Arc;
/// use scc::HashMap as SccHashMap;
///
/// # async fn example() {
/// # let req = Request::builder().body(tako::body::TakoBody::empty()).unwrap();
/// # let next = Next {
/// # global_middlewares: Arc::default(),
/// # route_middlewares: Arc::default(),
/// # index: 0,
/// # endpoint: tako::handler::BoxHandler::new(|_req: tako::types::Request| async {
/// # tako::types::Response::new(tako::body::TakoBody::empty())
/// # }),
/// # };
/// let config = Config::default();
/// let store = Arc::new(SccHashMap::new());
/// let response = retain(req, next, config, store).await;
/// # }
/// ```
async