serenade_rate_limiter/
limiter.rs1use std::sync::Arc;
4use std::time::Instant;
5
6use crate::{Policy, RateLimit, RateLimiterError, RateLimiterStorage};
7
8#[derive(Clone)]
10pub struct RateLimiter {
11 id: String,
12 policy: Policy,
13 storage: Arc<dyn RateLimiterStorage>,
14}
15
16impl RateLimiter {
17 pub(crate) fn new(id: String, policy: Policy, storage: Arc<dyn RateLimiterStorage>) -> Self {
18 Self {
19 id,
20 policy,
21 storage,
22 }
23 }
24
25 #[must_use]
27 pub fn id(&self) -> &str {
28 &self.id
29 }
30
31 #[must_use]
33 pub const fn policy(&self) -> &Policy {
34 &self.policy
35 }
36
37 pub fn consume(&self, tokens: u32) -> Result<RateLimit, RateLimiterError> {
43 self.storage.consume(
44 &self.id,
45 &self.policy,
46 tokens,
47 Instant::now(),
48 Some(self.policy.storage_ttl()),
49 )
50 }
51
52 pub fn reset(&self) -> Result<(), RateLimiterError> {
58 self.storage.reset(&self.id)
59 }
60}