use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use limiteron::error::{LimiteronError, StorageError};
use limiteron::limiters::{DistributedLimiter, Limiter, RedisDistributedLimiter};
use limiteron::storage::Storage;
use oxcache::backend::RedisBackend;
use oxcache::Cache;
use std::sync::Arc;
use std::time::Duration;
use super::backend::LimiterBackend;
use crate::strategy::rate_limiter_backend::RateLimitBackend;
const REDIS_LIMITER_EVAL_TIMEOUT: Duration = Duration::from_secs(1);
pub struct RedisLimiterBackend {
limiter: RedisDistributedLimiter,
cache: Cache<String, String>,
}
impl RedisLimiterBackend {
pub async fn connect(redis_url: &str) -> GarrisonResult<Self> {
let endpoint = RateLimitBackend::Redis {
redis_url: redis_url.to_string(),
};
let backend = Arc::new(
RedisBackend::new(redis_url)
.await
.map_err(|e| config_error(&endpoint, "connect", &e))?,
);
let limiter_cache = Cache::<String, String>::builder()
.backend_arc(backend.clone())
.ttl_jitter(0.0)
.build()
.await
.map_err(|e| config_error(&endpoint, "limiter-cache", &e))?;
let storage_cache = Cache::<String, String>::builder()
.backend_arc(backend)
.ttl_jitter(0.0)
.build()
.await
.map_err(|e| config_error(&endpoint, "storage-cache", &e))?;
Ok(Self {
limiter: RedisDistributedLimiter::new(limiter_cache, 1, 1000)
.with_timeout(REDIS_LIMITER_EVAL_TIMEOUT),
cache: storage_cache,
})
}
}
fn config_error(
endpoint: &RateLimitBackend,
stage: &str,
e: &oxcache::OxCacheError,
) -> GarrisonError {
let endpoint = format!("{:?}", endpoint);
GarrisonError::Config(format!(
"config-rate-limit-redis-connect::{}",
crate::i18n::translate_detail(
"config-rate-limit-redis-connect",
&[
("stage", stage),
("endpoint", endpoint.as_str()),
("code", e.code()),
],
)
))
}
fn map_oxcache_err(e: oxcache::OxCacheError) -> LimiteronError {
LimiteronError::StorageError(StorageError::QueryError(format!(
"oxcache-redis-limiter::{}",
e.code()
)))
}
fn map_oxcache_storage_err(e: oxcache::OxCacheError) -> StorageError {
StorageError::QueryError(format!("oxcache-redis-limiter::{}", e.code()))
}
fn storage_ttl(ttl: Option<u64>) -> Option<Duration> {
match ttl {
None | Some(0) => None,
Some(secs) => Some(Duration::from_secs(secs)),
}
}
#[async_trait]
impl Limiter for RedisLimiterBackend {
async fn allow(&self, cost: u64) -> Result<bool, LimiteronError> {
self.limiter.allow(cost).await
}
}
#[async_trait]
impl DistributedLimiter for RedisLimiterBackend {
async fn incr(&self, key: &str, amount: u64) -> Result<u64, LimiteronError> {
DistributedLimiter::incr(&self.limiter, key, amount).await
}
async fn incr_with_ttl(
&self,
key: &str,
amount: u64,
ttl: Duration,
) -> Result<u64, LimiteronError> {
DistributedLimiter::incr_with_ttl(&self.limiter, key, amount, ttl).await
}
async fn get_count(&self, key: &str) -> Result<u64, LimiteronError> {
DistributedLimiter::get_count(&self.limiter, key).await
}
async fn reset(&self, key: &str) -> Result<(), LimiteronError> {
DistributedLimiter::reset(&self.limiter, key).await
}
}
#[async_trait]
impl Storage for RedisLimiterBackend {
async fn get(&self, key: &str) -> Result<Option<String>, StorageError> {
let key = key.to_string();
self.cache.get(&key).await.map_err(map_oxcache_storage_err)
}
async fn set(&self, key: &str, value: &str, ttl: Option<u64>) -> Result<(), StorageError> {
let key = key.to_string();
let value = value.to_string();
match storage_ttl(ttl) {
None => self
.cache
.set(&key, &value)
.await
.map_err(map_oxcache_storage_err),
Some(ttl) => self
.cache
.set_with_ttl(&key, &value, Some(ttl))
.await
.map_err(map_oxcache_storage_err),
}
}
async fn delete(&self, key: &str) -> Result<(), StorageError> {
let key = key.to_string();
self.cache
.delete(&key)
.await
.map_err(map_oxcache_storage_err)
}
}
#[async_trait]
impl LimiterBackend for RedisLimiterBackend {
async fn atomic_check_and_incr(
&self,
key: &str,
threshold: u64,
ttl: Duration,
) -> Result<bool, LimiteronError> {
let count = DistributedLimiter::incr_with_ttl(&self.limiter, key, 1, ttl).await?;
Ok(count <= threshold)
}
async fn reset_prefix(&self, prefix: &str) -> Result<(), LimiteronError> {
let pattern = format!("{prefix}*");
let keys = self.cache.keys(&pattern).await.map_err(map_oxcache_err)?;
for key in keys {
self.cache.delete(&key).await.map_err(map_oxcache_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> {
let (allowed, count) = RedisDistributedLimiter::allow_sliding_window(
&self.limiter,
key,
window_ms,
max_requests,
)
.await?;
Ok((allowed, count.max(0) as u64, 0))
}
}
#[cfg(test)]
mod tests {
use super::storage_ttl;
use std::time::Duration;
#[test]
fn storage_ttl_maps_zero_and_none_to_permanent() {
assert_eq!(storage_ttl(None), None);
assert_eq!(storage_ttl(Some(0)), None);
assert_eq!(storage_ttl(Some(60)), Some(Duration::from_secs(60)));
}
}