use crate::dao::GarrisonDao;
use crate::error::GarrisonError;
use async_trait::async_trait;
use limiteron::error::LimiteronError;
#[cfg(feature = "firewall-ratelimit")]
use limiteron::error::StorageError;
use limiteron::limiters::{DistributedLimiter, Limiter};
use std::sync::Arc;
use std::time::Duration;
use super::errors::map_to_limiter_err;
pub struct GarrisonDaoDistributedLimiter {
pub(super) dao: Arc<dyn GarrisonDao>,
global_threshold: u64,
}
impl GarrisonDaoDistributedLimiter {
pub fn new(dao: Arc<dyn GarrisonDao>) -> Self {
Self {
dao,
global_threshold: u64::MAX,
}
}
pub fn with_global_threshold(dao: Arc<dyn GarrisonDao>, threshold: u64) -> Self {
Self {
dao,
global_threshold: threshold,
}
}
pub async fn atomic_check_and_incr(
&self,
key: &str,
threshold: u64,
ttl: Duration,
) -> Result<bool, LimiteronError> {
const LUA_SCRIPT: &str = "local c=redis.call('INCR',KEYS[1]); if c==1 then redis.call('EXPIRE',KEYS[1],ARGV[2]) end; return c";
let keys = vec![key.to_string()];
let args = vec![threshold.to_string(), ttl.as_secs().to_string()];
match self.dao.eval_lua(LUA_SCRIPT, keys, args).await {
Ok(values) => {
let count: u64 = values
.first()
.ok_or_else(|| {
map_to_limiter_err(GarrisonError::Dao(
"limiter-eval-lua-empty::".to_string(),
))
})?
.parse()
.map_err(|e| {
map_to_limiter_err(GarrisonError::Dao(format!(
"limiteron-eval-lua-parse-failed::{}",
e
)))
})?;
Ok(count <= threshold)
},
Err(GarrisonError::NotImplemented(_)) => {
let count = self
.dao
.incr(key, ttl.as_secs())
.await
.map_err(map_to_limiter_err)?;
Ok(count <= threshold)
},
Err(e) => Err(map_to_limiter_err(e)),
}
}
#[cfg(feature = "firewall-ratelimit")]
pub async fn allow_sliding_window(
&self,
key: &str,
window_ms: u64,
max_requests: u64,
) -> Result<(bool, u64, u64), LimiteronError> {
if key.is_empty() {
return Err(LimiteronError::ConfigError(
"strategy-sliding-window-key-empty::".to_string(),
));
}
let seq_key = format!("{{{key}}}:seq");
let vals = self
.dao
.eval_lua(
limiteron::oxcache_lua::SLIDING_WINDOW_SCRIPT,
vec![key.to_string(), seq_key],
vec![window_ms.to_string(), max_requests.to_string()],
)
.await
.map_err(map_to_limiter_err)?;
match vals.as_slice() {
[allowed, count, reset] => {
let count = count.parse::<u64>().map_err(|_| {
LimiteronError::StorageError(StorageError::QueryError(format!(
"strategy-sliding-window-count-parse::{}",
count
)))
})?;
let reset = reset.parse::<u64>().unwrap_or(0);
Ok((allowed == "1", count, reset))
},
_ => Err(LimiteronError::StorageError(StorageError::QueryError(
"strategy-sliding-window-response-length::".to_string(),
))),
}
}
}
#[async_trait]
impl Limiter for GarrisonDaoDistributedLimiter {
async fn allow(&self, cost: u64) -> Result<bool, LimiteronError> {
let count = self.incr("_global", cost).await?;
Ok(count <= self.global_threshold)
}
}
#[async_trait]
impl DistributedLimiter for GarrisonDaoDistributedLimiter {
async fn incr(&self, key: &str, amount: u64) -> Result<u64, LimiteronError> {
let mut count = 0u64;
for _ in 0..amount {
count = self.dao.incr(key, 0).await.map_err(map_to_limiter_err)?;
}
if amount == 0 {
count = self.get_count(key).await?;
}
Ok(count)
}
async fn incr_with_ttl(
&self,
key: &str,
amount: u64,
ttl: Duration,
) -> Result<u64, LimiteronError> {
let ttl_secs = ttl.as_secs();
let mut count = 0u64;
for _ in 0..amount {
count = self
.dao
.incr(key, ttl_secs)
.await
.map_err(map_to_limiter_err)?;
}
if amount == 0 {
count = self.get_count(key).await?;
}
Ok(count)
}
async fn get_count(&self, key: &str) -> Result<u64, LimiteronError> {
match self.dao.get(key).await.map_err(map_to_limiter_err)? {
None => Ok(0),
Some(val) => val.parse::<u64>().map_err(|e| {
map_to_limiter_err(GarrisonError::Dao(format!(
"limiteron-get-count-parse-failed::{}::{}::{}",
key, val, e
)))
}),
}
}
async fn reset(&self, key: &str) -> Result<(), LimiteronError> {
self.dao.delete(key).await.map_err(map_to_limiter_err)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::InMemoryDao;
fn make_dao() -> Arc<dyn GarrisonDao> {
Arc::new(InMemoryDao::new())
}
#[tokio::test]
async fn limiter_incr_and_get_count() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
let count1 = limiter.incr("test:key", 1).await.unwrap();
assert_eq!(count1, 1);
let count2 = limiter.incr("test:key", 1).await.unwrap();
assert_eq!(count2, 2);
assert_eq!(limiter.get_count("test:key").await.unwrap(), 2);
}
#[tokio::test]
async fn limiter_incr_with_ttl() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
let count = limiter
.incr_with_ttl("ttl:key", 1, Duration::from_secs(60))
.await
.unwrap();
assert_eq!(count, 1);
assert_eq!(limiter.get_count("ttl:key").await.unwrap(), 1);
}
#[tokio::test]
async fn limiter_reset() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
limiter.incr("reset:key", 3).await.unwrap();
assert_eq!(limiter.get_count("reset:key").await.unwrap(), 3);
limiter.reset("reset:key").await.unwrap();
assert_eq!(limiter.get_count("reset:key").await.unwrap(), 0);
}
#[tokio::test]
async fn limiter_get_count_nonexistent() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
assert_eq!(limiter.get_count("noexist").await.unwrap(), 0);
}
#[tokio::test]
async fn m3_limiter_get_count_dirty_data_returns_err() {
let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
limiter
.dao
.set("dirty-count-key", "not-a-number", 0)
.await
.unwrap();
let result = limiter.get_count("dirty-count-key").await;
assert!(result.is_err(), "脏数据应返回错误,实际: {:?}", result);
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("get count parse failed"),
"错误消息应包含解析失败标识(嵌套错误不经过翻译链,断言取 locale 无关片段),实际: {}",
err_msg
);
}
#[tokio::test(flavor = "multi_thread")]
async fn t010_atomic_check_and_incr_concurrent_threshold() {
use std::sync::atomic::{AtomicU64, Ordering};
let dao = Arc::new(InMemoryDao::new());
let limiter = Arc::new(GarrisonDaoDistributedLimiter::new(
dao as Arc<dyn GarrisonDao>,
));
let key = "rate_limit:t010:concurrent";
let threshold = 10u64;
let ttl = Duration::from_secs(60);
let allowed = Arc::new(AtomicU64::new(0));
let rejected = Arc::new(AtomicU64::new(0));
let mut handles = Vec::new();
for _ in 0..100 {
let l = limiter.clone();
let a = allowed.clone();
let r = rejected.clone();
handles.push(tokio::spawn(async move {
let ok = l
.atomic_check_and_incr(key, threshold, ttl)
.await
.expect("atomic_check_and_incr 不应失败");
if ok {
a.fetch_add(1, Ordering::SeqCst);
} else {
r.fetch_add(1, Ordering::SeqCst);
}
}));
}
for handle in handles {
handle.await.expect("task panicked");
}
assert_eq!(
allowed.load(Ordering::SeqCst),
10,
"应精确 10 次通过,实际: {}",
allowed.load(Ordering::SeqCst)
);
assert_eq!(
rejected.load(Ordering::SeqCst),
90,
"应精确 90 次拒绝,实际: {}",
rejected.load(Ordering::SeqCst)
);
}
#[tokio::test]
async fn t010_atomic_check_and_incr_sequential_threshold() {
let dao = Arc::new(InMemoryDao::new());
let limiter = GarrisonDaoDistributedLimiter::new(dao as Arc<dyn GarrisonDao>);
let key = "rate_limit:t010:seq";
let threshold = 3u64;
let ttl = Duration::from_secs(60);
assert!(limiter
.atomic_check_and_incr(key, threshold, ttl)
.await
.unwrap());
assert!(limiter
.atomic_check_and_incr(key, threshold, ttl)
.await
.unwrap());
assert!(limiter
.atomic_check_and_incr(key, threshold, ttl)
.await
.unwrap());
assert!(!limiter
.atomic_check_and_incr(key, threshold, ttl)
.await
.unwrap());
assert!(!limiter
.atomic_check_and_incr(key, threshold, ttl)
.await
.unwrap());
}
#[tokio::test]
async fn t010_eval_lua_default_returns_not_implemented() {
use crate::dao::tests::MinimalDao;
let dao = MinimalDao::new();
let result = dao
.eval_lua(
"return 'test'",
vec!["k1".to_string()],
vec!["a1".to_string()],
)
.await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"eval_lua 默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
#[cfg(feature = "firewall-ratelimit")]
async fn sliding_window_allows_then_blocks_at_threshold() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
for expected_count in 0..3 {
let (allowed, count, _reset) = limiter
.allow_sliding_window("rl:ip:10.0.0.1", 60_000, 3)
.await
.unwrap();
assert!(allowed, "计数 {expected_count} 时应放行");
assert_eq!(count, expected_count, "判定时计数应为 {expected_count}");
}
let (allowed, count, _reset) = limiter
.allow_sliding_window("rl:ip:10.0.0.1", 60_000, 3)
.await
.unwrap();
assert!(!allowed, "第 4 个请求应被拒(达到阈值)");
assert_eq!(count, 3, "被拒时判定计数应为 3(已达上限)");
}
#[tokio::test]
#[cfg(feature = "firewall-ratelimit")]
async fn sliding_window_keys_are_independent() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
let (a1, _, _) = limiter
.allow_sliding_window("rl:ip:a", 60_000, 1)
.await
.unwrap();
let (b1, _, _) = limiter
.allow_sliding_window("rl:ip:b", 60_000, 1)
.await
.unwrap();
assert!(a1 && b1, "不同 key 的首个请求都应放行");
let (a2, _, _) = limiter
.allow_sliding_window("rl:ip:a", 60_000, 1)
.await
.unwrap();
assert!(!a2, "key a 达限后被拒");
let (b2, _, _) = limiter
.allow_sliding_window("rl:ip:b", 60_000, 1)
.await
.unwrap();
assert!(!b2, "key b 达限后被拒");
}
#[tokio::test]
#[cfg(feature = "firewall-ratelimit")]
async fn sliding_window_empty_key_rejected() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
let result = limiter.allow_sliding_window("", 60_000, 1).await;
assert!(
matches!(result, Err(LimiteronError::ConfigError(_))),
"空 key 应返回 ConfigError,实际: {:?}",
result
);
}
#[tokio::test]
#[cfg(feature = "firewall-ratelimit")]
async fn sliding_window_not_implemented_passthrough() {
use crate::dao::tests::MinimalDao;
let limiter = GarrisonDaoDistributedLimiter::new(Arc::new(MinimalDao::new()));
let result = limiter.allow_sliding_window("rl:ip:x", 60_000, 1).await;
assert!(
matches!(result, Err(LimiteronError::StorageError(_))),
"NotImplemented 应经 map_to_limiter_err 透传为 StorageError,实际: {:?}",
result
);
}
#[tokio::test]
async fn limiter_allow_returns_true() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
let result = limiter.allow(3).await;
assert!(result.is_ok(), "allow 应返回 Ok");
assert!(result.unwrap(), "allow 应返回 true");
assert!(
limiter.get_count("_global").await.unwrap() >= 3,
"_global 计数器应 >= 3"
);
}
#[tokio::test]
async fn limiter_allow_with_global_threshold_rejects() {
let limiter = GarrisonDaoDistributedLimiter::with_global_threshold(make_dao(), 5);
assert!(limiter.allow(2).await.unwrap(), "count 2 <= 5 应允许");
assert!(limiter.allow(2).await.unwrap(), "count 4 <= 5 应允许");
assert!(!limiter.allow(2).await.unwrap(), "count 6 > 5 应拒绝");
assert!(!limiter.allow(1).await.unwrap(), "count 7 > 5 应继续拒绝");
}
#[tokio::test]
async fn limiter_incr_amount_greater_than_one() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
let count = limiter.incr("batch:key", 5).await.unwrap();
assert_eq!(count, 5, "amount=5 应累计到 5");
assert_eq!(limiter.get_count("batch:key").await.unwrap(), 5);
}
#[tokio::test]
async fn limiter_incr_zero_amount_returns_current_count() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
limiter.incr("zero_key", 3).await.unwrap();
let count = limiter.incr("zero_key", 0).await.unwrap();
assert_eq!(count, 3, "amount=0 应返回当前 count 而不递增");
}
#[tokio::test]
async fn limiter_incr_with_ttl_zero_amount_returns_current_count() {
let limiter = GarrisonDaoDistributedLimiter::new(make_dao());
limiter
.incr_with_ttl("ttl_zero_key", 2, Duration::from_secs(60))
.await
.unwrap();
let count = limiter
.incr_with_ttl("ttl_zero_key", 0, Duration::from_secs(60))
.await
.unwrap();
assert_eq!(count, 2, "amount=0 应返回当前 count");
}
#[tokio::test]
async fn atomic_check_and_incr_eval_lua_success_path() {
let dao = Arc::new(InMemoryDao::new());
let limiter = GarrisonDaoDistributedLimiter::new(dao as Arc<dyn GarrisonDao>);
let ok = limiter
.atomic_check_and_incr("lua_key", 5, Duration::from_secs(60))
.await
.unwrap();
assert!(ok, "count 1 <= 5 应允许");
for _ in 0..5 {
limiter
.atomic_check_and_incr("lua_key", 5, Duration::from_secs(60))
.await
.unwrap();
}
let blocked = limiter
.atomic_check_and_incr("lua_key", 5, Duration::from_secs(60))
.await
.unwrap();
assert!(!blocked, "count 7 > 5 应拒绝");
}
}