forcebot_rs/src/core/ratelimiter.rs

81 lines
1.9 KiB
Rust
Raw Normal View History

2023-12-19 00:34:21 -05:00
const TIME_THRESHOLD_S: u64 = 30;
2024-03-18 22:26:58 -04:00
const TIME_MIN_S_F64: f64 = 1.0;
2023-12-19 00:34:21 -05:00
const MSG_THRESHOLD: u32 = 20;
2024-03-02 09:44:09 -05:00
use std::time::Instant;
2024-03-18 22:26:58 -04:00
use crate::core::botlog;
2024-03-02 09:44:09 -05:00
#[derive(Debug, Clone)]
2023-12-19 00:34:21 -05:00
pub struct RateLimiter {
timer: Instant,
msgcounter: u32,
2024-03-18 22:26:58 -04:00
lastmsgtimer : Instant,
2023-12-19 00:34:21 -05:00
}
2024-03-18 22:26:58 -04:00
#[derive(Debug)]
2023-12-19 00:34:21 -05:00
pub enum LimiterResp {
Allow, // when it's evaluated to be within limits
2024-02-25 10:40:54 -05:00
Skip, // as outside of rate limits
2024-03-02 10:06:26 -05:00
// Enqueue, // [FUTURE]
2024-03-18 22:26:58 -04:00
Sleep(f64), // Sleep for x seconds
2023-12-19 00:34:21 -05:00
}
2024-03-01 23:36:37 -05:00
impl Default for RateLimiter {
fn default() -> Self {
Self::new()
}
}
2023-12-19 00:34:21 -05:00
impl RateLimiter {
pub fn new() -> Self {
Self {
timer: Instant::now(),
msgcounter: 0,
2024-03-18 22:26:58 -04:00
lastmsgtimer: Instant::now(),
2023-12-19 00:34:21 -05:00
}
}
2024-02-25 10:40:54 -05:00
pub fn check_limiter(&mut self) -> LimiterResp {
2024-03-18 22:26:58 -04:00
let logstr = format!(
">> RateLimiter > {:?}",self
);
botlog::trace(
logstr.as_str(),
Some("Rate Limiter Inner".to_string()),
None,
);
let rsp = if self.timer.elapsed().as_secs() >= TIME_THRESHOLD_S {
2024-02-25 10:40:54 -05:00
self.timer = Instant::now();
self.msgcounter = 0;
LimiterResp::Allow
2024-03-18 22:26:58 -04:00
} else if self.msgcounter < MSG_THRESHOLD &&
self.lastmsgtimer.elapsed().as_secs_f64() >= TIME_MIN_S_F64 {
2024-02-25 10:40:54 -05:00
LimiterResp::Allow
} else {
2024-03-02 09:44:09 -05:00
// when elapsed() < TIME_THRESHOLD_S && msgcounter >= MSG_THRESHOLD
2024-03-18 22:26:58 -04:00
// LimiterResp::Skip
2024-03-19 18:01:34 -04:00
LimiterResp::Sleep(TIME_MIN_S_F64 - self.lastmsgtimer.elapsed().as_secs_f64() + 0.1)
2024-03-18 22:26:58 -04:00
};
botlog::trace(
&format!("Limiter Response : {:?} ; Elapsed (as_sec_f64) : {}",
rsp, self.lastmsgtimer.elapsed().as_secs_f64()),
Some("Rate Limiter Inner".to_string()),
None,
);
rsp
2023-12-19 00:34:21 -05:00
}
2023-12-20 18:49:28 -05:00
2024-03-01 23:36:37 -05:00
pub fn increment_counter(&mut self) {
2024-02-25 10:40:54 -05:00
self.msgcounter += 1;
2024-03-18 22:26:58 -04:00
self.lastmsgtimer = Instant::now();
2023-12-19 00:34:21 -05:00
}
2024-02-25 10:40:54 -05:00
}