mirror of
https://github.com/YGGverse/aquatic-crawler.git
synced 2026-03-31 17:15:35 +00:00
implement separated mod for the Ban feature
This commit is contained in:
parent
9cd28eaa3b
commit
bf35e8e361
2 changed files with 64 additions and 41 deletions
45
src/ban.rs
Normal file
45
src/ban.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
use chrono::{DateTime, Local};
|
||||
use librqbit::dht::Id20;
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
pub struct Ban {
|
||||
index: HashMap<Id20, DateTime<Local>>,
|
||||
timeout: u64,
|
||||
}
|
||||
|
||||
impl Ban {
|
||||
pub fn init(timeout: u64, capacity: usize) -> Self {
|
||||
Self {
|
||||
index: HashMap::with_capacity(capacity),
|
||||
timeout,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has(&self, key: &Id20) -> bool {
|
||||
self.index.contains_key(key)
|
||||
}
|
||||
|
||||
pub fn total(&self) -> usize {
|
||||
self.index.len()
|
||||
}
|
||||
|
||||
pub fn update(&mut self, time: DateTime<Local>) {
|
||||
self.index.retain(|i, &mut expires| {
|
||||
if time > expires {
|
||||
log::debug!(
|
||||
"remove ban for `{}` by the timeout expiration ({expires})",
|
||||
i.as_string()
|
||||
);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add(&mut self, key: Id20) -> DateTime<Local> {
|
||||
let t = Local::now() + Duration::from_secs(self.index.len() as u64 * self.timeout);
|
||||
assert!(self.index.insert(key, t).is_none());
|
||||
t
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue