Skip to main content

use_rate_limit/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7/// Error returned when API primitive text or labels are invalid.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10    /// The supplied value was empty after trimming.
11    Empty,
12    /// The supplied value used syntax this crate rejects.
13    Invalid,
14    /// The supplied label was not recognized.
15    Unknown,
16}
17
18impl fmt::Display for ApiPrimitiveError {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::Empty => formatter.write_str("API primitive value cannot be empty"),
22            Self::Invalid => formatter.write_str("invalid API primitive value"),
23            Self::Unknown => formatter.write_str("unknown API primitive label"),
24        }
25    }
26}
27
28impl Error for ApiPrimitiveError {}
29
30fn validate_api_text(value: &str) -> Result<&str, ApiPrimitiveError> {
31    let trimmed = value.trim();
32    if trimmed.is_empty() {
33        return Err(ApiPrimitiveError::Empty);
34    }
35    if trimmed.chars().any(char::is_control) {
36        return Err(ApiPrimitiveError::Invalid);
37    }
38    Ok(trimmed)
39}
40
41macro_rules! text_newtype {
42    ($name:ident) => {
43        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44        pub struct $name(String);
45
46        impl $name {
47            /// Creates validated text metadata.
48            ///
49            /// # Errors
50            ///
51            /// Returns [ApiPrimitiveError] when the value is empty or contains control characters.
52            pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
53                validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
54            }
55
56            /// Parses validated text metadata.
57            ///
58            /// # Errors
59            ///
60            /// Returns [ApiPrimitiveError] when validation fails.
61            pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62                Self::new(value)
63            }
64
65            /// Returns the stored text.
66            #[must_use]
67            pub fn as_str(&self) -> &str {
68                &self.0
69            }
70
71            /// Consumes the value and returns the stored text.
72            #[must_use]
73            pub fn into_string(self) -> String {
74                self.0
75            }
76        }
77
78        impl AsRef<str> for $name {
79            fn as_ref(&self) -> &str {
80                self.as_str()
81            }
82        }
83
84        impl fmt::Display for $name {
85            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86                formatter.write_str(self.as_str())
87            }
88        }
89
90        impl FromStr for $name {
91            type Err = ApiPrimitiveError;
92
93            fn from_str(value: &str) -> Result<Self, Self::Err> {
94                Self::new(value)
95            }
96        }
97
98        impl TryFrom<&str> for $name {
99            type Error = ApiPrimitiveError;
100
101            fn try_from(value: &str) -> Result<Self, Self::Error> {
102                Self::new(value)
103            }
104        }
105    };
106}
107
108text_newtype!(BucketName);
109text_newtype!(ResetTimeLabel);
110
111/// Rate limit policy labels.
112#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
113pub enum LimitPolicy {
114    /// A stable label variant.
115    FixedWindow,
116    /// A stable label variant.
117    SlidingWindow,
118    /// A stable label variant.
119    TokenBucket,
120    /// A stable label variant.
121    LeakyBucket,
122}
123
124impl LimitPolicy {
125    /// Returns the stable label.
126    #[must_use]
127    pub const fn as_str(self) -> &'static str {
128        match self {
129            Self::FixedWindow => "fixed-window",
130            Self::SlidingWindow => "sliding-window",
131            Self::TokenBucket => "token-bucket",
132            Self::LeakyBucket => "leaky-bucket",
133        }
134    }
135}
136
137impl Default for LimitPolicy {
138    fn default() -> Self {
139        Self::FixedWindow
140    }
141}
142
143impl fmt::Display for LimitPolicy {
144    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
145        formatter.write_str(self.as_str())
146    }
147}
148
149impl FromStr for LimitPolicy {
150    type Err = ApiPrimitiveError;
151
152    fn from_str(value: &str) -> Result<Self, Self::Err> {
153        let trimmed = value.trim();
154        if trimmed.is_empty() {
155            return Err(ApiPrimitiveError::Empty);
156        }
157        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
158        match normalized.as_str() {
159            "fixed-window" => Ok(Self::FixedWindow),
160            "sliding-window" => Ok(Self::SlidingWindow),
161            "token-bucket" => Ok(Self::TokenBucket),
162            "leaky-bucket" => Ok(Self::LeakyBucket),
163            _ => Err(ApiPrimitiveError::Unknown),
164        }
165    }
166}
167
168/// Lightweight metadata tying this crate's primary text and label together.
169#[derive(Clone, Debug, Eq, PartialEq)]
170pub struct PrimitiveMetadata {
171    name: BucketName,
172    kind: LimitPolicy,
173}
174
175impl PrimitiveMetadata {
176    /// Creates primitive metadata.
177    #[must_use]
178    pub const fn new(name: BucketName, kind: LimitPolicy) -> Self {
179        Self { name, kind }
180    }
181
182    /// Returns the primary text value.
183    #[must_use]
184    pub const fn name(&self) -> &BucketName {
185        &self.name
186    }
187
188    /// Returns the primary label.
189    #[must_use]
190    pub const fn kind(&self) -> LimitPolicy {
191        self.kind
192    }
193}
194
195/// Rate limit counters.
196#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
197pub struct RateLimit {
198    quota: u64,
199    remaining: u64,
200}
201
202impl RateLimit {
203    /// Creates rate limit counters.
204    #[must_use]
205    pub const fn new(quota: u64, remaining: u64) -> Self {
206        Self { quota, remaining }
207    }
208
209    /// Returns true when no quota remains.
210    #[must_use]
211    pub const fn is_exhausted(self) -> bool {
212        self.remaining == 0
213    }
214
215    /// Returns true when quota remains.
216    #[must_use]
217    pub const fn has_remaining(self) -> bool {
218        self.remaining > 0
219    }
220
221    /// Returns the configured quota.
222    #[must_use]
223    pub const fn quota(self) -> u64 {
224        self.quota
225    }
226}
227
228/// Retry-after seconds.
229#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
230pub struct RetryAfterSeconds(u64);
231
232impl RetryAfterSeconds {
233    /// Creates retry-after seconds.
234    #[must_use]
235    pub const fn new(value: u64) -> Self {
236        Self(value)
237    }
238
239    /// Returns the seconds value.
240    #[must_use]
241    pub const fn value(self) -> u64 {
242        self.0
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
252        let value = BucketName::new("global")?;
253
254        assert_eq!(value.as_str(), "global");
255        assert_eq!(value.to_string(), "global");
256        assert_eq!("global".parse::<BucketName>()?, value);
257        Ok(())
258    }
259
260    #[test]
261    fn rejects_empty_text() {
262        assert_eq!(BucketName::new(""), Err(ApiPrimitiveError::Empty));
263    }
264
265    #[test]
266    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
267        let kind = "fixed-window".parse::<LimitPolicy>()?;
268
269        assert_eq!(kind, LimitPolicy::FixedWindow);
270        assert_eq!(kind.to_string(), "fixed-window");
271        Ok(())
272    }
273
274    #[test]
275    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
276        let metadata = PrimitiveMetadata::new(BucketName::new("global")?, LimitPolicy::default());
277
278        assert_eq!(metadata.name().as_str(), "global");
279        assert_eq!(metadata.kind(), LimitPolicy::default());
280        Ok(())
281    }
282}