1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2025-01-31 06:22:59 +00:00
comunicapiv3/src/helpers/requests_limit_helper.rs

60 lines
1.4 KiB
Rust
Raw Normal View History

2021-01-22 19:39:14 +01:00
//! # Requests limit helper
//!
//! Handle the limitation of requests, depending on threshold criterias
use std::sync::{Arc, Mutex};
use crate::constants::LIMIT_COUNTER_LIFETIME;
use crate::data::error::ResultBoxError;
use crate::utils::date_utils;
/// Information about a IP address limitation
struct IpInfo {
time_start: u64,
count: u64,
}
/// Limits cache
type Cache = Arc<dashmap::DashMap<String, IpInfo>>;
static mut LIMITS_CACHE: Option<Arc<Mutex<Cache>>> = None;
/// Initialize limit cache storage
pub fn init() {
let limits_cache = Arc::new(dashmap::DashMap::new());
let limits_cache = Some(Arc::new(Mutex::new(limits_cache)));
unsafe {
LIMITS_CACHE = limits_cache;
}
}
/// Get access to the cache. This resource must absolutely be released as quickly as possible
fn get_cache() -> ResultBoxError<Cache> {
let cache: Cache;
unsafe {
let guard = LIMITS_CACHE.as_ref().unwrap().lock();
cache = guard.unwrap().clone();
}
Ok(cache)
}
/// Clean cached information
pub fn clean_cache() -> ResultBoxError {
let time = date_utils::time();
let cache = get_cache()?;
let obsolete_ips: Vec<String> = cache
.iter()
.filter(|k| k.time_start + LIMIT_COUNTER_LIFETIME < time)
.map(|k| k.key().to_string())
.collect();
for obsolete_ip in obsolete_ips {
cache.remove(&obsolete_ip);
}
Ok(())
}