-
-
Notifications
You must be signed in to change notification settings - Fork 212
/
lib.rs
410 lines (357 loc) · 13.8 KB
/
lib.rs
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
//! Rate limiter middleware for Salvo.
//!
//! Rate Limiter middleware is used to limiting the amount of requests to the server
//! from a particular IP or id within a time period.
//!
//! [`RateIssuer`] is used to issue a key to request, your can define your custom `RateIssuer`.
//! If you want just identify user by IP address, you can use [`RemoteIpIssuer`].
//!
//! [`QuotaGetter`] is used to get quota for every key.
//!
//! [`RateGuard`] is strategy to verify is the request exceeded quota.
//!
//! Read more: <https://salvo.rs>
#![doc(html_favicon_url = "https://salvo.rs/favicon-32x32.png")]
#![doc(html_logo_url = "https://salvo.rs/images/logo.svg")]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::borrow::Borrow;
use std::error::Error as StdError;
use std::future::Future;
use std::hash::Hash;
use salvo_core::conn::SocketAddr;
use salvo_core::handler::{none_skipper, Skipper};
use salvo_core::http::{HeaderValue, Request, Response, StatusCode, StatusError};
use salvo_core::{async_trait, Depot, FlowCtrl, Handler};
mod quota;
pub use quota::{BasicQuota, CelledQuota, QuotaGetter};
#[macro_use]
mod cfg;
cfg_feature! {
#![feature = "moka-store"]
mod moka_store;
pub use moka_store::MokaStore;
}
cfg_feature! {
#![feature = "fixed-guard"]
mod fixed_guard;
pub use fixed_guard::FixedGuard;
}
cfg_feature! {
#![feature = "sliding-guard"]
mod sliding_guard;
pub use sliding_guard::SlidingGuard;
}
/// Issuer is used to identify every request.
pub trait RateIssuer: Send + Sync + 'static {
/// The key is used to identify the rate limit.
type Key: Hash + Eq + Send + Sync + 'static;
/// Issue a new key for the request.
fn issue(&self, req: &mut Request, depot: &Depot) -> impl Future<Output = Option<Self::Key>> + Send;
}
impl<F, K> RateIssuer for F
where
F: Fn(&mut Request, &Depot) -> Option<K> + Send + Sync + 'static,
K: Hash + Eq + Send + Sync + 'static,
{
type Key = K;
async fn issue(&self, req: &mut Request, depot: &Depot) -> Option<Self::Key> {
(self)(req, depot)
}
}
/// Identify user by IP address.
pub struct RemoteIpIssuer;
impl RateIssuer for RemoteIpIssuer {
type Key = String;
async fn issue(&self, req: &mut Request, _depot: &Depot) -> Option<Self::Key> {
match req.remote_addr() {
SocketAddr::IPv4(addr) => Some(addr.ip().to_string()),
SocketAddr::IPv6(addr) => Some(addr.ip().to_string()),
_ => None,
}
}
}
/// `RateGuard` is strategy to verify is the request exceeded quota
pub trait RateGuard: Clone + Send + Sync + 'static {
/// The quota for the rate limit.
type Quota: Clone + Send + Sync + 'static;
/// Verify is current request exceed the quota.
fn verify(&mut self, quota: &Self::Quota) -> impl Future<Output = bool> + Send;
/// Returns the remaining quota.
fn remaining(&self, quota: &Self::Quota) -> impl Future<Output = usize> + Send;
/// Returns the reset time.
fn reset(&self, quota: &Self::Quota) -> impl Future<Output = i64> + Send;
/// Returns the limit.
fn limit(&self, quota: &Self::Quota) -> impl Future<Output = usize> + Send;
}
/// `RateStore` is used to store rate limit data.
pub trait RateStore: Send + Sync + 'static {
/// Error type for RateStore.
type Error: StdError;
/// Key
type Key: Hash + Eq + Send + Clone + 'static;
/// Saved guard.
type Guard;
/// Get the guard from the store.
fn load_guard<Q>(
&self,
key: &Q,
refer: &Self::Guard,
) -> impl Future<Output = Result<Self::Guard, Self::Error>> + Send
where
Self::Key: Borrow<Q>,
Q: Hash + Eq + Sync;
/// Save the guard from the store.
fn save_guard(&self, key: Self::Key, guard: Self::Guard) -> impl Future<Output = Result<(), Self::Error>> + Send;
}
/// `RateLimiter` is the main struct to used limit user request.
pub struct RateLimiter<G, S, I, Q> {
guard: G,
store: S,
issuer: I,
quota_getter: Q,
add_headers: bool,
skipper: Box<dyn Skipper>,
}
impl<G: RateGuard, S: RateStore, I: RateIssuer, P: QuotaGetter<I::Key>> RateLimiter<G, S, I, P> {
/// Create a new `RateLimiter`
#[inline]
pub fn new(guard: G, store: S, issuer: I, quota_getter: P) -> Self {
Self {
guard,
store,
issuer,
quota_getter,
add_headers: false,
skipper: Box::new(none_skipper),
}
}
/// Sets skipper and returns new `RateLimiter`.
#[inline]
pub fn with_skipper(mut self, skipper: impl Skipper) -> Self {
self.skipper = Box::new(skipper);
self
}
/// Sets `add_headers` and returns new `RateLimiter`.
/// If `add_headers` is true, the rate limit headers will be added to the response.
#[inline]
pub fn add_headers(mut self, add_headers: bool) -> Self {
self.add_headers = add_headers;
self
}
}
#[async_trait]
impl<G, S, I, P> Handler for RateLimiter<G, S, I, P>
where
G: RateGuard<Quota = P::Quota>,
S: RateStore<Key = I::Key, Guard = G>,
P: QuotaGetter<I::Key>,
I: RateIssuer,
{
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
if self.skipper.skipped(req, depot) {
return;
}
let key = match self.issuer.issue(req, depot).await {
Some(key) => key,
None => {
res.render(StatusError::bad_request().brief("Invalid identifier."));
ctrl.skip_rest();
return;
}
};
let quota = match self.quota_getter.get(&key).await {
Ok(quota) => quota,
Err(e) => {
tracing::error!(error = ?e, "RateLimiter error: {}", e);
res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
ctrl.skip_rest();
return;
}
};
let mut guard = match self.store.load_guard(&key, &self.guard).await {
Ok(guard) => guard,
Err(e) => {
tracing::error!(error = ?e, "RateLimiter error: {}", e);
res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
ctrl.skip_rest();
return;
}
};
let verified = guard.verify("a).await;
if self.add_headers {
res.headers_mut().insert(
"X-RateLimit-Limit",
HeaderValue::from_str(&guard.limit("a).await.to_string()).expect("Invalid header value"),
);
res.headers_mut().insert(
"X-RateLimit-Remaining",
HeaderValue::from_str(&(guard.remaining("a).await).to_string()).expect("Invalid header value"),
);
res.headers_mut().insert(
"X-RateLimit-Reset",
HeaderValue::from_str(&guard.reset("a).await.to_string()).expect("Invalid header value"),
);
}
if !verified {
res.status_code(StatusCode::TOO_MANY_REQUESTS);
ctrl.skip_rest();
}
if let Err(e) = self.store.save_guard(key, guard).await {
tracing::error!(error = ?e, "RateLimiter save guard failed");
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::LazyLock;
use salvo_core::prelude::*;
use salvo_core::test::{ResponseExt, TestClient};
use salvo_core::Error;
use super::*;
struct UserIssuer;
impl RateIssuer for UserIssuer {
type Key = String;
async fn issue(&self, req: &mut Request, _depot: &Depot) -> Option<Self::Key> {
req.query::<Self::Key>("user")
}
}
#[handler]
async fn limited() -> &'static str {
"Limited page"
}
#[tokio::test]
async fn test_fixed_dynmaic_quota() {
static USER_QUOTAS: LazyLock<HashMap<String, BasicQuota>> = LazyLock::new(|| {
let mut map = HashMap::new();
map.insert("user1".into(), BasicQuota::per_second(1));
map.insert("user2".into(), BasicQuota::set_seconds(1, 5));
map
});
struct CustomQuotaGetter;
impl QuotaGetter<String> for CustomQuotaGetter {
type Quota = BasicQuota;
type Error = Error;
async fn get<Q>(&self, key: &Q) -> Result<Self::Quota, Self::Error>
where
String: Borrow<Q>,
Q: Hash + Eq + Sync,
{
USER_QUOTAS
.get(key)
.cloned()
.ok_or_else(|| Error::other("user not found"))
}
}
let limiter = RateLimiter::new(
FixedGuard::default(),
MokaStore::default(),
UserIssuer,
CustomQuotaGetter,
);
let router = Router::new().push(Router::with_path("limited").hoop(limiter).get(limited));
let service = Service::new(router);
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user1")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
let respone = TestClient::get("http://127.0.0.1:5800/limited?user=user1")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::TOO_MANY_REQUESTS));
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user1")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
let respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::TOO_MANY_REQUESTS));
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
let respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::TOO_MANY_REQUESTS));
tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
}
#[tokio::test]
async fn test_sliding_dynmaic_quota() {
static USER_QUOTAS: LazyLock<HashMap<String, CelledQuota>> = LazyLock::new(|| {
let mut map = HashMap::new();
map.insert("user1".into(), CelledQuota::per_second(1, 1));
map.insert("user2".into(), CelledQuota::set_seconds(1, 1, 5));
map
});
struct CustomQuotaGetter;
impl QuotaGetter<String> for CustomQuotaGetter {
type Quota = CelledQuota;
type Error = Error;
async fn get<Q>(&self, key: &Q) -> Result<Self::Quota, Self::Error>
where
String: Borrow<Q>,
Q: Hash + Eq + Sync,
{
USER_QUOTAS
.get(key)
.cloned()
.ok_or_else(|| Error::other("user not found"))
}
}
let limiter = RateLimiter::new(
SlidingGuard::default(),
MokaStore::default(),
UserIssuer,
CustomQuotaGetter,
);
let router = Router::new().push(Router::with_path("limited").hoop(limiter).get(limited));
let service = Service::new(router);
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user1")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
let respone = TestClient::get("http://127.0.0.1:5800/limited?user=user1")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::TOO_MANY_REQUESTS));
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user1")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
let respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::TOO_MANY_REQUESTS));
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
let respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::TOO_MANY_REQUESTS));
tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
let mut respone = TestClient::get("http://127.0.0.1:5800/limited?user=user2")
.send(&service)
.await;
assert_eq!(respone.status_code, Some(StatusCode::OK));
assert_eq!(respone.take_string().await.unwrap(), "Limited page");
}
}