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
pub use generic::{
RateLimiter as GenericRateLimiter, RateLimiterConfig as GenericRateLimiterConfig,
};
use instant::Instant;
use libp2p_core::multiaddr::{Multiaddr, Protocol};
use libp2p_core::PeerId;
use std::net::IpAddr;
pub trait RateLimiter: Send {
fn try_next(&mut self, peer: PeerId, addr: &Multiaddr, now: Instant) -> bool;
}
pub fn new_per_peer(config: GenericRateLimiterConfig) -> Box<dyn RateLimiter> {
let mut limiter = GenericRateLimiter::new(config);
Box::new(move |peer_id, _addr: &Multiaddr, now| limiter.try_next(peer_id, now))
}
pub fn new_per_ip(config: GenericRateLimiterConfig) -> Box<dyn RateLimiter> {
let mut limiter = GenericRateLimiter::new(config);
Box::new(move |_peer_id, addr: &Multiaddr, now| {
multiaddr_to_ip(addr)
.map(|a| limiter.try_next(a, now))
.unwrap_or(true)
})
}
impl<T: FnMut(PeerId, &Multiaddr, Instant) -> bool + Send> RateLimiter for T {
fn try_next(&mut self, peer: PeerId, addr: &Multiaddr, now: Instant) -> bool {
self(peer, addr, now)
}
}
fn multiaddr_to_ip(addr: &Multiaddr) -> Option<IpAddr> {
addr.iter().find_map(|p| match p {
Protocol::Ip4(addr) => Some(addr.into()),
Protocol::Ip6(addr) => Some(addr.into()),
_ => None,
})
}
mod generic {
use instant::Instant;
use std::collections::{HashMap, VecDeque};
use std::convert::TryInto;
use std::hash::Hash;
use std::num::NonZeroU32;
use std::time::Duration;
pub struct RateLimiter<Id> {
limit: u32,
interval: Duration,
refill_schedule: VecDeque<(Instant, Id)>,
buckets: HashMap<Id, u32>,
}
#[derive(Debug, Clone, Copy)]
pub struct RateLimiterConfig {
pub limit: NonZeroU32,
pub interval: Duration,
}
impl<Id: Eq + PartialEq + Hash + Clone> RateLimiter<Id> {
pub(crate) fn new(config: RateLimiterConfig) -> Self {
assert!(!config.interval.is_zero());
Self {
limit: config.limit.into(),
interval: config.interval,
refill_schedule: Default::default(),
buckets: Default::default(),
}
}
pub(crate) fn try_next(&mut self, id: Id, now: Instant) -> bool {
self.refill(now);
match self.buckets.get_mut(&id) {
Some(balance) => match balance.checked_sub(1) {
Some(a) => {
*balance = a;
true
}
None => false,
},
None => {
self.buckets.insert(id.clone(), self.limit - 1);
self.refill_schedule.push_back((now, id));
true
}
}
}
fn refill(&mut self, now: Instant) {
loop {
match self.refill_schedule.get(0) {
Some((last_refill, _)) if now.duration_since(*last_refill) >= self.interval => {
}
_ => return,
};
let (last_refill, id) = self
.refill_schedule
.pop_front()
.expect("Queue not to be empty.");
let balance = self
.buckets
.get(&id)
.expect("Entry can only be removed via refill.");
let duration_since = now.duration_since(last_refill);
let new_tokens = duration_since
.as_micros()
.checked_div(self.interval.as_micros())
.and_then(|i| i.try_into().ok())
.unwrap_or(u32::MAX);
let new_balance = balance.checked_add(new_tokens).unwrap_or(u32::MAX);
if new_balance < self.limit {
self.buckets
.insert(id.clone(), new_balance)
.expect("To override value.");
self.refill_schedule.push_back((now, id));
} else {
self.buckets.remove(&id);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::{QuickCheck, TestResult};
use std::num::NonZeroU32;
#[test]
fn first() {
let id = 1;
let mut l = RateLimiter::new(RateLimiterConfig {
limit: NonZeroU32::new(10).unwrap(),
interval: Duration::from_secs(1),
});
assert!(l.try_next(id, Instant::now()));
}
#[test]
fn limits() {
let id = 1;
let now = Instant::now();
let mut l = RateLimiter::new(RateLimiterConfig {
limit: NonZeroU32::new(10).unwrap(),
interval: Duration::from_secs(1),
});
for _ in 0..10 {
assert!(l.try_next(id, now));
}
assert!(!l.try_next(id, now));
}
#[test]
fn refills() {
let id = 1;
let now = Instant::now();
let mut l = RateLimiter::new(RateLimiterConfig {
limit: NonZeroU32::new(10).unwrap(),
interval: Duration::from_secs(1),
});
for _ in 0..10 {
assert!(l.try_next(id, now));
}
assert!(!l.try_next(id, now));
let now = now + Duration::from_secs(1);
assert!(l.try_next(id, now));
assert!(!l.try_next(id, now));
let now = now + Duration::from_secs(10);
for _ in 0..10 {
assert!(l.try_next(id, now));
}
}
#[test]
fn move_at_half_interval_steps() {
let id = 1;
let now = Instant::now();
let mut l = RateLimiter::new(RateLimiterConfig {
limit: NonZeroU32::new(1).unwrap(),
interval: Duration::from_secs(2),
});
assert!(l.try_next(id, now));
assert!(!l.try_next(id, now));
let now = now + Duration::from_secs(1);
assert!(!l.try_next(id, now));
let now = now + Duration::from_secs(1);
assert!(l.try_next(id, now));
}
#[test]
fn garbage_collects() {
let now = Instant::now();
let mut l = RateLimiter::new(RateLimiterConfig {
limit: NonZeroU32::new(1).unwrap(),
interval: Duration::from_secs(1),
});
assert!(l.try_next(1, now));
let now = now + Duration::from_secs(1);
assert!(l.try_next(2, now));
assert_eq!(l.buckets.len(), 1);
assert_eq!(l.refill_schedule.len(), 1);
}
#[test]
fn quick_check() {
fn prop(
limit: NonZeroU32,
interval: Duration,
events: Vec<(u32, Duration)>,
) -> TestResult {
if interval.is_zero() {
return TestResult::discard();
}
let mut now = Instant::now();
let mut l = RateLimiter::new(RateLimiterConfig { limit, interval });
for (id, d) in events {
now = if let Some(now) = now.checked_add(d) {
now
} else {
return TestResult::discard();
};
l.try_next(id, now);
}
now = if let Some(now) = interval
.checked_mul(limit.into())
.and_then(|full_interval| now.checked_add(full_interval))
{
now
} else {
return TestResult::discard();
};
assert!(l.try_next(1, now));
assert_eq!(l.buckets.len(), 1);
assert_eq!(l.refill_schedule.len(), 1);
TestResult::passed()
}
QuickCheck::new().quickcheck(prop as fn(_, _, _) -> _)
}
}
}