use super::{GarrisonDao, GarrisonResult, SmsRateLimiter};
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 = "sms";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SmsRateWindows {
pub hour_bucket: u64,
pub date: String,
}
pub(super) fn normalize_phone(phone: &str) -> String {
phone.trim().to_string()
}
pub(super) fn validate_phone(phone: &str) -> GarrisonResult<()> {
if phone.is_empty() {
return Err(GarrisonError::InvalidParam(
"secure-phone-empty::".to_string(),
));
}
if phone.contains(':') {
return Err(GarrisonError::InvalidParam(
"secure-phone-no-colon".to_string(),
));
}
if phone.chars().any(|c| c.is_control()) {
return Err(GarrisonError::InvalidParam(
"secure-phone-no-control-char".to_string(),
));
}
if phone.chars().any(|c| c.is_whitespace()) {
return Err(GarrisonError::InvalidParam(
"secure-phone-no-whitespace".to_string(),
));
}
if phone.len() > 20 {
return Err(GarrisonError::InvalidParam(
"secure-phone-too-long".to_string(),
));
}
Ok(())
}
fn ledger_identity(phone: &str) -> String {
format!("{LEDGER_NAMESPACE}:{phone}")
}
impl SmsRateLimiter {
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(|_| ())
}
fn current_windows() -> GarrisonResult<SmsRateWindows> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| GarrisonError::Internal(format!("secure-system-time::{}", e)))?;
Ok(SmsRateWindows {
hour_bucket: now.as_secs() / SECONDS_PER_HOUR,
date: chrono::Utc::now().format("%Y-%m-%d").to_string(),
})
}
pub async fn check_and_increment(&self, phone: &str) -> GarrisonResult<()> {
self.check_and_increment_with(phone).await.map(|_| ())
}
pub async fn check_and_increment_with(&self, phone: &str) -> GarrisonResult<SmsRateWindows> {
let phone = normalize_phone(phone);
validate_phone(&phone)?;
let windows = Self::current_windows()?;
self.kernel
.consume_and_check(&ledger_identity(&phone))
.await
.map_err(|e| match e {
DualWindowError::Exceeded(w) => GarrisonError::SmsRateLimitExceeded {
window: w.as_str().to_string(),
},
DualWindowError::Storage(msg) => GarrisonError::Internal(msg),
})?;
Ok(windows)
}
pub async fn rollback(&self, phone: &str) -> GarrisonResult<()> {
let phone = normalize_phone(phone);
validate_phone(&phone)?;
self.kernel.refund_windows(&ledger_identity(&phone)).await
}
pub async fn rollback_with(
&self,
phone: &str,
_windows: &SmsRateWindows,
) -> GarrisonResult<()> {
let phone = normalize_phone(phone);
validate_phone(&phone)?;
self.kernel.refund_windows(&ledger_identity(&phone)).await
}
}