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 = "dao-key-index")]
fn matches_pattern(key: &str, pattern: &str) -> bool {
super::in_memory::glob_match(pattern, key)
}
#[cfg(feature = "dao-key-index")]
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 {
atomic_mutex: parking_lot::Mutex<()>,
#[cfg(feature = "dao-key-index")]
key_index: parking_lot::RwLock<std::collections::HashSet<String>>,
cache: Cache<String, String>,
#[cfg(feature = "cache-redis")]
redis_config: Option<RedisConfig>,
}
impl GarrisonDaoOxcache {
pub async fn new() -> GarrisonResult<Self> {
let builder = Cache::builder().sync_mode(true).ttl_jitter(0.0);
#[cfg(feature = "cache-audit")]
let builder = builder.audit_publisher(std::sync::Arc::new(
oxcache::features::TracingAuditPublisher,
));
let cache = builder
.build()
.await
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-init::{}", e)))?;
Ok(Self {
atomic_mutex: parking_lot::Mutex::new(()),
#[cfg(feature = "dao-key-index")]
key_index: parking_lot::RwLock::new(std::collections::HashSet::new()),
cache,
#[cfg(feature = "cache-redis")]
redis_config: None,
})
}
#[cfg(feature = "cache-redis")]
pub fn with_redis_config(mut self, config: RedisConfig) -> Self {
config.warn_default_once();
tracing::warn!(
mode = %config.mode,
db = config.db,
"Redis config stored, but the _sync API (set_if_absent/incr/decr/get_and_delete) is incompatible with the Redis L2 backend; \
atomic operation methods will return Err(Config) when called until migrated to the async API"
);
self.redis_config = Some(config);
self
}
#[cfg(feature = "cache-redis")]
fn check_redis_compat(&self) -> GarrisonResult<()> {
if self.redis_config.is_some() {
return Err(GarrisonError::Config(
"dao-oxcache-sync-api-incompatible-with-redis::".to_string(),
));
}
Ok(())
}
#[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 = "dao-key-index")]
self.key_index.write().insert(actual_key);
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
let _guard = self.atomic_mutex.lock();
let actual_key = prefixed_key(key);
let remaining_ttl = self
.cache
.ttl_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
let remaining_ttl =
match remaining_ttl {
Some(ttl) => Some(ttl),
None => {
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)));
}
None },
};
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))
})?;
#[cfg(feature = "dao-key-index")]
self.key_index.write().insert(actual_key);
Ok(())
}
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 = "dao-key-index")]
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 = "dao-key-index")]
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 _guard = self.atomic_mutex.lock();
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)))?;
let remaining_ttl =
match remaining_ttl {
Some(ttl) => Some(ttl),
None => {
if !self.cache.exists_sync(&actual_old).map_err(|e| {
GarrisonError::Dao(format!("dao-oxcache-exists-sync::{}", e))
})? {
return Err(GarrisonError::InvalidParam(format!(
"dao-key-missing::{}",
old_key
)));
}
None
},
};
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)))?;
#[cfg(feature = "dao-key-index")]
{
let mut index = self.key_index.write();
index.remove(&actual_old);
index.insert(actual_new);
}
Ok(())
}
async fn get_and_delete(&self, key: &str) -> GarrisonResult<Option<String>> {
#[cfg(feature = "cache-redis")]
self.check_redis_compat()?;
let _guard = self.atomic_mutex.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)))?;
#[cfg(feature = "dao-key-index")]
self.key_index.write().remove(&actual_key);
}
Ok(value)
}
async fn set_if_absent(
&self,
key: &str,
value: &str,
ttl_seconds: u64,
) -> GarrisonResult<bool> {
#[cfg(feature = "cache-redis")]
self.check_redis_compat()?;
let _guard = self.atomic_mutex.lock();
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 Ok(false);
}
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 = "dao-key-index")]
self.key_index.write().insert(actual_key);
Ok(true)
}
async fn incr(&self, key: &str, ttl_seconds: u64) -> GarrisonResult<u64> {
#[cfg(feature = "cache-redis")]
self.check_redis_compat()?;
let _guard = self.atomic_mutex.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!("dao-incr-parse-u64::{}::{}", actual_key, v))
})?;
let new_val = cur_val.checked_add(1).ok_or_else(|| {
GarrisonError::Dao(format!("counter-overflow::{}", actual_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, &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))
})?;
#[cfg(feature = "dao-key-index")]
self.key_index.write().insert(actual_key);
Ok(1)
},
}
}
async fn decr(&self, key: &str) -> GarrisonResult<u64> {
#[cfg(feature = "cache-redis")]
self.check_redis_compat()?;
let _guard = self.atomic_mutex.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!("dao-decr-parse-u64::{}::{}", actual_key, v))
})?;
if cur_val == 0 {
return Ok(0);
}
let new_val = cur_val - 1;
if new_val == 0 {
self.cache.delete_sync(&actual_key).map_err(|e| {
GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e))
})?;
#[cfg(feature = "dao-key-index")]
self.key_index.write().remove(&actual_key);
} else {
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 => Ok(0),
}
}
async fn compare_and_update_if_greater(
&self,
key: &str,
new_value: u64,
ttl_seconds: u64,
) -> GarrisonResult<bool> {
#[cfg(feature = "cache-redis")]
self.check_redis_compat()?;
let _guard = self.atomic_mutex.lock();
let actual_key = prefixed_key(key);
let current_val: u64 = match self
.cache
.get_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
{
Some(v) => {
v.parse().map_err(|_| {
GarrisonError::Dao(format!(
"dao-compare-and-update-parse-u64::{}::{}",
actual_key, v
))
})?
},
None => 0,
};
if new_value > current_val {
let ttl = if ttl_seconds == 0 {
None
} else {
let remaining = self
.cache
.ttl_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
Some(remaining.unwrap_or_else(|| Duration::from_secs(ttl_seconds)))
};
self.cache
.set_with_ttl_sync(&actual_key, &new_value.to_string(), ttl)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e)))?;
#[cfg(feature = "dao-key-index")]
self.key_index.write().insert(actual_key);
Ok(true)
} else {
Ok(false)
}
}
async fn compare_and_swap(
&self,
key: &str,
expected: Option<&str>,
new_value: &str,
ttl_seconds: u64,
) -> GarrisonResult<bool> {
#[cfg(feature = "cache-redis")]
self.check_redis_compat()?;
let _guard = self.atomic_mutex.lock();
let actual_key = prefixed_key(key);
let current = self
.cache
.get_sync(&actual_key)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-cas-get-sync::{}", e)))?;
if current.as_deref() == expected {
let ttl = if ttl_seconds == 0 {
None
} else {
Some(Duration::from_secs(ttl_seconds))
};
self.cache
.set_with_ttl_sync(&actual_key, &new_value.to_string(), ttl)
.map_err(|e| GarrisonError::Dao(format!("dao-oxcache-cas-set-sync::{}", e)))?;
#[cfg(feature = "dao-key-index")]
self.key_index.write().insert(actual_key);
Ok(true)
} else {
Ok(false)
}
}
#[cfg(feature = "dao-key-index")]
async fn keys(&self, pattern: &str) -> GarrisonResult<Vec<String>> {
let actual_pattern = prefixed_key(pattern);
let estimated_matches = (self.key_index.read().len() / 8).max(8);
let mut result = Vec::with_capacity(estimated_matches);
let mut expired_keys = Vec::new();
let matched_keys: Vec<String> = {
let index = self.key_index.read();
index
.iter()
.filter(|key| matches_pattern(key, &actual_pattern))
.cloned()
.collect()
};
for key in &matched_keys {
match self.cache.exists_sync(key) {
Ok(true) => result.push(strip_prefix(key)),
Ok(false) => expired_keys.push(key.clone()),
Err(e) => {
tracing::warn!(
key = %key,
error = %e,
"keys() exists_sync failed; keep key_index entry"
);
},
}
}
if !expired_keys.is_empty() {
let mut index = self.key_index.write();
for key in &expired_keys {
index.remove(key);
}
tracing::debug!("keys() cleaned up {} expired keys", expired_keys.len());
}
Ok(result)
}
#[cfg(feature = "cache-redis")]
async fn eval_lua(
&self,
script: &str,
keys: Vec<String>,
args: Vec<String>,
) -> GarrisonResult<Vec<String>> {
let key_refs: Vec<&str> = keys.iter().map(|s| s.as_str()).collect();
let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
let value = self
.cache
.eval_lua(script, &key_refs, &arg_refs)
.await
.map_err(|e| {
if is_lua_backend_unsupported(&e) {
GarrisonError::NotImplemented(format!("dao-oxcache-eval-lua::{}", e))
} else {
GarrisonError::Dao(format!("dao-oxcache-eval-lua::{}", e))
}
})?;
Ok(redis_value_to_strings(value))
}
}
#[cfg(feature = "cache-redis")]
fn is_lua_backend_unsupported(e: &oxcache::OxCacheError) -> bool {
matches!(e, oxcache::OxCacheError::Operation(_))
&& e.to_string()
.contains("Lua scripts require a Redis backend")
}
#[cfg(feature = "cache-redis")]
fn redis_value_to_strings(value: oxcache::redis::Value) -> Vec<String> {
match value {
oxcache::redis::Value::Nil => vec![],
oxcache::redis::Value::Int(i) => vec![i.to_string()],
oxcache::redis::Value::BulkString(v) => {
vec![String::from_utf8_lossy(&v).to_string()]
},
oxcache::redis::Value::SimpleString(s) => vec![s],
oxcache::redis::Value::Okay => vec!["OK".to_string()],
oxcache::redis::Value::Double(d) => vec![d.to_string()],
oxcache::redis::Value::Array(items) => {
items.into_iter().flat_map(redis_value_to_strings).collect()
},
oxcache::redis::Value::Set(items) => {
items.into_iter().flat_map(redis_value_to_strings).collect()
},
oxcache::redis::Value::Map(pairs) => {
let mut result = Vec::with_capacity(pairs.len() * 2);
for (k, v) in pairs {
result.extend(redis_value_to_strings(k));
result.extend(redis_value_to_strings(v));
}
result
},
oxcache::redis::Value::Attribute { data, .. } => redis_value_to_strings(*data),
_ => vec!["[unsupported redis value type]".to_string()],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn set_overwrites_value_and_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("ow", "v1", 3600).await.unwrap();
dao.set("ow", "v2", 1).await.unwrap();
assert_eq!(dao.get("ow").await.unwrap().as_deref(), Some("v2"));
tokio::time::sleep(Duration::from_secs(2)).await;
assert!(
dao.get("ow").await.unwrap().is_none(),
"重复 set 应覆盖原 TTL,新 TTL 过期后应返回 None"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn expired_key_reads_return_none() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("exp_read", "v", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
assert!(
dao.get("exp_read").await.unwrap().is_none(),
"过期后 get → None"
);
assert!(
dao.get_timeout("exp_read").await.unwrap().is_none(),
"过期后 get_timeout → None"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn boundary_keys_roundtrip_without_panic() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("", "empty", 60).await.unwrap();
assert_eq!(dao.get("").await.unwrap().as_deref(), Some("empty"));
let weird = "a:b\nc\"d'e\u{1f4af}";
dao.set(weird, "v", 60).await.unwrap();
assert_eq!(dao.get(weird).await.unwrap().as_deref(), Some("v"));
let long = "k".repeat(4096);
dao.set(&long, "lv", 60).await.unwrap();
assert_eq!(dao.get(&long).await.unwrap().as_deref(), Some("lv"));
}
#[tokio::test(flavor = "multi_thread")]
async fn incr_missing_key_initializes_to_one_with_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
assert_eq!(dao.incr("ic_new", 60).await.unwrap(), 1);
assert_eq!(dao.get("ic_new").await.unwrap().as_deref(), Some("1"));
let ttl = dao.get_timeout("ic_new").await.unwrap();
assert!(ttl.is_some(), "首次 incr 应设置 TTL");
assert!(ttl.unwrap() <= Duration::from_secs(60));
}
#[tokio::test(flavor = "multi_thread")]
async fn incr_existing_key_preserves_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("ic_exist", "5", 2).await.unwrap();
assert_eq!(dao.incr("ic_exist", 3600).await.unwrap(), 6);
tokio::time::sleep(Duration::from_secs(3)).await;
assert!(
dao.get("ic_exist").await.unwrap().is_none(),
"incr 不应重置 TTL:原 2s TTL 过期后应返回 None"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn incr_new_key_with_zero_ttl_is_permanent() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
assert_eq!(dao.incr("ic_perm", 0).await.unwrap(), 1);
tokio::time::sleep(Duration::from_millis(50)).await;
assert_eq!(dao.get("ic_perm").await.unwrap().as_deref(), Some("1"));
assert!(dao.get_timeout("ic_perm").await.unwrap().is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn incr_non_numeric_value_returns_error() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("ic_bad", "not-a-number", 60).await.unwrap();
let result = dao.incr("ic_bad", 60).await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-incr-parse-u64")),
"incr 非数字值应返回含'dao-incr-parse-u64'的 Dao 错误,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn decr_missing_key_returns_zero_without_creating() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
assert_eq!(dao.decr("dc_missing").await.unwrap(), 0);
assert!(
dao.get("dc_missing").await.unwrap().is_none(),
"decr 不存在的 key 不应创建 key"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn decr_decrements_and_deletes_at_zero() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("dc_counter", "3", 60).await.unwrap();
assert_eq!(dao.decr("dc_counter").await.unwrap(), 2);
assert_eq!(dao.decr("dc_counter").await.unwrap(), 1);
assert_eq!(dao.decr("dc_counter").await.unwrap(), 0);
assert!(
dao.get("dc_counter").await.unwrap().is_none(),
"decr 到 0(new_val == 0 分支)应删除 key"
);
assert_eq!(
dao.decr("dc_counter").await.unwrap(),
0,
"key 已删除后 decr → 0"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn decr_zero_value_stays_zero_and_keeps_key() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("dc_zero", "0", 60).await.unwrap();
assert_eq!(dao.decr("dc_zero").await.unwrap(), 0);
assert_eq!(
dao.get("dc_zero").await.unwrap().as_deref(),
Some("0"),
"cur_val == 0 时 decr 不应删除 key"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn decr_positive_result_preserves_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("dc_ttl", "5", 2).await.unwrap();
assert_eq!(dao.decr("dc_ttl").await.unwrap(), 4);
tokio::time::sleep(Duration::from_secs(3)).await;
assert!(
dao.get("dc_ttl").await.unwrap().is_none(),
"decr 保留原 2s TTL,过期后应返回 None"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn decr_non_numeric_value_returns_error() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("dc_bad", "not-a-number", 60).await.unwrap();
let result = dao.decr("dc_bad").await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-decr-parse-u64")),
"decr 非数字值应返回含'dao-decr-parse-u64'的 Dao 错误,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn compare_greater_missing_key_initializes_with_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let updated = dao
.compare_and_update_if_greater("cg_new", 5, 60)
.await
.unwrap();
assert!(updated, "key 不存在(current=0)且 new=5 > 0 应更新");
assert_eq!(dao.get("cg_new").await.unwrap().as_deref(), Some("5"));
assert!(dao.get_timeout("cg_new").await.unwrap().is_some());
}
#[tokio::test(flavor = "multi_thread")]
async fn compare_greater_with_zero_ttl_is_permanent() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let updated = dao
.compare_and_update_if_greater("cg_perm", 5, 0)
.await
.unwrap();
assert!(updated);
assert!(
dao.get_timeout("cg_perm").await.unwrap().is_none(),
"ttl_seconds=0 应写入永久键(get_timeout → None)"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn compare_greater_existing_key_preserves_remaining_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("cg_exist", "3", 2).await.unwrap();
let updated = dao
.compare_and_update_if_greater("cg_exist", 5, 3600)
.await
.unwrap();
assert!(updated);
tokio::time::sleep(Duration::from_secs(3)).await;
assert!(
dao.get("cg_exist").await.unwrap().is_none(),
"CAS 更新应保留原 2s 剩余 TTL,过期后应返回 None"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn compare_not_greater_returns_false() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("cg_hold", "10", 60).await.unwrap();
let smaller = dao
.compare_and_update_if_greater("cg_hold", 5, 60)
.await
.unwrap();
assert!(!smaller, "5 <= 10 不应更新");
let equal = dao
.compare_and_update_if_greater("cg_hold", 10, 60)
.await
.unwrap();
assert!(!equal, "10 <= 10(相等)不应更新");
assert_eq!(
dao.get("cg_hold").await.unwrap().as_deref(),
Some("10"),
"未更新时值应保持不变"
);
let zero = dao
.compare_and_update_if_greater("cg_absent", 0, 60)
.await
.unwrap();
assert!(!zero, "缺失 key + new_value=0 不应更新");
assert!(
dao.get("cg_absent").await.unwrap().is_none(),
"不应创建 key"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn compare_greater_non_numeric_value_returns_error() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("cg_bad", "not-a-number", 60).await.unwrap();
let result = dao.compare_and_update_if_greater("cg_bad", 1, 60).await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-compare-and-update-parse-u64")),
"非数字值应返回含 'dao-compare-and-update-parse-u64' 的 Dao 错误,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cas_match_replaces_value_with_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("cs_k", "old", 60).await.unwrap();
let ok = dao
.compare_and_swap("cs_k", Some("old"), "new", 60)
.await
.unwrap();
assert!(ok);
assert_eq!(dao.get("cs_k").await.unwrap().as_deref(), Some("new"));
assert!(
dao.get_timeout("cs_k").await.unwrap().is_some(),
"CAS 写入应带 TTL"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cas_mismatch_and_absent_branches_return_false() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("cs_m", "actual", 60).await.unwrap();
let ok = dao
.compare_and_swap("cs_m", Some("expected"), "new", 60)
.await
.unwrap();
assert!(!ok);
assert_eq!(dao.get("cs_m").await.unwrap().as_deref(), Some("actual"));
let ok = dao.compare_and_swap("cs_m", None, "new", 60).await.unwrap();
assert!(!ok);
let ok = dao
.compare_and_swap("cs_absent", Some("old"), "new", 60)
.await
.unwrap();
assert!(!ok);
assert!(
dao.get("cs_absent").await.unwrap().is_none(),
"不应创建 key"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cas_none_expected_creates_and_zero_ttl_is_permanent() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let ok = dao
.compare_and_swap("cs_init", None, "initial", 0)
.await
.unwrap();
assert!(ok);
assert_eq!(
dao.get("cs_init").await.unwrap().as_deref(),
Some("initial")
);
assert!(
dao.get_timeout("cs_init").await.unwrap().is_none(),
"ttl=0 应写入永久键"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn prefixed_key_without_tenant_context_is_identity() {
assert_eq!(prefixed_key("plain_key"), "plain_key");
assert_eq!(prefixed_key(""), "");
}
#[cfg(feature = "dao-key-index")]
mod key_index {
use super::*;
#[test]
fn matches_pattern_basic_cases() {
assert!(matches_pattern("anything", "*"));
assert!(matches_pattern("anomalous:login:1:1", "anomalous:login:*"));
assert!(matches_pattern("exact-key", "exact-key"));
assert!(!matches_pattern("other:key", "anomalous:login:*"));
assert!(!matches_pattern("short", "exact-key"));
}
#[test]
fn matches_pattern_middle_star_is_wildcard() {
assert!(matches_pattern("axb", "a*b"), "中间 * 应做通配");
assert!(matches_pattern("ab", "a*b"), "* 可匹配空序列");
assert!(matches_pattern("aXYzb", "a*b"), "* 跨多字符");
assert!(
matches_pattern("a/b", "a*b"),
"* 回溯时可匹配任意字符(含 /)"
);
assert!(
!matches_pattern("aXbY", "a*b"),
"尾部无剩余 pattern 时不应命中"
);
}
#[test]
fn matches_pattern_question_mark_is_single_char() {
assert!(matches_pattern("key1", "key?"), "? 应匹配单个字符");
assert!(
matches_pattern("key:", "key?"),
"? 匹配任意单字符(含冒号)"
);
assert!(!matches_pattern("key12", "key?"), "? 不匹配两个字符");
assert!(!matches_pattern("key", "key?"), "? 不匹配零个字符");
assert!(
matches_pattern("user:1:tok", "user:*:tok"),
"* 与 ? 组合(跨段通配)"
);
assert!(matches_pattern("user:1", "user:?"), "? 恰好匹配尾段单字符");
}
#[test]
fn strip_prefix_variants() {
assert_eq!(strip_prefix("plain"), "plain");
#[cfg(feature = "tenant-isolation")]
{
assert_eq!(strip_prefix("tenant:42:real_key"), "real_key");
assert_eq!(strip_prefix("tenant:42"), "tenant:42");
}
#[cfg(not(feature = "tenant-isolation"))]
{
assert_eq!(strip_prefix("tenant:42:real_key"), "tenant:42:real_key");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn keys_exact_pattern_and_no_match() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("kx_exact", "v", 3600).await.unwrap();
let keys = dao.keys("kx_exact").await.unwrap();
assert_eq!(
keys,
vec!["kx_exact".to_string()],
"精确 pattern 应命中该 key"
);
let none = dao.keys("kx_no_such_*").await.unwrap();
assert!(none.is_empty(), "无匹配应返回空 Vec");
}
#[tokio::test(flavor = "multi_thread")]
async fn keys_includes_key_created_by_incr() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
assert_eq!(dao.incr("ki_incr_key", 60).await.unwrap(), 1);
let keys = dao.keys("ki_incr_key").await.unwrap();
assert_eq!(
keys,
vec!["ki_incr_key".to_string()],
"incr 新建的 key 应被 key_index 收录"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn keys_rename_migrates_index_entry() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("kr_old", "v", 3600).await.unwrap();
dao.rename("kr_old", "kr_new").await.unwrap();
let old_keys = dao.keys("kr_old").await.unwrap();
assert!(old_keys.is_empty(), "rename 后旧键应从 key_index 移除");
let new_keys = dao.keys("kr_new").await.unwrap();
assert_eq!(
new_keys,
vec!["kr_new".to_string()],
"rename 后新键应被 key_index 收录"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn keys_get_and_delete_cleans_index_entry() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("kg_k", "v", 3600).await.unwrap();
let v = dao.get_and_delete("kg_k").await.unwrap();
assert_eq!(v.as_deref(), Some("v"));
let keys = dao.keys("kg_k").await.unwrap();
assert!(
keys.is_empty(),
"get_and_delete 后 key 不应残留在 key_index 中"
);
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test(flavor = "multi_thread")]
async fn keys_strip_tenant_prefix_in_tenant_context() {
use crate::context::tenant::{TenantContext, TenantSource, TENANT};
let dao = GarrisonDaoOxcache::new().await.unwrap();
let ctx = TenantContext {
tenant_id: 7,
resolved_from: TenantSource::Header,
};
TENANT
.scope(ctx, async {
dao.set("tk1", "v1", 3600).await.unwrap();
dao.set("tk2", "v2", 3600).await.unwrap();
dao.set("other:k", "v3", 3600).await.unwrap();
let mut keys = dao.keys("tk*").await.unwrap();
keys.sort();
assert_eq!(
keys,
vec!["tk1".to_string(), "tk2".to_string()],
"keys() 应返回去租户前缀的原始 key 名"
);
})
.await;
}
}
#[cfg(feature = "cache-redis")]
mod redis_compat {
use super::*;
use crate::dao::RedisDeploymentMode;
fn test_redis_config() -> RedisConfig {
RedisConfig {
mode: RedisDeploymentMode::Single {
url: "redis://127.0.0.1:6379".to_string(),
},
password: None,
db: 0,
connection_timeout_secs: 5,
pool_size: 10,
}
}
#[tokio::test(flavor = "multi_thread")]
async fn with_redis_config_blocks_sync_atomic_ops() {
let dao = GarrisonDaoOxcache::new()
.await
.unwrap()
.with_redis_config(test_redis_config());
assert!(dao.redis_config().is_some(), "配置应已存储");
let r = dao.set_if_absent("rc_k", "v", 60).await;
assert!(matches!(r, Err(GarrisonError::Config(_))), "实际: {:?}", r);
let r = dao.incr("rc_k", 60).await;
assert!(matches!(r, Err(GarrisonError::Config(_))), "实际: {:?}", r);
let r = dao.decr("rc_k").await;
assert!(matches!(r, Err(GarrisonError::Config(_))), "实际: {:?}", r);
let r = dao.get_and_delete("rc_k").await;
assert!(matches!(r, Err(GarrisonError::Config(_))), "实际: {:?}", r);
let r = dao.compare_and_swap("rc_k", None, "v", 60).await;
assert!(matches!(r, Err(GarrisonError::Config(_))), "实际: {:?}", r);
let r = dao.compare_and_update_if_greater("rc_k", 1, 60).await;
assert!(matches!(r, Err(GarrisonError::Config(_))), "实际: {:?}", r);
}
#[tokio::test(flavor = "multi_thread")]
async fn eval_lua_on_memory_backend_returns_not_implemented() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let result = dao
.eval_lua("return 1", vec!["el_k".to_string()], vec![])
.await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("dao-oxcache-eval-lua")),
"内存后端 eval_lua 应返回含 'dao-oxcache-eval-lua' 的 NotImplemented 错误,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn distributed_limiter_falls_back_to_incr_with_oxcache_dao() {
use crate::limiteron::GarrisonDaoDistributedLimiter;
let dao: std::sync::Arc<dyn GarrisonDao> =
std::sync::Arc::new(GarrisonDaoOxcache::new().await.unwrap());
let limiter = GarrisonDaoDistributedLimiter::new(dao.clone());
let allowed = limiter
.atomic_check_and_incr("rc_lua_fb", 5, Duration::from_secs(60))
.await
.expect("内存后端应走 incr 降级而非报错");
assert!(allowed, "count 1 <= 5 应放行");
assert_eq!(
dao.get("rc_lua_fb").await.unwrap().as_deref(),
Some("1"),
"降级路径应经 incr 落盘计数"
);
}
#[test]
fn redis_value_to_strings_scalars() {
assert!(
redis_value_to_strings(oxcache::redis::Value::Nil).is_empty(),
"Nil → 空"
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Int(-7)),
vec!["-7"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::BulkString(b"hello".to_vec())),
vec!["hello"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::BulkString(vec![0xff])),
vec!["\u{FFFD}"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::SimpleString("PONG".to_string())),
vec!["PONG"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Okay),
vec!["OK"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Double(1.5)),
vec!["1.5"]
);
}
#[test]
fn redis_value_to_strings_composites_and_fallback() {
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Array(vec![
oxcache::redis::Value::Int(1),
oxcache::redis::Value::Array(vec![oxcache::redis::Value::Okay]),
])),
vec!["1", "OK"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Set(vec![
oxcache::redis::Value::Int(2)
])),
vec!["2"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Map(vec![(
oxcache::redis::Value::BulkString(b"k".to_vec()),
oxcache::redis::Value::Int(1),
)])),
vec!["k", "1"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Attribute {
data: Box::new(oxcache::redis::Value::Int(9)),
attributes: vec![],
}),
vec!["9"]
);
assert_eq!(
redis_value_to_strings(oxcache::redis::Value::Boolean(true)),
vec!["[unsupported redis value type]"]
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ttl_exact_after_jitter_pin() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let mut max_seen = Duration::ZERO;
for i in 0..20 {
let k = format!("jitter_pin_{i}");
dao.set(&k, "v", 60).await.unwrap();
let ttl = dao.get_timeout(&k).await.unwrap().expect("TTL 键应可读");
max_seen = max_seen.max(ttl);
}
assert!(
max_seen <= Duration::from_secs(60),
"DAO TTL 必须精确(ttl_jitter(0.0) 钉定):实测最大 {max_seen:?} > 60s,抖动回归?"
);
}
}