sf_rate_limiter/
rate_limit.rs

1use crate::error::RateLimitExceededError;
2use crate::LocalDateTime;
3
4/// A structure containing information about
5/// the current speed limit for a particular key.
6#[derive(Debug)]
7pub struct RateLimit {
8    pub(crate) available_tokens: usize,
9    pub(crate) retry_after: LocalDateTime,
10    pub(crate) accepted: bool,
11    pub(crate) limit: usize,
12}
13
14impl RateLimit {
15    /// Returns the number of tokens available.
16    pub fn get_remaining_tokens(&self) -> usize {
17        self.available_tokens
18    }
19
20    /// If the tokens have run out, this method will return the time after which
21    /// at least one token will be available.
22    pub fn get_retry_after(&self) -> LocalDateTime {
23        self.retry_after.clone()
24    }
25
26    /// Returns a result reflecting whether this request was executed within the current limit.
27    pub fn is_accepted(&self) -> bool {
28        self.accepted
29    }
30
31    /// TODO doc
32    pub fn get_limit(&self) -> usize {
33        self.limit
34    }
35
36    /// Same as [`Self::is_accepted()`], but will return Err(RateLimitExceededError) if
37    /// the request failed within the current limit.
38    pub fn ensure_accepted(&self) -> Result<(), RateLimitExceededError> {
39        if !self.accepted {
40            return Err(RateLimitExceededError); // TODO : with extra info
41        }
42
43        Ok(())
44    }
45}