forcebot_rs/src/core/ratelimiter.rs

48 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;
2023-12-19 19:30:08 -05:00
2023-12-19 00:34:21 -05:00
#[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,
}
}
2023-12-20 18:49:28 -05:00
pub fn check_limiter(&mut self) -> LimiterResp {
if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S {
2023-12-19 00:34:21 -05:00
// # [x] elapsed >= TIME_THRESHOLD_S
2023-12-20 18:49:28 -05:00
self.timer = Instant::now();
self.msgcounter = 0;
LimiterResp::Allow
} else if self.msgcounter < MSG_THRESHOLD {
2023-12-19 00:34:21 -05:00
// # [x] elapsed < TIME_THRESHOLD_S && msgcounter < MSG_THRESHOLD
2023-12-20 18:49:28 -05:00
LimiterResp::Allow
// } else if self.msgcounter >= MSG_THRESHOLD {
} else {
2023-12-19 00:34:21 -05:00
// # [x] elapsed < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD
2023-12-20 18:49:28 -05:00
LimiterResp::Skip
2023-12-19 00:34:21 -05:00
}
2023-12-20 18:49:28 -05:00
}
2023-12-19 00:34:21 -05:00
pub fn increment_counter(&mut self) -> () {
self.msgcounter += 1;
}
}