use governor::{
clock::DefaultClock,
middleware::NoOpMiddleware,
state::{InMemoryState, NotKeyed},
Quota, RateLimiter as GovRateLimiter,
};
use std::num::NonZeroU32;
use tokio::time::Duration;
pub struct RateLimiter {
inner: GovRateLimiter<NotKeyed, InMemoryState, DefaultClock, NoOpMiddleware>,
}
impl RateLimiter {
pub fn new(requests_per_second: u32, burst_size: u32) -> Self {
let quota = Quota::with_period(Duration::from_secs(1))
.unwrap()
.allow_burst(NonZeroU32::new(burst_size).unwrap())
.allow_burst(NonZeroU32::new(requests_per_second + burst_size).unwrap());
let limiter = GovRateLimiter::direct(quota);
Self { inner: limiter }
}
pub async fn acquire(&self) {
self.inner.until_ready().await;
}
}