Skip to main content

throttle_kit/
quota.rs

1use std::time::Duration;
2
3/// A rate limit quota expressed in the GCRA style.
4#[derive(Debug, Clone, Copy)]
5pub struct Quota {
6    /// Minimum interval between allowed requests.
7    interval: Duration,
8    /// Maximum burst size.
9    pub burst: u32,
10}
11
12impl Quota {
13    /// Allow `n` requests per second.
14    pub fn per_second(n: u32) -> Self {
15        Self {
16            interval: Duration::from_secs_f64(1.0 / n as f64),
17            burst: n,
18        }
19    }
20
21    /// Allow `n` requests per minute.
22    pub fn per_minute(n: u32) -> Self {
23        Self {
24            interval: Duration::from_secs_f64(60.0 / n as f64),
25            burst: n,
26        }
27    }
28
29    /// Allow `n` requests per hour.
30    pub fn per_hour(n: u32) -> Self {
31        Self {
32            interval: Duration::from_secs_f64(3600.0 / n as f64),
33            burst: n,
34        }
35    }
36
37    /// Override the burst (token bucket) capacity.
38    pub fn allow_burst(mut self, burst: u32) -> Self {
39        self.burst = burst;
40        self
41    }
42
43    /// Create a quota with a custom interval and burst size.
44    ///
45    /// `interval` is the minimum time between allowed requests.
46    /// `burst` is the maximum number of requests that can be made in rapid succession.
47    pub fn from_parts(interval: Duration, burst: u32) -> Self {
48        Self { interval, burst }
49    }
50
51    /// The minimum interval between requests.
52    pub fn interval(&self) -> Duration {
53        self.interval
54    }
55}