use super::GarrisonDao;
#[cfg(feature = "cache-redis")]
use super::RedisConfig;
#[cfg(feature = "tenant-isolation")]
use crate::constants::DaoKeyPrefix;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use oxcache::Cache;
use std::time::Duration;
fn prefixed_key(key: &str) -> String {
#[cfg(feature = "tenant-isolation")]
{
if let Ok(ctx) = crate::context::tenant::TENANT.try_get() {
return format!("{}{}:{}", DaoKeyPrefix::Tenant, ctx.tenant_id, key);
}
}
#[allow(unused_variables)]
let _ = key;
key.to_string()
}
#[cfg(feature = "anomalous-detector-dual")]
fn matches_pattern(key: &str, pattern: &str) -> bool {
if pattern == "*" {
return true;
}
if let Some(prefix) = pattern.strip_suffix('*') {
return key.starts_with(prefix);
}
key == pattern
}
#[cfg(feature = "anomalous-detector-dual")]
fn strip_prefix(prefixed: &str) -> String {
#[cfg(feature = "tenant-isolation")]
{
if let Some(rest) = prefixed.strip_prefix("tenant:") {
if let Some(pos) = rest.find(':') {
return rest[pos + 1..].to_string();
}
}
}
prefixed.to_string()
}
pub struct GarrisonDaoOxcache {
cache: Cache<String, String>,
atomic_lock: parking_lot::Mutex<()>,
#[cfg(feature = "cache-redis")]
redis_config: Option<RedisConfig>,
#[cfg(feature = "anomalous-detector-dual")]
key_index: parking_lot::RwLock<std::collections::HashSet<String>>,
}
impl GarrisonDaoOxcache {
pub async fn new() -> GarrisonResult<Self> {
let cache = Cache::builder()
.sync_mode(true)
.build()
.await
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-init::{}", e)))?;
Ok(Self {
cache,
atomic_lock: parking_lot::Mutex::new(()),
#[cfg(feature = "cache-redis")]
redis_config: None,
#[cfg(feature = "anomalous-detector-dual")]
key_index: parking_lot::RwLock::new(std::collections::HashSet::new()),
})
}
#[cfg(feature = "cache-redis")]
pub fn with_redis_config(mut self, config: RedisConfig) -> Self {
tracing::info!(
mode = %config.mode,
db = config.db,
pool_size = config.pool_size,
"设置 Redis 部署模式配置"
);
self.redis_config = Some(config);
self
}
#[cfg(feature = "cache-redis")]
pub fn redis_config(&self) -> Option<&RedisConfig> {
self.redis_config.as_ref()
}
}
#[async_trait]
impl GarrisonDao for GarrisonDaoOxcache {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
let actual_key = prefixed_key(key);
self.cache
.get_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
let actual_key = prefixed_key(key);
let ttl = if ttl_seconds == 0 {
None
} else {
Some(Duration::from_secs(ttl_seconds))
};
self.cache
.set_with_ttl_sync(&actual_key, &value.to_string(), ttl)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e)))?;
#[cfg(feature = "anomalous-detector-dual")]
self.key_index.write().insert(actual_key);
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
let actual_key = prefixed_key(key);
if !self
.cache
.exists_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-exists-sync::{}", e)))?
{
return Err(GarrisonError::Dao(format!("dao-key-missing::{}", key)));
}
let remaining_ttl = self
.cache
.ttl_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
self.cache
.set_with_ttl_sync(&actual_key, &value.to_string(), remaining_ttl)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-update-set-with-ttl-sync::{}", e)))
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
let actual_key = prefixed_key(key);
if seconds == 0 {
let value = self
.cache
.get_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
.ok_or_else(|| GarrisonError::Dao(format!("dao-key-missing::{}", key)))?;
self.cache
.set_with_ttl_sync(&actual_key, &value, None)
.map_err(|e| {
GarrisonError::Dao(format!("dao-oxcache-expire-set-with-ttl-sync::{}", e))
})
} else {
let updated = self
.cache
.expire_sync(&actual_key, Duration::from_secs(seconds))
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-expire-sync::{}", e)))?;
if !updated {
return Err(GarrisonError::Dao(format!("dao-key-missing::{}", key)));
}
Ok(())
}
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
let actual_key = prefixed_key(key);
self.cache
.delete_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e)))?;
#[cfg(feature = "anomalous-detector-dual")]
self.key_index.write().remove(&actual_key);
Ok(())
}
async fn set_permanent(&self, key: &str, value: &str) -> GarrisonResult<()> {
let actual_key = prefixed_key(key);
self.cache
.set_with_ttl_sync(&actual_key, &value.to_string(), None)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e)))?;
#[cfg(feature = "anomalous-detector-dual")]
self.key_index.write().insert(actual_key);
Ok(())
}
async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
let actual_key = prefixed_key(key);
self.cache
.ttl_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))
}
async fn rename(&self, old_key: &str, new_key: &str) -> GarrisonResult<()> {
let actual_old = prefixed_key(old_key);
let actual_new = prefixed_key(new_key);
let value = self
.cache
.get_sync(&actual_old)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
.ok_or_else(|| GarrisonError::InvalidParam(format!("dao-key-missing::{}", old_key)))?;
let remaining_ttl = self
.cache
.ttl_sync(&actual_old)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
self.cache
.set_with_ttl_sync(&actual_new, &value, remaining_ttl)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e)))?;
self.cache
.delete_sync(&actual_old)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e)))
}
async fn get_and_delete(&self, key: &str) -> GarrisonResult<Option<String>> {
let _guard = self.atomic_lock.lock();
let actual_key = prefixed_key(key);
let value = self
.cache
.get_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?;
if value.is_some() {
self.cache
.delete_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e)))?;
}
Ok(value)
}
async fn incr(&self, key: &str, ttl_seconds: u64) -> GarrisonResult<u64> {
let _guard = self.atomic_lock.lock();
let actual_key = prefixed_key(key);
match self
.cache
.get_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
{
Some(v) => {
let cur_val: u64 = v.parse().map_err(|_| {
GarrisonError::Dao(format!(
"incr: 现存值非 u64,key={}, value={}",
actual_key, v
))
})?;
let new_val = cur_val + 1;
let remaining_ttl = self
.cache
.ttl_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
self.cache
.set_with_ttl_sync(&actual_key, &new_val.to_string(), remaining_ttl)
.map_err(|e| {
GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e))
})?;
Ok(new_val)
},
None => {
let ttl = if ttl_seconds == 0 {
None
} else {
Some(Duration::from_secs(ttl_seconds))
};
self.cache
.set_with_ttl_sync(&actual_key, &"1".to_string(), ttl)
.map_err(|e| {
GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e))
})?;
Ok(1)
},
}
}
#[cfg(feature = "anomalous-detector-dual")]
async fn keys(&self, pattern: &str) -> GarrisonResult<Vec<String>> {
let actual_pattern = prefixed_key(pattern);
let mut result = Vec::new();
let mut expired_keys = Vec::new();
{
let index = self.key_index.read();
for key in index.iter() {
if matches_pattern(key, &actual_pattern) {
if self.cache.exists_sync(key).unwrap_or(false) {
let raw_key = strip_prefix(key);
result.push(raw_key);
} else {
expired_keys.push(key.clone());
}
}
}
}
if !expired_keys.is_empty() {
let mut index = self.key_index.write();
for key in &expired_keys {
index.remove(key);
}
tracing::debug!("keys() 清理了 {} 个过期 key", expired_keys.len());
}
Ok(result)
}
}