Skip to main content

contentstack_api_client_rs/
rate_limiter.rs

1use std::{num::NonZeroU32, sync::Arc};
2
3use governor::{DefaultDirectRateLimiter, Quota, RateLimiter};
4
5pub enum RateLimitPreset {
6    Delivery,
7    Management,
8    Custom(NonZeroU32),
9}
10
11impl RateLimitPreset {
12    fn per_second(&self) -> NonZeroU32 {
13        match self {
14            Self::Delivery => Option::expect(NonZeroU32::new(100), "Provided value cannot be used"),
15            Self::Management => {
16                Option::expect(NonZeroU32::new(10), "Provided value cannot be used")
17            }
18            Self::Custom(n) => *n,
19        }
20    }
21}
22
23pub struct ClientRateLimiter {
24    inner: DefaultDirectRateLimiter,
25}
26
27impl ClientRateLimiter {
28    pub fn new(preset: RateLimitPreset) -> Arc<Self> {
29        let quota = Quota::per_second(preset.per_second());
30
31        Arc::new(Self {
32            inner: RateLimiter::direct(quota),
33        })
34    }
35
36    pub async fn until_ready(&self) {
37        self.inner.until_ready().await
38    }
39}