use crate::dao::GarrisonDao;
#[cfg(feature = "rate-limit-redis")]
use crate::error::GarrisonResult;
use async_trait::async_trait;
use limiteron::error::LimiteronError;
use limiteron::limiters::DistributedLimiter;
use limiteron::storage::Storage;
use std::sync::Arc;
use std::time::Duration;
use super::distributed::GarrisonDaoDistributedLimiter;
use super::errors::map_to_limiter_err;
use super::storage::GarrisonDaoStorage;
#[async_trait]
pub trait LimiterBackend: DistributedLimiter {
async fn atomic_check_and_incr(
&self,
key: &str,
threshold: u64,
ttl: Duration,
) -> Result<bool, LimiteronError>;
async fn reset_prefix(&self, prefix: &str) -> Result<(), LimiteronError>;
#[cfg(feature = "firewall-ratelimit")]
async fn allow_sliding_window(
&self,
key: &str,
window_ms: u64,
max_requests: u64,
) -> Result<(bool, u64, u64), LimiteronError>;
}
#[derive(Clone)]
pub struct LimiterRuntime {
limiter: Arc<dyn LimiterBackend>,
storage: Arc<dyn Storage>,
}
impl LimiterRuntime {
pub fn dao(dao: Arc<dyn GarrisonDao>) -> Self {
let limiter: Arc<dyn LimiterBackend> =
Arc::new(GarrisonDaoDistributedLimiter::new(dao.clone()));
let storage: Arc<dyn Storage> = Arc::new(GarrisonDaoStorage::new(dao));
Self { limiter, storage }
}
#[cfg(feature = "rate-limit-redis")]
pub async fn from_config(
config: &crate::config::GarrisonConfig,
dao: Arc<dyn GarrisonDao>,
) -> GarrisonResult<Self> {
use crate::strategy::rate_limiter_backend::RateLimitBackend;
match &config.rate_limit_backend {
RateLimitBackend::Memory => Ok(Self::dao(dao)),
RateLimitBackend::Redis { redis_url } => {
let backend = super::redis::RedisLimiterBackend::connect(redis_url).await?;
Ok(Self::redis(backend))
},
}
}
#[cfg(feature = "rate-limit-redis")]
pub fn redis(backend: super::redis::RedisLimiterBackend) -> Self {
let backend = Arc::new(backend);
let limiter: Arc<dyn LimiterBackend> = backend.clone();
let storage: Arc<dyn Storage> = backend;
Self { limiter, storage }
}
pub fn limiter(&self) -> Arc<dyn LimiterBackend> {
self.limiter.clone()
}
pub fn storage(&self) -> Arc<dyn Storage> {
self.storage.clone()
}
}
#[async_trait]
impl LimiterBackend for GarrisonDaoDistributedLimiter {
async fn atomic_check_and_incr(
&self,
key: &str,
threshold: u64,
ttl: Duration,
) -> Result<bool, LimiteronError> {
GarrisonDaoDistributedLimiter::atomic_check_and_incr(self, key, threshold, ttl).await
}
async fn reset_prefix(&self, prefix: &str) -> Result<(), LimiteronError> {
let pattern = format!("{prefix}*");
let keys = self.dao.keys(&pattern).await.map_err(map_to_limiter_err)?;
for key in keys {
self.dao.delete(&key).await.map_err(map_to_limiter_err)?;
}
Ok(())
}
#[cfg(feature = "firewall-ratelimit")]
async fn allow_sliding_window(
&self,
key: &str,
window_ms: u64,
max_requests: u64,
) -> Result<(bool, u64, u64), LimiteronError> {
GarrisonDaoDistributedLimiter::allow_sliding_window(self, key, window_ms, max_requests)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::tests::MockDao;
fn dao_runtime() -> (LimiterRuntime, Arc<MockDao>) {
let dao = Arc::new(MockDao::new());
(LimiterRuntime::dao(dao.clone()), dao)
}
#[tokio::test]
async fn dao_reset_prefix_removes_only_matching_keys() {
let (runtime, dao) = dao_runtime();
dao.set("fw:ip:1.1.1.1", "3", 60).await.unwrap();
dao.set("fw:ip:2.2.2.2", "1", 60).await.unwrap();
dao.set("fw:acct:1001", "2", 60).await.unwrap();
runtime.limiter().reset_prefix("fw:ip:").await.unwrap();
assert!(dao.get("fw:ip:1.1.1.1").await.unwrap().is_none());
assert!(dao.get("fw:ip:2.2.2.2").await.unwrap().is_none());
assert_eq!(
dao.get("fw:acct:1001").await.unwrap().as_deref(),
Some("2"),
"非目标前缀不得被清理"
);
}
#[tokio::test]
async fn dao_runtime_counts_and_storage_share_backend() {
let (runtime, dao) = dao_runtime();
runtime
.limiter()
.incr_with_ttl("fw:ip:9.9.9.9", 1, Duration::from_secs(60))
.await
.unwrap();
runtime
.storage()
.set("rl:ip:9.9.9.9:answer", "42", Some(60))
.await
.unwrap();
assert_eq!(
runtime.limiter().get_count("fw:ip:9.9.9.9").await.unwrap(),
1
);
assert_eq!(
dao.get("rl:ip:9.9.9.9:answer").await.unwrap().as_deref(),
Some("42")
);
}
#[cfg(feature = "rate-limit-redis")]
#[tokio::test]
async fn from_config_memory_uses_dao_backend() {
let dao = Arc::new(MockDao::new());
let config = crate::config::GarrisonConfig::default_config();
let runtime = LimiterRuntime::from_config(&config, dao).await.unwrap();
runtime
.limiter()
.incr_with_ttl("fw:acct:mem", 1, Duration::from_secs(60))
.await
.unwrap();
assert_eq!(runtime.limiter().get_count("fw:acct:mem").await.unwrap(), 1);
}
}