Skip to main content

ratelimit_rs/
lib.rs

1use std::thread;
2use std::time::{Duration, Instant};
3
4const ZERO_TIME: Duration = Duration::from_secs(0);
5
6/// `Bucket` represents a token bucket that fills at a predetermined rate. Methods on
7/// `Bucket` may be called concurrently.
8#[derive(Debug)]
9pub struct Bucket {
10    /// capacity holds the overall capacity of the bucket.
11    pub capacity: u64,
12    /// availableTokens holds the number of available
13    /// tokens as of the associated latestTick.
14    /// It will be negative when there are consumers
15    /// waiting for tokens.
16    pub available_tokens: u64,
17    /// quantum holds how many tokens are added on
18    /// each tick.
19    pub quantum: u64,
20    /// fillInterval holds the interval between each tick.
21    pub fill_interval: Duration,
22    /// latestTick holds the latest tick for which
23    /// we know the number of tokens in the bucket.
24    pub latest_tick: Instant,
25}
26
27impl Bucket {
28    pub fn new(
29        fill_interval: Duration,
30        capacity: u64,
31        quantum: u64,
32        available_tokens: u64,
33    ) -> Self {
34        Self {
35            capacity,
36            available_tokens,
37            latest_tick: Instant::now(),
38            quantum,
39            fill_interval,
40        }
41    }
42
43    fn current_tick(&self) -> f64 {
44        (self.latest_tick.elapsed().as_millis() as f64) / (self.fill_interval.as_millis() as f64)
45    }
46
47    fn adjust_available_tokens(&mut self, tick: f64) {
48        self.latest_tick = Instant::now();
49        if self.available_tokens >= self.capacity {
50            self.available_tokens = self.capacity;
51            return;
52        }
53        self.available_tokens += (tick * self.quantum as f64) as u64;
54        if self.available_tokens >= self.capacity {
55            self.available_tokens = self.capacity;
56        }
57    }
58
59    /// TakeAvailable takes up to count immediately available tokens from the bucket. It
60    /// returns the number of tokens removed, or zero if there are no available tokens.
61    /// It does not block.
62    pub fn take_available(&mut self, count: u64) -> u64 {
63        if count == 0 {
64            return 0;
65        }
66        self.adjust_available_tokens(self.current_tick());
67        if self.available_tokens == 0 {
68            return 0;
69        }
70        let mut tokens = count;
71        if count > self.available_tokens {
72            tokens = self.available_tokens
73        }
74        self.available_tokens -= tokens;
75        tokens
76    }
77
78    /// TakeOneAvailable takes up a token from the bucket.
79    pub fn take_one_available(&mut self) -> u64 {
80        self.take_available(1)
81    }
82
83    // take is the internal version of Take - it takes the current time as
84    // an argument to enable easy testing.
85    fn take(&mut self, count: u64, max_wait: Duration) -> (Duration, bool) {
86        if count == 0 {
87            return (ZERO_TIME, true);
88        }
89        let tick = self.current_tick();
90        self.adjust_available_tokens(tick);
91        let avail = (self.available_tokens as i64) - (count as i64);
92        if avail >= 0 {
93            self.available_tokens = avail as u64;
94            return (ZERO_TIME, true);
95        }
96        let end_tick = (-avail as f64) / self.quantum as f64;
97        let wait_time = (self.fill_interval.as_millis() as f64) * end_tick;
98        if wait_time > max_wait.as_millis() as f64 {
99            return (ZERO_TIME, false);
100        }
101        (Duration::from_millis(wait_time as u64), true)
102    }
103
104    /// TakeMaxDuration is take, except that it will only take tokens from the
105    /// bucket if the wait time for the tokens is no greater than maxWait.
106
107    /// If it would take longer than maxWait for the tokens to become available, it does
108    /// nothing and reports false, otherwise it returns the time that the caller should
109    /// wait until the tokens are actually available, and reports true.
110    pub fn take_max_duration(&mut self, count: u64, max_wait: Duration) -> (Duration, bool) {
111        self.take(count, max_wait)
112    }
113
114    /// WaitMaxDuration is like Wait except that it will only take tokens from the
115    /// bucket if it needs to wait for no greater than maxWait. It reports whether any
116    /// tokens have been removed from the bucket If no tokens have been removed, it
117    /// returns immediately.
118    pub fn wait_max_duration(&mut self, count: u64, max_wait: Duration) -> bool {
119        let (sleep_time, ok) = self.take(count, max_wait);
120        if sleep_time.as_millis() > 0 {
121            thread::sleep(sleep_time);
122        }
123        ok
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use crate::Bucket;
130    use std::thread;
131    use std::time::Duration;
132    #[test]
133    fn take_avaliable_works() {
134        let mut bucket = Bucket::new(Duration::from_secs(3), 100, 100, 100);
135        let count = bucket.take_available(200);
136        assert_eq!(count, 100);
137        let count = bucket.take_available(100);
138        assert_eq!(count, 0);
139        thread::sleep(Duration::from_secs(3));
140        let count = bucket.take_available(100);
141        assert_eq!(count, 100);
142        thread::sleep(Duration::from_secs(2));
143        let count = bucket.take_available(100);
144        assert_eq!(66, count);
145        thread::sleep(Duration::from_secs(3));
146        let count = bucket.take_available(200);
147        assert_eq!(100, count);
148    }
149
150    #[test]
151    fn take_max_duration_works() {
152        let mut bucket = Bucket::new(Duration::from_secs(3), 100, 100, 100);
153        bucket.take_available(100);
154        let (time, ok) = bucket.take_max_duration(100, Duration::from_secs(4));
155        assert_eq!(time.as_millis(), 3000);
156        assert_eq!(ok, true);
157        let (time, ok) = bucket.take_max_duration(100, Duration::from_secs(1));
158        assert_eq!(time.as_millis(), 0);
159        assert_eq!(ok, false);
160        thread::sleep(Duration::from_secs(1));
161        let (time, ok) = bucket.take_max_duration(100, Duration::from_secs(7));
162        assert_eq!(time.as_secs(), 2);
163        assert_eq!(ok, true);
164    }
165}