feat: implement upload error handling and rate limiting improvements
This commit is contained in:
@@ -9,7 +9,7 @@ use serde_json::Value;
|
||||
|
||||
use crate::MAX_ASSETS;
|
||||
use crate::{
|
||||
MAX_UPLOADS_PER_HOUR_PER_USER,
|
||||
MAX_UPLOADS_PER_USER,
|
||||
logs::{LogEventType, log_event},
|
||||
};
|
||||
|
||||
@@ -182,19 +182,19 @@ pub struct RateLimiter {
|
||||
}
|
||||
|
||||
impl RateLimiter {
|
||||
pub async fn is_allowed(&self, client_ip: &str) -> bool {
|
||||
let mut clients = self.clients.lock().await;
|
||||
pub async fn check(&self, client_ip: &str, asset_exp_time: i64) -> (bool, Option<i64>) {
|
||||
self.clear_expired().await;
|
||||
let now = Utc::now().timestamp_millis();
|
||||
let one_hour_ago = now - Duration::hours(1).num_milliseconds();
|
||||
|
||||
let mut clients = self.clients.lock().await;
|
||||
let entry = clients.entry(client_ip.to_string()).or_insert_with(Vec::new);
|
||||
entry.retain(|×tamp| timestamp > one_hour_ago);
|
||||
|
||||
let ret_val = if entry.len() < MAX_UPLOADS_PER_HOUR_PER_USER {
|
||||
entry.push(now);
|
||||
true
|
||||
let ret_val = if entry.len() < MAX_UPLOADS_PER_USER {
|
||||
entry.push(asset_exp_time);
|
||||
(true, None)
|
||||
} else {
|
||||
false
|
||||
let first_to_expire = entry.iter().min().copied().unwrap();
|
||||
let retry_after_ms = (first_to_expire - now).max(1);
|
||||
(false, Some(retry_after_ms))
|
||||
};
|
||||
println!("{:?}", clients);
|
||||
ret_val
|
||||
@@ -203,10 +203,9 @@ impl RateLimiter {
|
||||
pub async fn clear_expired(&self) {
|
||||
let mut clients = self.clients.lock().await;
|
||||
let now = Utc::now().timestamp_millis();
|
||||
let one_hour_ago = now - Duration::hours(1).num_milliseconds();
|
||||
|
||||
for timestamps in clients.values_mut() {
|
||||
timestamps.retain(|×tamp| timestamp > one_hour_ago);
|
||||
timestamps.retain(|×tamp| timestamp > now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user