#[cfg(feature = "rate-limit-redis")]
use crate::config::GarrisonConfig;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::limiteron::{LimiterBackend, LimiterRuntime};
use crate::strategy::firewall::{CaptchaChallenge, FirewallContext, GarrisonFirewallStrategy};
use async_trait::async_trait;
use limiteron::error::LimiteronError;
use limiteron::limiters::adaptive_threshold::{
AdaptiveThresholdConfig, AdaptiveThresholdLimiter, Feedback,
};
use limiteron::storage::Storage;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::Mutex;
const ADAPTIVE_WINDOW_SAMPLES: usize = 20;
const ADAPTIVE_MIN_SAMPLES: usize = 5;
const ADAPTIVE_COOLDOWN_SAMPLES: usize = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RateLimitScope {
Ip,
User,
Tenant,
}
#[derive(Debug, Clone)]
pub struct RateLimitConfig {
pub max_requests: u32,
pub window_seconds: u64,
pub scope: RateLimitScope,
pub dynamic_threshold: Option<usize>,
}
impl Default for RateLimitConfig {
fn default() -> Self {
Self {
max_requests: 100,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
}
}
}
impl RateLimitConfig {
pub fn validate(&self) -> GarrisonResult<()> {
if self.max_requests == 0 {
return Err(GarrisonError::InvalidParam(
"firewall-ratelimit-max-requests-zero::".to_string(),
));
}
if self.window_seconds == 0 {
return Err(GarrisonError::InvalidParam(
"firewall-ratelimit-window-seconds-zero::".to_string(),
));
}
Ok(())
}
}
pub struct RateLimitStrategy {
config: RateLimitConfig,
storage: Arc<dyn Storage>,
limiter: Arc<dyn LimiterBackend>,
adaptive: Option<AdaptiveThresholdLimiter>,
atomic_lock: Mutex<()>,
}
impl RateLimitStrategy {
pub fn new(config: RateLimitConfig, dao: Arc<dyn GarrisonDao>) -> Self {
Self::with_runtime(config, LimiterRuntime::dao(dao))
}
pub fn with_runtime(config: RateLimitConfig, runtime: LimiterRuntime) -> Self {
let storage = runtime.storage();
let adaptive = config.dynamic_threshold.map(|upper| {
AdaptiveThresholdConfig {
base_limit: u64::from(config.max_requests),
min_limit: u64::from(config.max_requests),
max_limit: upper as u64,
window_samples: ADAPTIVE_WINDOW_SAMPLES,
min_samples_for_adjust: ADAPTIVE_MIN_SAMPLES,
error_rate_increase_threshold: 0.8,
error_rate_decrease_threshold: 0.2,
latency_increase_ms: u64::MAX,
latency_decrease_ms: u64::MAX,
increase_step: (u64::from(config.max_requests) / 10).max(1),
decrease_ratio: 0.9,
cooldown_samples: ADAPTIVE_COOLDOWN_SAMPLES,
}
});
Self {
config,
storage,
limiter: runtime.limiter(),
adaptive: adaptive
.map(AdaptiveThresholdLimiter::with_validation)
.transpose()
.unwrap_or_else(|e| {
let detail = e.to_string();
panic!(
"{}",
crate::i18n::translate_detail(
"strategy-rate-limit-adaptive-config-invalid",
&[("error", detail.as_str())]
)
)
}),
atomic_lock: Mutex::new(()),
}
}
#[cfg(feature = "rate-limit-redis")]
pub async fn from_garrison_config(
config: RateLimitConfig,
dao: Arc<dyn GarrisonDao>,
app: &GarrisonConfig,
) -> GarrisonResult<Self> {
app.validate()?;
let runtime = LimiterRuntime::from_config(app, dao).await?;
Ok(Self::with_runtime(config, runtime))
}
pub async fn set_expected_answer(
&self,
ctx: &FirewallContext,
answer: &str,
) -> GarrisonResult<()> {
let (key, _) = self.build_key(ctx)?;
let answer_key = format!("{}:answer", key);
self.storage
.set(&answer_key, answer, Some(self.config.window_seconds))
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))
}
pub async fn current_threshold(&self, ctx: &FirewallContext) -> GarrisonResult<usize> {
let max = self.config.max_requests as usize;
let Some(_upper) = self.config.dynamic_threshold else {
return Ok(max);
};
let (_, _) = self.build_key(ctx)?;
Ok(self
.adaptive
.as_ref()
.map_or(max, |a| a.current_limit() as usize))
}
pub async fn adjust_threshold(
&self,
ctx: &FirewallContext,
traffic_count: usize,
) -> GarrisonResult<usize> {
let max = self.config.max_requests as usize;
let Some(adaptive) = &self.adaptive else {
return Ok(max);
};
let (_, _) = self.build_key(ctx)?;
let current = adaptive.current_limit() as usize;
let feedback = Feedback {
ok: traffic_count.saturating_mul(5) >= current.saturating_mul(4),
latency_ms: 0,
};
adaptive.report(feedback);
Ok(adaptive.current_limit() as usize)
}
fn build_key(&self, ctx: &FirewallContext) -> GarrisonResult<(String, String)> {
match self.config.scope {
RateLimitScope::Ip => Ok((format!("rl:ip:{}", ctx.ip), ctx.ip.clone())),
RateLimitScope::User => match &ctx.login_id {
Some(id) => Ok((format!("rl:user:{}", id), id.clone())),
None => Err(GarrisonError::InvalidParam(
"firewall-ratelimit-user-none::".to_string(),
)),
},
RateLimitScope::Tenant => match ctx.tenant_id {
Some(id) => Ok((format!("rl:tenant:{}", id), id.to_string())),
None => Err(GarrisonError::InvalidParam(
"firewall-ratelimit-tenant-none::".to_string(),
)),
},
}
}
}
#[async_trait]
impl GarrisonFirewallStrategy for RateLimitStrategy {
async fn check(&self, ctx: &FirewallContext) -> GarrisonResult<()> {
self.config.validate()?;
let (key, scope_id) = self.build_key(ctx)?;
let threshold = self.current_threshold(ctx).await?;
let lua_result = self
.limiter
.allow_sliding_window(&key, self.config.window_seconds * 1000, threshold as u64)
.await;
match lua_result {
Ok((true, _, _)) => Ok(()),
Ok((false, _, _)) => {
Err(GarrisonError::FirewallBlocked(format!(
"strategy-firewall-ratelimit-blocked::{}::{}::lua::{}",
scope_id,
format!("{:?}", self.config.scope).to_lowercase(),
threshold
)))
},
Err(e) if is_lua_unsupported(&e) => {
tracing::debug!(
"rate_limit: sliding window unsupported by backend, falling back to atomic_lock path (in-process atomic only)"
);
self.check_fallback(&key, &scope_id, threshold).await
},
Err(e) => {
Err(GarrisonError::Dao(format!(
"strategy-limiter-eval-lua::{}",
e
)))
},
}
}
}
fn is_lua_unsupported(e: &LimiteronError) -> bool {
matches!(e, LimiteronError::StorageError(_)) && format!("{e}").contains("NotImplemented")
}
impl RateLimitStrategy {
async fn check_fallback(
&self,
key: &str,
scope_id: &str,
threshold: usize,
) -> GarrisonResult<()> {
let _guard = self.atomic_lock.lock().await;
let timestamps = self.read_window(key).await?;
if timestamps.len() >= threshold {
return Err(GarrisonError::FirewallBlocked(format!(
"strategy-firewall-ratelimit-blocked::{}::{}::{}::{}",
scope_id,
format!("{:?}", self.config.scope).to_lowercase(),
timestamps.len(),
threshold
)));
}
let now_ms = self.now_ms()?;
let mut timestamps = timestamps;
timestamps.push(now_ms);
let serialized: String = timestamps
.iter()
.map(|t| t.to_string())
.collect::<Vec<_>>()
.join(",");
self.storage
.set(key, &serialized, Some(self.config.window_seconds))
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
Ok(())
}
async fn read_window(&self, key: &str) -> GarrisonResult<Vec<u64>> {
let now_ms = self.now_ms()?;
let window_start = now_ms.saturating_sub(self.config.window_seconds * 1000);
let stored = self
.storage
.get(key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
Ok(stored
.as_deref()
.unwrap_or("")
.split(',')
.filter(|s| !s.is_empty())
.filter_map(|s| match s.parse::<u64>() {
Ok(v) => Some(v),
Err(_) => {
tracing::warn!(key = %key, raw = %s, "rate_limit: timestamp parse failed, skipping entry (possible storage layer concurrent write truncation)");
None
}
})
.filter(|&t| t > window_start)
.collect())
}
fn now_ms(&self) -> GarrisonResult<u64> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.map_err(|e| GarrisonError::Dao(format!("strategy-system-time::{}", e)))
}
}
#[async_trait]
impl CaptchaChallenge for RateLimitStrategy {
async fn should_challenge(&self, ctx: &FirewallContext) -> GarrisonResult<bool> {
self.config.validate()?;
let (key, _) = self.build_key(ctx)?;
let count = self.read_window(&key).await?.len();
let threshold = self.current_threshold(ctx).await?;
Ok(count.saturating_mul(5) >= threshold.saturating_mul(4))
}
async fn verify_challenge(&self, ctx: &FirewallContext, answer: &str) -> GarrisonResult<bool> {
let (key, _) = self.build_key(ctx)?;
let answer_key = format!("{}:answer", key);
let stored = self
.storage
.get(&answer_key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
let matched = stored.as_deref() == Some(answer);
if matched {
self.storage
.delete(&answer_key)
.await
.map_err(|e| GarrisonError::Dao(format!("strategy-limiter-storage::{}", e)))?;
}
Ok(matched)
}
}
inventory::submit! {
crate::strategy::firewall::StrategyRegistration {
name: "ratelimit",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::tests::MockDao;
use crate::error::GarrisonError;
#[tokio::test]
async fn ratelimit_blocks_after_max_requests() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 1,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
for i in 1..=10 {
assert!(strategy.check(&ctx).await.is_ok(), "第 {} 次应通过", i);
}
let result = strategy.check(&ctx).await;
assert!(
matches!(&result, Err(GarrisonError::FirewallBlocked(msg)) if msg.contains("strategy-firewall-ratelimit-blocked")),
"第 11 次应返回 FirewallBlocked(错误串含 strategy-firewall-ratelimit-blocked),实际: {:?}",
result
);
}
#[tokio::test]
async fn ratelimit_block_error_string_contract() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 2,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("203.0.113.9");
strategy.check(&ctx).await.unwrap();
strategy.check(&ctx).await.unwrap();
let result = strategy.check(&ctx).await;
assert!(
matches!(&result, Err(GarrisonError::FirewallBlocked(msg))
if msg.contains("strategy-firewall-ratelimit-blocked::203.0.113.9::ip::lua::2")),
"错误串应含 scope_id/scope/lua/阈值,实际: {:?}",
result
);
}
#[tokio::test]
async fn ratelimit_scope_user_isolates_by_login_id() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 2,
window_seconds: 60,
scope: RateLimitScope::User,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx_a = FirewallContext::new("192.168.1.1").with_login_id("1001");
let ctx_b = FirewallContext::new("192.168.1.2").with_login_id("1002");
assert!(strategy.check(&ctx_a).await.is_ok());
assert!(strategy.check(&ctx_a).await.is_ok());
assert!(matches!(
strategy.check(&ctx_a).await,
Err(GarrisonError::FirewallBlocked(_))
));
assert!(strategy.check(&ctx_b).await.is_ok());
}
#[tokio::test]
async fn ratelimit_scope_user_without_login_id_fails() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::User,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"scope=User 且 login_id=None 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn captcha_challenge_should_trigger_when_rate_limit_near() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
for k in 0..8 {
if let Err(e) = strategy.check(&ctx).await {
panic!("第 {k} 次调用失败: {e:?}");
}
}
let should = strategy
.should_challenge(&ctx)
.await
.expect("should_challenge 不应报错");
assert!(should, "达到 80% 阈值时应触发验证码挑战,实际: {}", should);
}
#[tokio::test]
async fn captcha_challenge_should_not_trigger_when_below_threshold() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy.check(&ctx).await.expect("check 不应报错");
let should = strategy
.should_challenge(&ctx)
.await
.expect("should_challenge 不应报错");
assert!(!should, "远低于阈值时不应触发挑战,实际: {}", should);
}
#[tokio::test]
async fn captcha_challenge_verify_correct_answer() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig::default();
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy
.set_expected_answer(&ctx, "abc123")
.await
.expect("set_expected_answer 不应报错");
let ok = strategy
.verify_challenge(&ctx, "abc123")
.await
.expect("verify_challenge 不应报错");
assert!(ok, "正确答案应通过验证");
}
#[tokio::test]
async fn captcha_challenge_verify_incorrect_answer() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig::default();
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy
.set_expected_answer(&ctx, "abc123")
.await
.expect("set_expected_answer 不应报错");
let ok = strategy
.verify_challenge(&ctx, "wrong-answer")
.await
.expect("verify_challenge 不应报错");
assert!(!ok, "错误答案应验证失败");
}
#[tokio::test]
async fn captcha_challenge_verify_deletes_answer_after_success() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig::default();
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
strategy
.set_expected_answer(&ctx, "abc123")
.await
.expect("set_expected_answer 不应报错");
let first = strategy
.verify_challenge(&ctx, "abc123")
.await
.expect("首次 verify_challenge 不应报错");
assert!(first, "首次正确答案应通过");
let second = strategy
.verify_challenge(&ctx, "abc123")
.await
.expect("二次 verify_challenge 不应报错");
assert!(
!second,
"验证码验证通过后应被删除,二次使用同一答案应失败(C-6)"
);
}
#[tokio::test]
async fn dynamic_threshold_increases_when_traffic_high() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: Some(20),
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let initial = strategy
.current_threshold(&ctx)
.await
.expect("current_threshold 不应报错");
assert_eq!(initial, 10, "初始阈值应为 max_requests");
let mut current = initial;
for _ in 0..300 {
current = strategy
.adjust_threshold(&ctx, current)
.await
.expect("adjust_threshold 不应报错");
assert!(current <= 20, "阈值不得超过 dynamic_threshold 上限");
}
assert_eq!(current, 20, "持续高负载应最终封顶到 20,实际: {}", current);
}
#[tokio::test]
async fn dynamic_threshold_adjusts_only_at_decision_points() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: Some(20),
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
for i in 1..=4 {
let t = strategy.adjust_threshold(&ctx, 9).await.unwrap();
assert_eq!(t, 10, "第 {i} 次反馈(< min_samples)不应调整");
}
let at_decision = strategy.adjust_threshold(&ctx, 9).await.unwrap();
assert!(
at_decision > 10,
"第 5 次反馈(判定点)高负载应上调,实际: {}",
at_decision
);
}
#[tokio::test]
async fn dynamic_threshold_decreases_when_traffic_low() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: Some(20),
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let mut current = 10;
for _ in 0..300 {
current = strategy.adjust_threshold(&ctx, current).await.unwrap();
}
let peaked = strategy.current_threshold(&ctx).await.unwrap();
assert_eq!(peaked, 20, "高负载应将阈值推到上限,实际: {}", peaked);
let mut current = peaked;
for _ in 0..300 {
current = strategy.adjust_threshold(&ctx, 0).await.unwrap();
assert!(current >= 10, "阈值不得低于 max_requests");
}
assert_eq!(current, 10, "持续低负载应触底到 10,实际: {}", current);
}
#[tokio::test]
async fn check_uses_dynamic_threshold_not_max_requests() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 10,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: Some(20),
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("192.168.1.1");
let mut current = 10;
for _ in 0..300 {
current = strategy.adjust_threshold(&ctx, current).await.unwrap();
}
let current = strategy.current_threshold(&ctx).await.unwrap();
assert_eq!(current, 20, "阈值应已上调到 20,实际: {}", current);
for i in 1..=20 {
assert!(
strategy.check(&ctx).await.is_ok(),
"动态阈值=20 时第 {} 次 check 应通过(旧 bug 会在此拦截)",
i
);
}
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"动态阈值=20 时第 21 次 check 应被拦截,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn check_concurrent_only_max_requests_allowed_lua_path() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 5,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = Arc::new(RateLimitStrategy::new(config, dao));
let ctx = Arc::new(FirewallContext::new("10.0.0.1"));
let mut handles = Vec::new();
for _ in 0..20 {
let s = strategy.clone();
let c = ctx.clone();
handles.push(tokio::spawn(async move { s.check(&c).await }));
}
let mut allowed = 0;
let mut blocked = 0;
for handle in handles {
match handle.await.expect("tokio task panicked") {
Ok(()) => allowed += 1,
Err(GarrisonError::FirewallBlocked(_)) => blocked += 1,
Err(e) => {
panic!("check 不应返回非 FirewallBlocked 错误: {:?}", e);
},
}
}
assert_eq!(
allowed, 5,
"Lua 路径:并发 check 仅 max_requests=5 个返回 Ok(防 TOCTOU 绕过),实际: {}",
allowed
);
assert_eq!(blocked, 15, "其余 15 个应被拦截");
}
#[tokio::test(flavor = "multi_thread")]
async fn check_concurrent_only_max_requests_allowed_fallback_path() {
use crate::dao::tests::MinimalDao;
let dao: Arc<dyn GarrisonDao> = Arc::new(MinimalDao::new());
let config = RateLimitConfig {
max_requests: 5,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = Arc::new(RateLimitStrategy::new(config, dao));
let ctx = Arc::new(FirewallContext::new("10.0.0.2"));
let mut handles = Vec::new();
for _ in 0..20 {
let s = strategy.clone();
let c = ctx.clone();
handles.push(tokio::spawn(async move { s.check(&c).await }));
}
let mut allowed = 0;
let mut blocked = 0;
for handle in handles {
match handle.await.expect("tokio task panicked") {
Ok(()) => allowed += 1,
Err(GarrisonError::FirewallBlocked(_)) => blocked += 1,
Err(e) => {
panic!("check 不应返回非 FirewallBlocked 错误: {:?}", e);
},
}
}
assert_eq!(
allowed, 5,
"降级路径:atomic_lock 保护下并发 check 仅 max_requests=5 个返回 Ok,实际: {}",
allowed
);
assert_eq!(blocked, 15, "其余 15 个应被拦截");
}
#[tokio::test]
async fn check_lua_path_preserves_serial_semantics() {
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let config = RateLimitConfig {
max_requests: 3,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
};
let strategy = RateLimitStrategy::new(config, dao);
let ctx = FirewallContext::new("10.0.0.3");
assert!(strategy.check(&ctx).await.is_ok(), "第 1 次 check 应通过");
assert!(strategy.check(&ctx).await.is_ok(), "第 2 次 check 应通过");
assert!(strategy.check(&ctx).await.is_ok(), "第 3 次 check 应通过");
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::FirewallBlocked(_))),
"第 4 次 check 应被拦截,实际: {:?}",
result
);
}
#[tokio::test]
async fn zero_config_values_rejected_with_invalid_param() {
let ctx = FirewallContext::new("10.0.1.1");
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let strategy = RateLimitStrategy::new(
RateLimitConfig {
max_requests: 0,
window_seconds: 60,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
},
dao,
);
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"max_requests=0 应返回 InvalidParam,实际: {:?}",
result
);
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let strategy = RateLimitStrategy::new(
RateLimitConfig {
max_requests: 10,
window_seconds: 0,
scope: RateLimitScope::Ip,
dynamic_threshold: None,
},
dao,
);
let result = strategy.check(&ctx).await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"window_seconds=0 应返回 InvalidParam,实际: {:?}",
result
);
}
}