rateflow/
tier.rs

1use crate::{Strategy, Window};
2
3/// Tier represents a rate limiting tier with specific limits
4#[derive(Debug, Clone)]
5pub struct Tier {
6    /// Name of the tier (e.g., "free", "premium")
7    name: String,
8    /// Maximum number of requests allowed in the window
9    limit: u64,
10    /// Time window for the rate limit
11    window: Window,
12    /// Rate limiting strategy to use
13    strategy: Strategy,
14}
15
16impl Tier {
17    /// Create a new tier with the given name
18    pub fn new(name: impl Into<String>) -> Self {
19        Self {
20            name: name.into(),
21            limit: 100,
22            window: Window::default(),
23            strategy: Strategy::default(),
24        }
25    }
26
27    /// Set the request limit
28    pub fn limit(mut self, limit: u64) -> Self {
29        self.limit = limit;
30        self
31    }
32
33    /// Set the time window
34    pub fn window(mut self, window: Window) -> Self {
35        self.window = window;
36        self
37    }
38
39    /// Set the rate limiting strategy
40    pub fn strategy(mut self, strategy: Strategy) -> Self {
41        self.strategy = strategy;
42        self
43    }
44
45    /// Get the tier name
46    pub fn name(&self) -> &str {
47        &self.name
48    }
49
50    /// Get the limit
51    pub fn get_limit(&self) -> u64 {
52        self.limit
53    }
54
55    /// Get the window
56    pub fn get_window(&self) -> Window {
57        self.window
58    }
59
60    /// Get the strategy
61    pub fn get_strategy(&self) -> Strategy {
62        self.strategy
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn test_tier_builder() {
72        let tier = Tier::new("premium")
73            .limit(1000)
74            .window(Window::Hour)
75            .strategy(Strategy::TokenBucket);
76
77        assert_eq!(tier.name(), "premium");
78        assert_eq!(tier.get_limit(), 1000);
79        assert_eq!(tier.get_window(), Window::Hour);
80        assert_eq!(tier.get_strategy(), Strategy::TokenBucket);
81    }
82}