Skip to main content

serenade_rate_limiter/
compile_pass.rs

1//! DI tag and compile pass for the default rate-limiter storage.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use serenade_di::{CompilePass, ContainerBuilder, DiError, ServiceDefinition};
7
8use crate::{
9    InMemoryRateLimiterStorage, Policy, RateLimiterError, RateLimiterFactory, RateLimiterStorage,
10};
11
12/// Service tag applied to rate-limiter storage definitions.
13pub const RATE_LIMITER_STORAGE_TAG: &str = "rate_limiter.storage";
14
15/// Container id of the default rate-limiter storage when registered by the pass.
16pub const DEFAULT_RATE_LIMITER_STORAGE_SERVICE: &str = "rate_limiter.storage";
17
18/// Newtype so [`RateLimiterStorage`] trait objects can be stored in the container.
19#[derive(Clone)]
20pub struct RateLimiterStorageService(pub Arc<dyn RateLimiterStorage>);
21
22impl RateLimiterStorageService {
23    /// Builds a [`RateLimiterFactory`] against the wrapped storage.
24    ///
25    /// # Errors
26    ///
27    /// Propagates empty `name` or invalid `policy` construction errors from the caller-built policy.
28    pub fn factory(
29        &self,
30        name: impl Into<String>,
31        policy: Policy,
32    ) -> Result<RateLimiterFactory, RateLimiterError> {
33        RateLimiterFactory::new(name, policy, Arc::clone(&self.0))
34    }
35
36    /// Convenience factory: fixed window of `limit` tokens per `interval`.
37    ///
38    /// # Errors
39    ///
40    /// Propagates policy and factory validation errors.
41    pub fn fixed_window_factory(
42        &self,
43        name: impl Into<String>,
44        limit: u32,
45        interval: Duration,
46    ) -> Result<RateLimiterFactory, RateLimiterError> {
47        self.factory(name, Policy::fixed_window(limit, interval)?)
48    }
49
50    /// Convenience factory: token bucket of `limit` tokens refill over `interval`.
51    ///
52    /// # Errors
53    ///
54    /// Propagates policy and factory validation errors.
55    pub fn token_bucket_factory(
56        &self,
57        name: impl Into<String>,
58        limit: u32,
59        interval: Duration,
60    ) -> Result<RateLimiterFactory, RateLimiterError> {
61        self.factory(name, Policy::token_bucket(limit, interval)?)
62    }
63}
64
65/// Seeds [`DEFAULT_RATE_LIMITER_STORAGE_SERVICE`] with an [`InMemoryRateLimiterStorage`] when missing.
66#[derive(Debug, Default)]
67pub struct RegisterDefaultRateLimiterPass;
68
69impl CompilePass for RegisterDefaultRateLimiterPass {
70    fn name(&self) -> &'static str {
71        "register_default_rate_limiter_storage"
72    }
73
74    fn process(&self, builder: &mut ContainerBuilder) -> Result<(), DiError> {
75        let has_default = builder
76            .definitions()
77            .iter()
78            .any(|definition| definition.id() == DEFAULT_RATE_LIMITER_STORAGE_SERVICE);
79        if has_default {
80            return Ok(());
81        }
82
83        // `expect`: default id cannot collide after the has_default guard above.
84        builder
85            .register(
86                ServiceDefinition::new(DEFAULT_RATE_LIMITER_STORAGE_SERVICE)
87                    .with_tag(RATE_LIMITER_STORAGE_TAG),
88                |_container| {
89                    Ok(Box::new(RateLimiterStorageService(
90                        Arc::new(InMemoryRateLimiterStorage::new()) as Arc<dyn RateLimiterStorage>,
91                    )))
92                },
93            )
94            .expect("default rate_limiter.storage id is unique");
95
96        Ok(())
97    }
98}