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
#![deny(unsafe_code)]
#![deny(warnings)]
#![deny(clippy::all)]
use governor::clock::{Clock, DefaultClock};
pub use governor::Quota;
use lazy_static::lazy_static;
use registry::Registry;
pub use rocket::http::Method;
use rocket::{
http::Status,
request::{FromRequest, Outcome},
response::{self, Responder},
Request, Response,
};
use std::marker::PhantomData;
pub use std::num::NonZeroU32;
mod registry;
#[rocket::async_trait]
pub trait RocketGovernable<'r>: FromRequest<'r> + Default {
#[must_use]
fn quota(method: Method, route_name: &str) -> Quota;
#[inline(always)]
fn rocket_governor_catcher<'c>(request: &'c Request) -> &'c LimitError {
let cached_res: &Result<(), LimitError> = request.local_cache(|| Err(LimitError::Error));
if let Err(limit_err) = cached_res {
limit_err
} else {
&LimitError::Error
}
}
#[inline]
fn nonzero(n: u32) -> NonZeroU32 {
NonZeroU32::new(n).unwrap_or_else(|| NonZeroU32::new(1u32).unwrap())
}
}
lazy_static! {
static ref CLOCK: DefaultClock = DefaultClock::default();
}
const HEADER_X_RATELIMIT_ERROR: &'static str = "X-RateLimit-Error";
const HEADER_X_RATELIMIT_RESET: &'static str = "X-RateLimit-Reset";
pub struct RocketGovernorMacroUtil<'r, T: RocketGovernable<'r>> {
_phantom: &'r PhantomData<T>,
}
impl<'r, T> RocketGovernorMacroUtil<'r, T>
where
T: RocketGovernable<'r>,
{
#[inline(always)]
pub fn handle_from_request(request: &'r Request) -> Outcome<T, LimitError> {
let res = request.local_cache(|| {
if let Some(route) = request.route() {
if let Some(route_name) = &route.name {
let limiter = Registry::get_or_insert(
route.method,
route_name,
T::quota(route.method, route_name),
);
if let Some(client_ip) = request.client_ip() {
if let Err(notuntil) = limiter.check_key(&client_ip) {
let wait_time = notuntil.wait_time_from(CLOCK.now()).as_secs();
Err(LimitError::GovernedRequest(wait_time))
} else {
Ok(())
}
} else {
Err(LimitError::MissingClientIpAddr)
}
} else {
Err(LimitError::MissingRouteName)
}
} else {
Err(LimitError::MissingRoute)
}
});
if let Err(e) = res {
let e = e.clone();
match e {
LimitError::GovernedRequest(_) => Outcome::Failure((Status::TooManyRequests, e)),
_ => Outcome::Failure((Status::BadRequest, e)),
}
} else {
Outcome::Success(T::default())
}
}
}
#[derive(Clone, Debug)]
pub enum LimitError {
Error,
GovernedRequest(u64),
MissingClientIpAddr,
MissingRoute,
MissingRouteName,
}
impl<'r, 'o: 'r> Responder<'r, 'o> for &LimitError {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
let mut builder = Response::build();
let mut builder = builder.status(Status::TooManyRequests);
builder = match self {
LimitError::Error => builder.raw_header(HEADER_X_RATELIMIT_ERROR, "rate limiter error"),
LimitError::GovernedRequest(wait_time) => {
builder.raw_header(HEADER_X_RATELIMIT_RESET, wait_time.to_string())
}
LimitError::MissingClientIpAddr => builder.raw_header(
HEADER_X_RATELIMIT_ERROR,
"application no retrieving client ip",
),
LimitError::MissingRoute => {
builder.raw_header(HEADER_X_RATELIMIT_ERROR, "routing failure")
}
LimitError::MissingRouteName => {
builder.raw_header(HEADER_X_RATELIMIT_ERROR, "route without name")
}
};
builder.ok()
}
}