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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use diem_infallible::{Mutex, RwLock};
use diem_logger::debug;
use diem_metrics::HistogramVec;
use std::{cmp::min, collections::HashMap, fmt::Debug, hash::Hash, sync::Arc, time::Instant};
use tokio::time::Duration;
pub type SharedBucket = Arc<Mutex<Bucket>>;
const ONE_SEC: Duration = Duration::from_secs(1);
pub struct TokenBucketRateLimiter<Key: Eq + Hash + Clone + Debug> {
label: &'static str,
log_info: String,
buckets: RwLock<HashMap<Key, SharedBucket>>,
new_bucket_start_percentage: u8,
default_bucket_size: usize,
default_fill_rate: usize,
enabled: bool,
metrics: Option<HistogramVec>,
}
impl<Key: Eq + Hash + Clone + Debug> TokenBucketRateLimiter<Key> {
pub fn new(
label: &'static str,
log_info: String,
new_bucket_start_percentage: u8,
default_bucket_size: usize,
default_fill_rate: usize,
metrics: Option<HistogramVec>,
) -> Self {
assert!(new_bucket_start_percentage <= 100);
assert!(default_bucket_size > 0);
assert!(default_fill_rate > 0);
Self {
label,
log_info,
buckets: RwLock::new(HashMap::new()),
new_bucket_start_percentage,
default_bucket_size,
default_fill_rate,
enabled: true,
metrics,
}
}
pub fn test(default_bucket_size: usize, default_fill_rate: usize) -> Self {
Self::new(
"test",
"test".to_string(),
100,
default_bucket_size,
default_fill_rate,
None,
)
}
pub fn open(label: &'static str) -> Self {
Self {
label,
log_info: String::new(),
buckets: RwLock::new(HashMap::new()),
new_bucket_start_percentage: 100,
default_bucket_size: std::usize::MAX,
default_fill_rate: std::usize::MAX,
enabled: false,
metrics: None,
}
}
pub fn bucket(&self, key: Key) -> SharedBucket {
self.bucket_inner(key, |label, log_info, key, initial, size, rate, metrics| {
Arc::new(Mutex::new(if self.enabled {
Bucket::new(label, log_info, key, initial, size, rate, metrics)
} else {
Bucket::open(label)
}))
})
}
fn bucket_inner<
F: FnOnce(String, String, String, usize, usize, usize, Option<HistogramVec>) -> SharedBucket,
>(
&self,
key: Key,
bucket_create: F,
) -> SharedBucket {
let maybe_bucket = { self.buckets.read().get(&key).cloned() };
if let Some(bucket) = maybe_bucket {
bucket
} else {
let size = self.default_bucket_size;
let rate = self.default_fill_rate;
self.buckets
.write()
.entry(key.clone())
.or_insert_with(|| {
bucket_create(
self.label.to_string(),
self.log_info.clone(),
format!("{:?}", key),
size.saturating_mul(self.new_bucket_start_percentage as usize) / 100,
size,
rate,
self.metrics.clone(),
)
})
.clone()
}
}
pub fn try_garbage_collect_key(&self, key: &Key) -> bool {
let mut buckets = self.buckets.write();
let remove = buckets
.get(key)
.map_or(false, |bucket| Arc::strong_count(bucket) <= 1);
if remove {
buckets.remove(key);
}
remove
}
}
#[derive(Debug)]
pub struct Bucket {
label: String,
log_info: String,
key: String,
tokens: usize,
size: usize,
rate: usize,
last_refresh_time: Instant,
enabled: bool,
allowed_in_period: usize,
throttled_in_period: usize,
metrics: Option<HistogramVec>,
}
impl Bucket {
pub fn new(
label: String,
log_info: String,
key: String,
initial: usize,
size: usize,
rate: usize,
metrics: Option<HistogramVec>,
) -> Self {
assert!(
size >= rate,
"Bucket size must be greater than or equal to fill rate"
);
Self {
label,
log_info,
key,
tokens: initial,
size,
rate,
last_refresh_time: Instant::now(),
enabled: true,
allowed_in_period: 0,
throttled_in_period: 0,
metrics,
}
}
pub fn open(label: String) -> Self {
Self {
label,
log_info: String::new(),
key: String::new(),
tokens: std::usize::MAX,
size: std::usize::MAX,
rate: std::usize::MAX,
last_refresh_time: Instant::now(),
enabled: false,
allowed_in_period: 0,
throttled_in_period: 0,
metrics: None,
}
}
pub(crate) fn refill(&mut self) {
let num_intervals = self.last_refresh_time.elapsed().as_secs();
if num_intervals > 0 {
if self.allowed_in_period > 0 || self.throttled_in_period > 0 {
debug!(
throttle_label = self.label,
throttle_log_info = self.log_info,
throttle_key = self.key,
num_allowed_in_period = self.allowed_in_period,
num_throttled_in_period = self.throttled_in_period,
"{}-{}-{}={}/{}",
self.label,
self.log_info,
self.key,
self.allowed_in_period,
self.allowed_in_period
.saturating_add(self.throttled_in_period),
);
}
if let Some(metrics) = self.metrics.as_ref() {
metrics
.with_label_values(&[self.label.as_str(), "allowed"])
.observe(self.allowed_in_period as f64);
metrics
.with_label_values(&[self.label.as_str(), "throttled"])
.observe(self.throttled_in_period as f64);
}
self.allowed_in_period = 0;
self.throttled_in_period = 0;
self.add_tokens((num_intervals as usize).saturating_mul(self.rate));
self.last_refresh_time += Duration::from_secs(num_intervals);
}
}
pub fn acquire_all_tokens(&mut self, requested: usize) -> Result<(), Option<Instant>> {
if !self.enabled || requested == 0 {
return Ok(());
}
self.refill();
if self.tokens >= requested {
self.deduct_tokens(requested);
self.allowed_in_period = self.allowed_in_period.saturating_add(requested);
Ok(())
} else {
self.throttled_in_period = self.throttled_in_period.saturating_add(requested);
Err(self.time_of_tokens_needed(requested))
}
}
pub fn acquire_tokens(&mut self, requested: usize) -> Result<usize, Instant> {
if !self.enabled || requested == 0 {
return Ok(requested);
}
self.refill();
let allowed = self.deduct_tokens(requested);
if allowed > 0 {
self.allowed_in_period = self.allowed_in_period.saturating_add(allowed);
Ok(allowed)
} else {
self.throttled_in_period = self.throttled_in_period.saturating_add(requested);
Err(self.time_of_next_refill())
}
}
fn deduct_tokens(&mut self, requested: usize) -> usize {
let tokens_allowed = min(self.tokens, requested);
self.tokens = self.tokens.saturating_sub(requested);
tokens_allowed
}
pub fn time_of_next_refill(&self) -> Instant {
self.last_refresh_time + ONE_SEC
}
pub fn time_of_tokens_needed(&self, requested: usize) -> Option<Instant> {
if !self.enabled {
Some(Instant::now())
} else if self.size < requested {
None
} else {
let tokens_needed = requested.saturating_sub(self.tokens);
let intervals = (tokens_needed as f64 / self.rate as f64).ceil() as u32;
Some(self.last_refresh_time + (ONE_SEC * intervals))
}
}
fn add_tokens(&mut self, new_tokens: usize) {
self.tokens = min(self.size, self.tokens.saturating_add(new_tokens));
}
pub fn return_tokens(&mut self, new_tokens: usize) {
self.allowed_in_period = self.allowed_in_period.saturating_sub(new_tokens);
self.add_tokens(new_tokens);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{sync::MutexGuard, thread::sleep};
use tokio::time::Duration;
fn assert_acquire(rate_limiter: &mut MutexGuard<Bucket>, num_allowed: usize) {
assert_eq!(
num_allowed,
rate_limiter
.acquire_tokens(num_allowed)
.expect("Expected tokens")
);
rate_limiter
.acquire_tokens(1)
.expect_err("Expected time to wait");
}
fn assert_num_keys(rate_limiters: &TokenBucketRateLimiter<&str>, num_keys: usize) {
assert_eq!(num_keys, rate_limiters.buckets.read().len())
}
#[test]
fn test_rate_limiting() {
let bucket_size = 5;
let bucket_rate = 1;
let key = "Key";
let rate_limiter = TokenBucketRateLimiter::test(bucket_size, bucket_rate);
let bucket_arc = rate_limiter.bucket(key);
let mut bucket = bucket_arc.lock();
assert_acquire(&mut bucket, bucket_size);
bucket.return_tokens(2);
assert_acquire(&mut bucket, 2);
bucket.return_tokens(bucket_size + 1);
assert_acquire(&mut bucket, bucket_size);
}
#[test]
fn test_message_rate_limiting() {
let bucket_size = 5;
let bucket_rate = 3;
let key = "Key";
let rate_limiter = TokenBucketRateLimiter::test(bucket_size, bucket_rate);
let bucket_arc = rate_limiter.bucket(key);
let mut bucket = bucket_arc.lock();
let result = bucket.acquire_all_tokens(bucket_size + 1);
assert!(result.expect_err("Should not give tokens").is_none());
let result = bucket.acquire_all_tokens(bucket_size);
result.expect("Should be successful");
let result = bucket.acquire_all_tokens(bucket_size);
let wait_time = result
.expect_err("Should not succeed, but will in future")
.expect("Should have a time it succeeds");
sleep(wait_time.duration_since(Instant::now()));
let result = bucket.acquire_all_tokens(bucket_size);
result.expect("Should be successful");
}
#[test]
fn test_refill() {
let bucket_size = 5;
let bucket_rate = 1;
let key = "Key";
let rate_limiter = TokenBucketRateLimiter::test(bucket_size, bucket_rate);
let bucket_arc = rate_limiter.bucket(key);
let mut bucket = bucket_arc.lock();
assert_acquire(&mut bucket, bucket_size);
sleep(bucket.time_of_next_refill().duration_since(Instant::now()));
bucket.refill();
let num_tokens = bucket.tokens;
assert!(num_tokens >= bucket_rate);
assert_acquire(&mut bucket, num_tokens);
sleep(bucket.time_of_next_refill().duration_since(Instant::now()));
bucket.acquire_tokens(1).unwrap();
}
#[test]
fn test_time_checks() {
let bucket_size = 5;
let bucket_rate = 1;
let rate_limiter = TokenBucketRateLimiter::test(bucket_size, bucket_rate);
let bucket_arc = rate_limiter.bucket("Key");
let mut bucket = bucket_arc.lock();
assert!(bucket.time_of_next_refill() < Instant::now() + Duration::from_secs(1));
assert!(
bucket
.time_of_tokens_needed(bucket_size)
.expect("Should have a duration")
<= Instant::now()
);
assert_acquire(&mut bucket, bucket_size);
assert!(
bucket
.time_of_tokens_needed(bucket_size)
.expect("Should have a duration")
> Instant::now() + Duration::from_secs(bucket_size as u64 - 1)
);
assert!(bucket.time_of_tokens_needed(bucket_size + 1).is_none());
}
#[test]
fn test_bucket_creation() {
let key = "key";
let rate_limiter = TokenBucketRateLimiter::test(1, 1);
assert_num_keys(&rate_limiter, 0);
let bucket1 = rate_limiter.bucket(key);
let bucket2 = rate_limiter.bucket(key);
assert_eq!(Arc::as_ptr(&bucket1), Arc::as_ptr(&bucket2));
assert_eq!(3, Arc::strong_count(&bucket1));
}
#[test]
fn test_garbage_collection() {
let key_to_keep = "don't gc";
let key_to_gc = "do gc";
let rate_limiter = TokenBucketRateLimiter::test(1, 1);
assert_num_keys(&rate_limiter, 0);
let _bucket_arc = rate_limiter.bucket(key_to_keep);
assert_num_keys(&rate_limiter, 1);
{
let _bucket_arc = rate_limiter.bucket(key_to_gc);
}
assert_num_keys(&rate_limiter, 2);
assert!(rate_limiter.try_garbage_collect_key(&key_to_gc));
assert_num_keys(&rate_limiter, 1);
assert!(!rate_limiter.try_garbage_collect_key(&key_to_keep));
assert_num_keys(&rate_limiter, 1);
}
}