48 lines
No EOL
1.1 KiB
Rust
48 lines
No EOL
1.1 KiB
Rust
|
|
use std::time::Instant;
|
|
|
|
const TIME_THRESHOLD_S: u64 = 30;
|
|
const MSG_THRESHOLD: u32 = 20;
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
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;
|
|
}
|
|
} |