forcebot_rs/src/ratelimiter.rs

47 lines
1.1 KiB
Rust
Raw Normal View History

2023-12-19 00:34:21 -05:00
use std::time::Instant;
const TIME_THRESHOLD_S: u64 = 30;
const MSG_THRESHOLD: u32 = 20;
#[derive(Debug)]
pub struct RateLimiter {
timer: Instant,
msgcounter: u32,
}
pub enum LimiterResp {
Allow, // when it's evaluated to be within limits
Skip, // as outside of rate limits
}
impl RateLimiter {
pub fn new() -> Self {
Self {
timer: Instant::now(),
msgcounter: 0,
}
}
pub fn check_limiter(&mut self) -> LimiterResp {
if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S {
// # [x] elapsed >= TIME_THRESHOLD_S
self.timer = Instant::now();
self.msgcounter = 0;
LimiterResp::Allow
} else if self.msgcounter < MSG_THRESHOLD {
// # [x] elapsed < TIME_THRESHOLD_S && msgcounter < MSG_THRESHOLD
LimiterResp::Allow
// } else if self.msgcounter >= MSG_THRESHOLD {
} else {
// # [x] elapsed < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD
LimiterResp::Skip
}
}
pub fn increment_counter(&mut self) -> () {
self.msgcounter += 1;
}
}