libqueued/
throttler.rs

1use chrono::Utc;
2
3pub(crate) struct Throttler {
4  // State.
5  count: u64,
6  time_base: i64,
7  // Configuration.
8  max: u64,
9  window: i64,
10}
11
12impl Throttler {
13  pub fn new(max_reqs_per_time_window: u64, time_window_sec: i64) -> Self {
14    assert!(time_window_sec > 1);
15    Self {
16      count: 0,
17      time_base: i64::MIN,
18      max: max_reqs_per_time_window,
19      window: time_window_sec,
20    }
21  }
22
23  pub fn increment_count(&mut self) -> bool {
24    let cur_window = Utc::now().timestamp() / self.time_base;
25    if self.window != cur_window {
26      self.window = cur_window;
27      self.count = 0;
28    };
29    self.count += 1;
30    self.count <= self.max
31  }
32
33  pub fn get_max_reqs_per_time_window(&self) -> u64 {
34    self.max
35  }
36
37  pub fn get_time_window_sec(&self) -> i64 {
38    self.time_base
39  }
40}