use super::{EmailRateLimiter, GarrisonDao, GarrisonResult};
use crate::error::GarrisonError;
use crate::limiteron::storage::GarrisonDaoQuotaStorage;
use crate::secure::dual_window::{DualWindowError, DualWindowQuota};
use std::sync::Arc;
const SECONDS_PER_HOUR: u64 = 3600;
const LEDGER_NAMESPACE: &str = "email";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmailRateWindows {
pub hour_bucket: u64,
pub date: String,
}
pub(super) fn normalize_email(email: &str) -> String {
email.trim().to_lowercase()
}
pub(super) fn validate_email(email: &str) -> GarrisonResult<()> {
if email.is_empty() {
return Err(GarrisonError::InvalidParam(
"secure-email-empty::".to_string(),
));
}
if email.contains(':') {
return Err(GarrisonError::InvalidParam(
"secure-email-no-colon::".to_string(),
));
}
if email.chars().any(|c| c.is_control()) {
return Err(GarrisonError::InvalidParam(
"secure-email-no-control-char::".to_string(),
));
}
if email.len() > 254 {
return Err(GarrisonError::InvalidParam(
"secure-email-invalid-format::".to_string(),
));
}
if !email.contains('@') {
return Err(GarrisonError::InvalidParam(
"secure-email-invalid-format::".to_string(),
));
}
Ok(())
}
fn ledger_identity(email: &str) -> String {
format!("{LEDGER_NAMESPACE}:{email}")
}
impl EmailRateLimiter {
pub fn new(dao: Arc<dyn GarrisonDao>, hourly_limit: u32, daily_limit: u32) -> Self {
Self {
kernel: DualWindowQuota::new(
GarrisonDaoQuotaStorage::new(dao),
hourly_limit,
daily_limit,
),
}
}
pub(super) async fn decrement_counter(dao: &dyn GarrisonDao, key: &str) -> GarrisonResult<()> {
dao.decr(key).await.map(|_| ())
}
pub async fn check_and_increment(&self, email: &str) -> GarrisonResult<()> {
let normalized = normalize_email(email);
validate_email(&normalized)?;
self.check_and_increment_inner(&normalized)
.await
.map(|_| ())
}
pub(super) async fn check_and_increment_inner(
&self,
normalized: &str,
) -> GarrisonResult<EmailRateWindows> {
let windows = current_windows()?;
self.kernel
.consume_and_check(&ledger_identity(normalized))
.await
.map_err(|e| match e {
DualWindowError::Exceeded(w) => GarrisonError::EmailRateLimitExceeded {
window: w.as_str().to_string(),
},
DualWindowError::Storage(msg) => GarrisonError::Internal(msg),
})?;
Ok(windows)
}
pub async fn rollback(&self, email: &str) -> GarrisonResult<()> {
let normalized = normalize_email(email);
validate_email(&normalized)?;
self.kernel
.refund_windows(&ledger_identity(&normalized))
.await
}
pub(super) async fn rollback_inner_with(
&self,
normalized: &str,
_windows: &EmailRateWindows,
) -> GarrisonResult<()> {
self.kernel
.refund_windows(&ledger_identity(normalized))
.await
}
}
fn current_windows() -> GarrisonResult<EmailRateWindows> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| GarrisonError::Internal(format!("secure-system-time::{}", e)))?;
Ok(EmailRateWindows {
hour_bucket: now.as_secs() / SECONDS_PER_HOUR,
date: chrono::Utc::now().format("%Y-%m-%d").to_string(),
})
}