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
#[derive(Clone,Debug)]
pub struct Config {
rate: std::time::Duration,
burst: u32,
}
#[derive(Debug,PartialEq)]
#[non_exhaustive]
pub enum Denied {
TooEarly(TooEarly),
TooBig,
}
impl std::fmt::Display for Denied {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Denied::TooEarly(TooEarly{next}) => write!(f, "Try again after {:?}", next),
Denied::TooBig => f.write_str("Request cost is larger than bucket size."),
}
}
}
impl std::error::Error for Denied {}
#[derive(Debug,PartialEq)]
pub struct TooEarly {
next: std::time::SystemTime,
}
impl TooEarly {
pub fn available_at(&self) -> std::time::SystemTime {
self.next
}
}
impl Config {
pub const fn new(rate: std::time::Duration, burst: u32) -> Self {
Config{rate, burst}
}
}
#[derive(Clone,Default,Debug)]
#[cfg_attr(feature="use_serde", derive(serde_derive::Deserialize,serde_derive::Serialize))]
pub struct Tracker {
#[cfg_attr(feature="use_serde", serde(rename="l"))]
last: Option<std::time::SystemTime>,
}
impl Tracker {
pub fn empty() -> Self {
Self::new_at(std::time::SystemTime::now())
}
pub fn full() -> Self {
Self::default()
}
pub fn new_at(now: std::time::SystemTime) -> Self {
Tracker{
last: Some(now),
}
}
pub fn capacity(&self,
config: &Config,
) -> u32 {
self.capacity_at(config, std::time::SystemTime::now())
}
pub fn capacity_at(&self,
config: &Config,
now: std::time::SystemTime,
) -> u32 {
match self.last {
Some(last) => {
match now.duration_since(last) {
Ok(elapsed) => {
let periods = elapsed.as_nanos() / config.rate.as_nanos();
let periods = u32::try_from(periods)
.unwrap_or(u32::max_value());
periods.min(config.burst)
}
Err(_) => 0,
}
}
None => config.burst,
}
}
pub fn acquire(&mut self,
config: &Config,
count: u32,
) -> Result<(), Denied> {
self.acquire_at(config, count, std::time::SystemTime::now())
}
pub fn acquire_at(&mut self,
config: &Config,
count: u32,
now: std::time::SystemTime,
) -> Result<(), Denied> {
if count > config.burst {
return Err(Denied::TooBig)
}
let required = config.rate * count;
let max_last = now - (config.rate * config.burst) + required;
if let Some(ref mut last) = self.last {
let available_at = *last + required;
if available_at > now {
return Err(Denied::TooEarly(TooEarly{next: available_at}))
}
*last = available_at.max(max_last);
} else {
self.last = Some(max_last);
}
Ok(())
}
pub fn simplify(&mut self,
config: &Config,
) -> bool {
self.simplify_at(config, std::time::SystemTime::now())
}
pub fn simplify_at(&mut self,
config: &Config,
now: std::time::SystemTime,
) -> bool {
if let Some(last) = self.last {
if let Ok(elapsed) = now.duration_since(last) {
let periods = elapsed.as_nanos() / config.rate.as_nanos();
if periods >= config.burst as u128 {
self.last = None;
}
}
}
self.last.is_none()
}
}
#[test]
fn test_rate_limit_fresh() {
let cfg = Config::new(std::time::Duration::from_secs(1), 10);
assert!(Tracker::default().simplify_at(&cfg, std::time::UNIX_EPOCH));
assert_eq!(
Tracker::default().acquire(&cfg, 11),
Err(Denied::TooBig));
let mut t = Tracker::default();
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 10);
assert_eq!(t.acquire_at(&cfg, 1, std::time::UNIX_EPOCH), Ok(()));
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 9);
let mut t = Tracker::default();
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 10);
assert_eq!(t.acquire_at(&cfg, 8, std::time::UNIX_EPOCH), Ok(()));
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 2);
}
#[test]
fn test_rate_limit_active_capacity() {
let cfg = Config::new(std::time::Duration::from_secs(1), 10);
let mut t = Tracker::default();
assert_eq!(t.acquire_at(&cfg, 4, std::time::UNIX_EPOCH), Ok(()));
assert!(!t.simplify_at(&cfg, std::time::UNIX_EPOCH));
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 6);
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(1)), 7);
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(2)), 8);
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(3)), 9);
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(4)), 10);
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(5)), 10);
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(50)), 10);
}
#[test]
fn test_rate_limit_active_acquire() {
let cfg = Config::new(std::time::Duration::from_secs(1), 10);
let mut base = Tracker::default();
assert_eq!(base.acquire_at(&cfg, 4, std::time::UNIX_EPOCH), Ok(()));
assert_eq!(base.capacity_at(&cfg, std::time::UNIX_EPOCH), 6);
let base = base;
let mut t = base.clone();
assert_eq!(
t.acquire_at(&cfg, 2, std::time::UNIX_EPOCH),
Ok(()));
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 4);
let mut t = base.clone();
assert_eq!(
t.acquire_at(&cfg, 6, std::time::UNIX_EPOCH),
Ok(()));
assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 0);
let mut t = base.clone();
assert_eq!(
t.acquire_at(&cfg, 7, std::time::UNIX_EPOCH),
Err(Denied::TooEarly(TooEarly{
next: std::time::UNIX_EPOCH + std::time::Duration::from_secs(1),
})));
assert_eq!(
t.acquire_at(&cfg, 7, std::time::UNIX_EPOCH + std::time::Duration::from_secs(1)),
Ok(()));
let mut t = base.clone();
assert_eq!(
t.acquire_at(&cfg, 10, std::time::UNIX_EPOCH),
Err(Denied::TooEarly(TooEarly{
next: std::time::UNIX_EPOCH + std::time::Duration::from_secs(4),
})));
assert_eq!(
t.acquire_at(&cfg, 10, std::time::UNIX_EPOCH + std::time::Duration::from_secs(4)),
Ok(()));
}