use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
mod macros;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub(crate) use macros::dao_session;
#[async_trait]
pub trait GarrisonDao: Send + Sync {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>>;
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()>;
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()>;
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()>;
async fn delete(&self, key: &str) -> GarrisonResult<()>;
async fn set_permanent(&self, key: &str, value: &str) -> GarrisonResult<()> {
self.set(key, value, 0).await
}
async fn set_if_absent(&self, key: &str, value: &str, ttl_seconds: u64)
-> GarrisonResult<bool>;
async fn get_timeout(&self, _key: &str) -> GarrisonResult<Option<Duration>> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
async fn get_with_ttl(&self, key: &str) -> GarrisonResult<Option<(String, Option<Duration>)>> {
let value = self.get(key).await?;
if value.is_none() {
return Ok(None);
}
let ttl = self.get_timeout(key).await?;
Ok(Some((value.unwrap(), ttl)))
}
async fn keys(&self, _pattern: &str) -> GarrisonResult<Vec<String>> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
async fn rename(&self, old_key: &str, new_key: &str) -> GarrisonResult<()>;
async fn get_and_delete(&self, key: &str) -> GarrisonResult<Option<String>>;
async fn incr(&self, key: &str, ttl_seconds: u64) -> GarrisonResult<u64>;
async fn decr(&self, key: &str) -> GarrisonResult<u64>;
async fn compare_and_update_if_greater(
&self,
_key: &str,
_new_value: u64,
_ttl_seconds: u64,
) -> GarrisonResult<bool> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
async fn find_social_binding(
&self,
_tenant_id: i64,
_provider: &str,
_provider_user_id: &str,
) -> GarrisonResult<Option<String>> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
async fn insert_social_binding(
&self,
_tenant_id: i64,
_login_id: &str,
_provider: &str,
_provider_user_id: &str,
_union_id: Option<&str>,
_created_at: i64,
) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn query_role_hierarchy_edges(
&self,
_tenant_id: i64,
) -> GarrisonResult<Vec<(String, String)>> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn insert_role_hierarchy_edge(
&self,
_tenant_id: i64,
_child_role: &str,
_parent_role: &str,
) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn delete_role_hierarchy_edge(
&self,
_tenant_id: i64,
_child_role: &str,
_parent_role: &str,
) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
async fn eval_lua(
&self,
_script: &str,
_keys: Vec<String>,
_args: Vec<String>,
) -> GarrisonResult<Vec<String>> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
async fn compare_and_swap(
&self,
key: &str,
expected: Option<&str>,
new_value: &str,
ttl_seconds: u64,
) -> GarrisonResult<bool>;
async fn vacuum_expired(&self) -> GarrisonResult<u64> {
Ok(0)
}
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn insert_credit_consumption(
&self,
_tenant_id: i64,
_resource: &str,
_cost: u64,
_credits: u64,
_total_consumed: u64,
_cycle_start: i64,
) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn query_credit_consumption(
&self,
_tenant_id: i64,
_from_ts: i64,
_to_ts: i64,
) -> GarrisonResult<Vec<(i64, String, u64, u64, u64, i64, i64)>> {
Err(GarrisonError::NotImplemented(format!(
"dao-not-implemented::{}",
std::any::type_name::<Self>()
)))
}
}
#[doc(hidden)]
pub mod atomic_fallback;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "lowercase")]
pub enum RedisDeploymentMode {
Single {
url: String,
},
Sentinel {
#[serde(alias = "master_name")]
primary_name: String,
urls: Vec<String>,
},
Cluster {
urls: Vec<String>,
},
#[serde(alias = "MasterSlave")]
PrimaryReplica {
primary_url: String,
replica_urls: Vec<String>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RedisConfig {
pub mode: RedisDeploymentMode,
pub password: Option<String>,
pub db: u8,
pub connection_timeout_secs: u64,
pub pool_size: u32,
}
impl RedisConfig {
pub fn warn_default_once(&self) {
use std::sync::OnceLock;
static DEFAULT_URL_WARNED: OnceLock<()> = OnceLock::new();
let is_default = matches!(
&self.mode,
RedisDeploymentMode::Single { url }
if url == "redis://127.0.0.1:6379"
);
if is_default && DEFAULT_URL_WARNED.set(()).is_ok() {
tracing::warn!(
"redis-config-using-default-url: connection will target 127.0.0.1:6379; \
configure Redis via dao config for production"
);
}
}
}
pub mod defaults;
#[cfg(any(feature = "cache-memory", feature = "cache-redis"))]
mod oxcache_impl;
#[cfg(any(feature = "cache-memory", feature = "cache-redis"))]
pub use oxcache_impl::GarrisonDaoOxcache;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
mod dbnexus_impl;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dbnexus_impl::{init_dbnexus, init_dbnexus_with_pool_config, GarrisonMigration};
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
mod dbnexus_dao;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dbnexus_dao::GarrisonDaoDbnexus;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
mod dbnexus_kv;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dbnexus_kv::DbnexusKvDao;
#[cfg(all(
feature = "listener",
any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql")
))]
mod tx;
#[cfg(all(
feature = "listener",
any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql")
))]
pub use tx::GarrisonEventTx;
pub mod repository;
#[cfg(feature = "alone-cache")]
pub mod alone_cache;
pub mod warmup;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
mod in_memory;
pub use in_memory::InMemoryDao;
#[cfg(all(test, feature = "protocol-apikey"))]
pub(crate) use in_memory::glob_match;
#[cfg(test)]
pub mod tests {
pub use super::InMemoryDao as MockDao;
use super::*;
use crate::error::GarrisonError;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
pub struct VacuumCountingDao {
inner: MockDao,
calls: std::sync::atomic::AtomicU64,
result: u64,
}
impl VacuumCountingDao {
pub fn new(result: u64) -> Self {
Self {
inner: MockDao::new(),
calls: std::sync::atomic::AtomicU64::new(0),
result,
}
}
pub fn calls(&self) -> u64 {
self.calls.load(std::sync::atomic::Ordering::SeqCst)
}
}
#[async_trait]
impl GarrisonDao for VacuumCountingDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
self.inner.get(key).await
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
self.inner.set(key, value, ttl_seconds).await
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
self.inner.update(key, value).await
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
self.inner.expire(key, seconds).await
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
self.inner.delete(key).await
}
async fn set_if_absent(
&self,
key: &str,
value: &str,
ttl_seconds: u64,
) -> GarrisonResult<bool> {
self.inner.set_if_absent(key, value, ttl_seconds).await
}
async fn rename(&self, old_key: &str, new_key: &str) -> GarrisonResult<()> {
self.inner.rename(old_key, new_key).await
}
async fn get_and_delete(&self, key: &str) -> GarrisonResult<Option<String>> {
self.inner.get_and_delete(key).await
}
async fn incr(&self, key: &str, ttl_seconds: u64) -> GarrisonResult<u64> {
self.inner.incr(key, ttl_seconds).await
}
async fn decr(&self, key: &str) -> GarrisonResult<u64> {
self.inner.decr(key).await
}
async fn compare_and_swap(
&self,
key: &str,
expected: Option<&str>,
new_value: &str,
ttl_seconds: u64,
) -> GarrisonResult<bool> {
self.inner
.compare_and_swap(key, expected, new_value, ttl_seconds)
.await
}
async fn vacuum_expired(&self) -> GarrisonResult<u64> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(self.result)
}
}
#[cfg(all(
feature = "dao-key-index",
any(feature = "cache-memory", feature = "cache-redis")
))]
mod oxcache_keys_tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn test_oxcache_keys_empty() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let keys = dao.keys("anomalous:login:*").await.unwrap();
assert!(keys.is_empty(), "无 key 时 keys() 应返回空 Vec");
}
#[tokio::test(flavor = "multi_thread")]
async fn test_oxcache_keys_pattern_match() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("anomalous:login:1:1", "v1", 3600).await.unwrap();
dao.set("anomalous:login:2:2", "v2", 3600).await.unwrap();
dao.set("other:key", "v3", 3600).await.unwrap();
let mut keys = dao.keys("anomalous:login:*").await.unwrap();
keys.sort();
assert_eq!(
keys,
vec![
"anomalous:login:1:1".to_string(),
"anomalous:login:2:2".to_string()
],
"keys() 应返回 2 个匹配 anomalous:login:* 的 key"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn test_oxcache_keys_clears_expired() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("anomalous:login:1:1", "v1", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let keys = dao.keys("anomalous:login:*").await.unwrap();
assert!(
keys.is_empty(),
"TTL 过期后 keys() 应返回空 Vec(惰性清理)"
);
let keys2 = dao.keys("anomalous:login:*").await.unwrap();
assert!(keys2.is_empty(), "清理后再次 keys() 仍应返回空");
}
#[tokio::test(flavor = "multi_thread")]
async fn test_oxcache_keys_after_delete() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("anomalous:login:1:1", "v1", 3600).await.unwrap();
let keys = dao.keys("anomalous:login:*").await.unwrap();
assert_eq!(keys.len(), 1, "set 后应有 1 个 key");
dao.delete("anomalous:login:1:1").await.unwrap();
let keys = dao.keys("anomalous:login:*").await.unwrap();
assert!(keys.is_empty(), "delete 后 keys() 应返回空 Vec");
}
#[cfg(feature = "protocol-apikey")]
#[tokio::test(flavor = "multi_thread")]
async fn test_oxcache_apikey_list_by_namespace() {
use crate::protocol::apikey::ApiKeyHandler;
let dao: Arc<dyn GarrisonDao> = Arc::new(GarrisonDaoOxcache::new().await.unwrap());
let handler = ApiKeyHandler::new(dao);
handler
.generate_with_namespace("1001", "internal", vec!["read".into()], 3600)
.await
.unwrap();
handler
.generate_with_namespace("1002", "internal", vec!["write".into()], 3600)
.await
.unwrap();
handler
.generate_with_namespace("2001", "partner", vec!["admin".into()], 3600)
.await
.unwrap();
let listed = handler.list_by_namespace("internal").await.unwrap();
assert_eq!(
listed.len(),
2,
"internal namespace 下应列出 2 个 key(非 NotImplemented)"
);
assert!(listed.iter().all(|i| i.namespace == "internal"));
}
}
#[tokio::test]
async fn mock_set_get_pair() {
let dao = MockDao::new();
dao.set("key1", "value1", 3600).await.unwrap();
let got = dao.get("key1").await.unwrap();
assert_eq!(got, Some("value1".to_string()));
}
#[tokio::test]
async fn mock_expire_auto_delete() {
let dao = MockDao::new();
dao.set("key1", "value1", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("key1").await.unwrap();
assert!(got.is_none(), "过期后 get 应返回 None");
}
#[tokio::test]
async fn mock_delete_removes_key() {
let dao = MockDao::new();
dao.set("key1", "value1", 3600).await.unwrap();
dao.delete("key1").await.unwrap();
let got = dao.get("key1").await.unwrap();
assert!(got.is_none(), "delete 后 get 应返回 None");
}
#[tokio::test]
async fn mock_update_preserves_ttl() {
let dao = MockDao::new();
dao.set("key1", "value1", 2).await.unwrap();
dao.update("key1", "value2").await.unwrap();
let got = dao.get("key1").await.unwrap();
assert_eq!(got, Some("value2".to_string()));
tokio::time::sleep(Duration::from_secs(3)).await;
let got = dao.get("key1").await.unwrap();
assert!(
got.is_none(),
"update 不应重置 TTL,原 TTL 过期后应返回 None"
);
}
#[tokio::test]
async fn mock_update_missing_key_errors() {
let dao = MockDao::new();
let result = dao.update("missing", "value").await;
assert!(
matches!(result, Err(GarrisonError::Dao(_))),
"update 不存在的键应返回 Dao 错误"
);
}
#[tokio::test]
async fn mock_expire_resets_ttl() {
let dao = MockDao::new();
dao.set("key1", "value1", 1).await.unwrap();
dao.expire("key1", 3600).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("key1").await.unwrap();
assert_eq!(got, Some("value1".to_string()));
}
#[tokio::test]
async fn mock_expire_missing_key_errors() {
let dao = MockDao::new();
let result = dao.expire("missing", 3600).await;
assert!(
matches!(result, Err(GarrisonError::Dao(_))),
"expire 不存在的键应返回 Dao 错误"
);
}
#[tokio::test]
async fn mock_set_zero_ttl_means_permanent() {
let dao = MockDao::new();
dao.set("perm", "value", 0).await.unwrap();
tokio::time::sleep(Duration::from_millis(10)).await;
let got = dao.get("perm").await.unwrap();
assert_eq!(got, Some("value".to_string()));
}
#[tokio::test]
async fn mock_get_missing_returns_none() {
let dao = MockDao::new();
let got = dao.get("never_set").await.unwrap();
assert!(got.is_none());
}
#[tokio::test]
async fn mock_dao_default_equals_new() {
let dao = MockDao::default();
dao.set("default_key", "default_value", 60).await.unwrap();
let got = dao.get("default_key").await.unwrap();
assert_eq!(got, Some("default_value".to_string()));
}
#[tokio::test]
async fn mock_expire_zero_seconds_means_permanent() {
let dao = MockDao::new();
dao.set("k", "v", 1).await.unwrap();
dao.expire("k", 0).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("k").await.unwrap();
assert_eq!(got, Some("v".to_string()), "expire(0) 应改为永久驻留");
}
#[tokio::test]
async fn mock_set_permanent_persists_value() {
let dao = MockDao::new();
dao.set_permanent("perm_key", "perm_value").await.unwrap();
let got = dao.get("perm_key").await.unwrap();
assert_eq!(got, Some("perm_value".to_string()));
}
#[tokio::test]
async fn mock_set_permanent_does_not_expire_quickly() {
let dao = MockDao::new();
dao.set_permanent("perm_key", "perm_value").await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
let got = dao.get("perm_key").await.unwrap();
assert_eq!(got, Some("perm_value".to_string()), "永久键不应过期");
}
#[tokio::test]
async fn mock_get_timeout_returns_none_for_permanent_key() {
let dao = MockDao::new();
dao.set_permanent("perm", "v").await.unwrap();
let timeout = dao.get_timeout("perm").await.unwrap();
assert!(timeout.is_none(), "永久键应返回 None");
}
#[tokio::test]
async fn mock_get_timeout_returns_some_for_ttl_key() {
let dao = MockDao::new();
dao.set("ttl_key", "v", 3600).await.unwrap();
let timeout = dao.get_timeout("ttl_key").await.unwrap();
assert!(timeout.is_some(), "TTL 键应返回 Some");
let remaining = timeout.unwrap();
assert!(
remaining <= Duration::from_secs(3600),
"剩余时间应 ≤ 原 TTL"
);
}
#[tokio::test]
async fn mock_get_timeout_returns_none_for_missing_key() {
let dao = MockDao::new();
let timeout = dao.get_timeout("missing").await.unwrap();
assert!(timeout.is_none(), "不存在的键应返回 None");
}
#[tokio::test]
async fn mock_keys_returns_namespace_matches() {
let dao = MockDao::new();
dao.set("garrison:apikey:abc123", "v1", 3600).await.unwrap();
dao.set("garrison:apikey:def456", "v2", 3600).await.unwrap();
dao.set("garrison:session:xyz", "v3", 3600).await.unwrap();
let keys = dao.keys("garrison:apikey:*").await.unwrap();
assert_eq!(keys.len(), 2, "应匹配 2 个 apikey");
assert!(keys.contains(&"garrison:apikey:abc123".to_string()));
assert!(keys.contains(&"garrison:apikey:def456".to_string()));
}
#[tokio::test]
async fn mock_keys_star_returns_all() {
let dao = MockDao::new();
dao.set("k1", "v1", 3600).await.unwrap();
dao.set("k2", "v2", 3600).await.unwrap();
let keys = dao.keys("*").await.unwrap();
assert!(keys.len() >= 2, "应至少返回 2 个 key");
}
#[tokio::test]
async fn mock_keys_no_match_returns_empty() {
let dao = MockDao::new();
dao.set("k1", "v1", 3600).await.unwrap();
let keys = dao.keys("nonexistent:*").await.unwrap();
assert!(keys.is_empty(), "无匹配应返回空 Vec");
}
#[tokio::test]
async fn mock_keys_supports_question_mark() {
let dao = MockDao::new();
dao.set("key1", "v1", 3600).await.unwrap();
dao.set("key2", "v2", 3600).await.unwrap();
dao.set("key10", "v3", 3600).await.unwrap();
let keys = dao.keys("key?").await.unwrap();
assert_eq!(
keys.len(),
2,
"? 应匹配单个字符,key1/key2 匹配,key10 不匹配"
);
}
#[tokio::test]
async fn mock_rename_moves_key() {
let dao = MockDao::new();
dao.set("old_key", "value", 3600).await.unwrap();
dao.rename("old_key", "new_key").await.unwrap();
let old = dao.get("old_key").await.unwrap();
let new = dao.get("new_key").await.unwrap();
assert!(old.is_none(), "rename 后 old_key 应不存在");
assert_eq!(new, Some("value".to_string()), "rename 后 new_key 应有值");
}
#[tokio::test]
async fn mock_rename_missing_key_returns_invalid_param() {
let dao = MockDao::new();
let result = dao.rename("missing", "new").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(_))),
"rename 不存在的键应返回 InvalidParam,实际: {:?}",
result
);
}
#[cfg(any(feature = "cache-memory", feature = "cache-redis"))]
mod oxcache_tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_set_get_pair() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_key1", "value1", 3600).await.unwrap();
let got = dao.get("oc_key1").await.unwrap();
assert_eq!(got, Some("value1".to_string()));
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_expire_auto_delete() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_key2", "value1", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("oc_key2").await.unwrap();
assert!(got.is_none(), "过期后 get 应返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_delete_removes_key() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_key3", "value1", 3600).await.unwrap();
dao.delete("oc_key3").await.unwrap();
let got = dao.get("oc_key3").await.unwrap();
assert!(got.is_none(), "delete 后 get 应返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_update_changes_value() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_key4", "value1", 3600).await.unwrap();
dao.update("oc_key4", "value2").await.unwrap();
let got = dao.get("oc_key4").await.unwrap();
assert_eq!(got, Some("value2".to_string()));
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_update_missing_key_errors() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let result = dao.update("oc_missing", "value").await;
assert!(
matches!(result, Err(GarrisonError::Dao(_))),
"update 不存在的键应返回 Dao 错误"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_update_expired_key_returns_missing_no_permanent_write() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_exp_ttl", "value1", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let result = dao.update("oc_exp_ttl", "value2").await;
assert!(
matches!(result, Err(GarrisonError::Dao(_))),
"过期键 update 应返回 Dao 错误而非写入永久值"
);
let got = dao.get("oc_exp_ttl").await.unwrap();
assert!(got.is_none(), "过期键 update 后不应存在(含永久键)");
let timeout = dao.get_timeout("oc_exp_ttl").await.unwrap();
assert!(timeout.is_none(), "过期键 update 后 timeout 应为 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_update_permanent_key_stays_permanent() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set_permanent("oc_perm", "value1").await.unwrap();
dao.update("oc_perm", "value2").await.unwrap();
let got = dao.get("oc_perm").await.unwrap();
assert_eq!(got, Some("value2".to_string()), "永久键 update 应更新值");
let timeout = dao.get_timeout("oc_perm").await.unwrap();
assert!(timeout.is_none(), "永久键 update 后 timeout 仍应为 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_incr_overflow_returns_error() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_incr_max", &u64::MAX.to_string(), 3600)
.await
.unwrap();
let result = dao.incr("oc_incr_max", 3600).await;
assert!(
matches!(result, Err(GarrisonError::Dao(_))),
"u64::MAX 自增应返回 Dao 错误而非溢出"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_expire_resets_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_key5", "value1", 1).await.unwrap();
dao.expire("oc_key5", 3600).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("oc_key5").await.unwrap();
assert_eq!(got, Some("value1".to_string()));
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_new_direct_construction() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_init", "init_value", 60).await.unwrap();
let got = dao.get("oc_init").await.unwrap();
assert_eq!(got, Some("init_value".to_string()));
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_update_preserves_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_ttl", "value1", 2).await.unwrap();
dao.update("oc_ttl", "value2").await.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let got = dao.get("oc_ttl").await.unwrap();
assert!(
got.is_none(),
"update 不应重置 TTL,原 TTL 过期后应返回 None"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_expire_zero_seconds_makes_permanent() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_perm", "value1", 1).await.unwrap();
dao.expire("oc_perm", 0).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("oc_perm").await.unwrap();
assert_eq!(
got,
Some("value1".to_string()),
"expire(0) 应将键改为永久驻留,不应过期"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_expire_zero_seconds_missing_key_errors() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let result = dao.expire("oc_missing_perm", 0).await;
assert!(
matches!(result, Err(GarrisonError::Dao(_))),
"expire(0) 不存在的键应返回 Dao 错误"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_expire_missing_key_errors() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let result = dao.expire("oc_missing_expire", 3600).await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-key-missing")),
"expire 不存在的键应返回含 'dao-key-missing' 的 Dao 错误,实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_set_with_zero_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_zero_ttl", "permanent_value", 0).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("oc_zero_ttl").await.unwrap();
assert_eq!(
got,
Some("permanent_value".to_string()),
"set(ttl=0) 应写入永久驻留的键,2 秒后仍应存在"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_set_permanent_persists_without_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set_permanent("oc_perm", "perm_value").await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get("oc_perm").await.unwrap();
assert_eq!(
got,
Some("perm_value".to_string()),
"set_permanent 应写入永久键,2 秒后仍应存在"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_get_timeout_returns_none_for_permanent_key() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set_permanent("oc_perm_ttl", "v").await.unwrap();
let timeout = dao.get_timeout("oc_perm_ttl").await.unwrap();
assert!(timeout.is_none(), "永久键应返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_get_timeout_returns_some_for_ttl_key() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_ttl_key", "v", 3600).await.unwrap();
let timeout = dao.get_timeout("oc_ttl_key").await.unwrap();
assert!(timeout.is_some(), "TTL 键应返回 Some");
let remaining = timeout.unwrap();
assert!(
remaining <= Duration::from_secs(3600),
"剩余时间应 ≤ 原 TTL"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_get_timeout_returns_none_for_missing_key() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let timeout = dao.get_timeout("oc_missing_ttl").await.unwrap();
assert!(timeout.is_none(), "不存在的键应返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_keys_behavior() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_key1", "v1", 3600).await.unwrap();
let result = dao.keys("oc_*").await;
#[cfg(feature = "dao-key-index")]
{
let keys = result.expect("dao-key-index 启用时 keys() 应返回 key 列表");
assert!(
keys.iter().any(|k| k.contains("oc_key1")),
"keys 应包含 oc_key1, 实际: {:?}",
keys
);
}
#[cfg(not(feature = "dao-key-index"))]
{
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"未启用 dao-key-index 时 keys() 应返回 NotImplemented, 实际: {:?}",
result
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_rename_moves_key() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_old", "value", 3600).await.unwrap();
dao.rename("oc_old", "oc_new").await.unwrap();
let old = dao.get("oc_old").await.unwrap();
let new = dao.get("oc_new").await.unwrap();
assert!(old.is_none(), "rename 后 oc_old 应不存在");
assert_eq!(new, Some("value".to_string()), "rename 后 oc_new 应有值");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_rename_missing_key_returns_invalid_param() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let result = dao.rename("oc_missing_old", "oc_new").await;
assert!(
result.is_err(),
"rename 不存在的键应返回错误(且不写入永久条目),实际: {:?}",
result
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_rename_preserves_ttl() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_short_ttl", "value", 2).await.unwrap();
dao.rename("oc_short_ttl", "oc_renamed").await.unwrap();
let got = dao.get("oc_renamed").await.unwrap();
assert_eq!(got, Some("value".to_string()));
tokio::time::sleep(Duration::from_secs(3)).await;
let got = dao.get("oc_renamed").await.unwrap();
assert!(
got.is_none(),
"rename 应保留原 TTL,原 TTL 过期后应返回 None"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_get_and_delete_returns_value_and_removes_key() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("oc_atomic", "value", 3600).await.unwrap();
let got = dao.get_and_delete("oc_atomic").await.unwrap();
assert_eq!(got, Some("value".to_string()));
let after = dao.get("oc_atomic").await.unwrap();
assert!(after.is_none(), "get_and_delete 后 key 应不存在");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_get_and_delete_missing_returns_none() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
let got = dao.get_and_delete("oc_missing").await.unwrap();
assert!(got.is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_get_and_delete_concurrent_only_one_succeeds() {
let dao = Arc::new(GarrisonDaoOxcache::new().await.unwrap());
dao.set("oc_concurrent", "value", 3600).await.unwrap();
let mut handles = Vec::new();
for _ in 0..10 {
let d = dao.clone();
handles.push(tokio::spawn(async move {
d.get_and_delete("oc_concurrent").await
}));
}
let mut success = 0;
let mut none_count = 0;
for handle in handles {
let result = handle.await.unwrap();
match result {
Ok(Some(_)) => success += 1,
Ok(None) => none_count += 1,
Err(e) => panic!("get_and_delete 不应返回错误: {:?}", e),
}
}
assert_eq!(success, 1, "并发调用仅一个返回 Some");
assert_eq!(none_count, 9, "其他 9 个返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_set_if_absent_concurrent_only_one_succeeds() {
let dao = Arc::new(GarrisonDaoOxcache::new().await.unwrap());
let key = "oc_set_if_absent_concurrent";
let mut handles = Vec::new();
for i in 0..10u32 {
let d = dao.clone();
let k = key.to_string();
handles.push(tokio::spawn(async move {
d.set_if_absent(&k, &format!("value_{i}"), 0).await
}));
}
let mut success = 0;
let mut already_exists = 0;
for handle in handles {
let result = handle.await.unwrap();
match result {
Ok(true) => success += 1,
Ok(false) => already_exists += 1,
Err(e) => panic!("set_if_absent 不应返回错误: {:?}", e),
}
}
assert_eq!(
success, 1,
"并发调用仅一个返回 true(写入成功),实际: {success}"
);
assert_eq!(already_exists, 9, "其他 9 个返回 false(已存在)");
}
#[tokio::test(flavor = "multi_thread")]
async fn oxcache_moka_write_then_read_visibility() {
let dao = Arc::new(GarrisonDaoOxcache::new().await.unwrap());
let mut miss = 0u32;
for i in 0..200u32 {
let key = format!("vis_test_{i}");
dao.set(&key, "v", 0).await.unwrap();
if dao.get(&key).await.unwrap().is_none() {
miss += 1;
}
}
assert_eq!(
miss, 0,
"单线程写后立即读不应 miss,实际 miss={miss}/200(Moka channel 异步写入导致写后读不一致)"
);
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test(flavor = "multi_thread")]
async fn dao_key_prefixed_with_tenant_when_isolation_enabled() {
use crate::context::tenant::{TenantContext, TenantSource, TENANT};
let dao = GarrisonDaoOxcache::new().await.unwrap();
let ctx_42 = TenantContext {
tenant_id: 42,
resolved_from: TenantSource::Header,
};
TENANT
.scope(ctx_42.clone(), async {
dao.set("shared_key", "tenant_42_value", 3600)
.await
.unwrap();
let got = dao.get("shared_key").await.unwrap();
assert_eq!(
got,
Some("tenant_42_value".to_string()),
"同租户 get 应命中 set 写入的值(前缀一致)"
);
})
.await;
let ctx_1 = TenantContext {
tenant_id: 1,
resolved_from: TenantSource::Header,
};
TENANT
.scope(ctx_1, async {
let got = dao.get("shared_key").await.unwrap();
assert!(
got.is_none(),
"跨租户 get 应返回 None(隔离失败),实际: {:?}",
got
);
dao.set("shared_key", "tenant_1_value", 3600).await.unwrap();
let got_self = dao.get("shared_key").await.unwrap();
assert_eq!(
got_self,
Some("tenant_1_value".to_string()),
"tenant 1 应读到自己的值"
);
})
.await;
TENANT
.scope(ctx_42.clone(), async {
let got = dao.get("shared_key").await.unwrap();
assert_eq!(
got,
Some("tenant_42_value".to_string()),
"tenant 42 的值不应被 tenant 1 覆盖(隔离失败)"
);
})
.await;
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test(flavor = "multi_thread")]
async fn dao_key_unchanged_when_tenant_context_absent() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
dao.set("no_ctx_key", "value", 3600).await.unwrap();
let got = dao.get("no_ctx_key").await.unwrap();
assert_eq!(
got,
Some("value".to_string()),
"TENANT 上下文不存在时 key 应保持原样(无前缀)"
);
let prefixed = dao.get("tenant:0:no_ctx_key").await.unwrap();
assert!(
prefixed.is_none(),
"TENANT 上下文不存在时不应有带前缀的 key"
);
}
#[cfg(feature = "tenant-isolation")]
#[tokio::test(flavor = "multi_thread")]
async fn dao_delete_uses_prefixed_key_in_tenant_context() {
use crate::context::tenant::{TenantContext, TenantSource, TENANT};
let dao = GarrisonDaoOxcache::new().await.unwrap();
let ctx = TenantContext {
tenant_id: 42,
resolved_from: TenantSource::Header,
};
TENANT
.scope(ctx, async {
dao.set("del_key", "value", 3600).await.unwrap();
assert_eq!(
dao.get("del_key").await.unwrap(),
Some("value".to_string()),
"set 后同租户 get 应命中"
);
dao.delete("del_key").await.unwrap();
let after = dao.get("del_key").await.unwrap();
assert!(
after.is_none(),
"delete 后同租户 get 应返回 None(delete 也加了前缀)"
);
})
.await;
}
}
#[tokio::test]
async fn mock_get_and_delete_returns_value_and_removes_key() {
let dao = MockDao::new();
dao.set("atomic_key", "value", 3600).await.unwrap();
let got = dao.get_and_delete("atomic_key").await.unwrap();
assert_eq!(got, Some("value".to_string()));
let after = dao.get("atomic_key").await.unwrap();
assert!(after.is_none(), "get_and_delete 后 key 应不存在");
}
#[tokio::test]
async fn mock_get_and_delete_missing_returns_none() {
let dao = MockDao::new();
let got = dao.get_and_delete("missing").await.unwrap();
assert!(got.is_none(), "不存在的 key 应返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn mock_get_and_delete_concurrent_only_one_succeeds() {
let dao = Arc::new(MockDao::new());
dao.set("concurrent_key", "value", 3600).await.unwrap();
let mut handles = Vec::new();
for _ in 0..10 {
let d = dao.clone();
handles.push(tokio::spawn(async move {
d.get_and_delete("concurrent_key").await
}));
}
let mut success = 0;
let mut none_count = 0;
for handle in handles {
let result = handle.await.unwrap();
match result {
Ok(Some(_)) => success += 1,
Ok(None) => none_count += 1,
Err(e) => panic!("get_and_delete 不应返回错误: {:?}", e),
}
}
assert_eq!(success, 1, "并发调用仅一个返回 Some");
assert_eq!(none_count, 9, "其他 9 个返回 None");
}
#[tokio::test(flavor = "multi_thread")]
async fn mock_decr_concurrent_only_5_effective() {
let dao = Arc::new(MockDao::new());
dao.set("counter", "5", 3600).await.unwrap();
let mut handles = Vec::new();
for _ in 0..10 {
let d = dao.clone();
handles.push(tokio::spawn(async move { d.decr("counter").await }));
}
let mut effective = 0;
let mut zero_count = 0;
for handle in handles {
let result = handle.await.unwrap();
match result {
Ok(0) => zero_count += 1,
Ok(_) => effective += 1,
Err(e) => panic!("decr 不应返回错误: {:?}", e),
}
}
assert_eq!(
effective, 4,
"4 次 decr 返回非 0(5→4→3→2→1),实际 {} 个",
effective
);
assert_eq!(
zero_count, 6,
"6 次 decr 返回 0(1 次 1→0 + 5 次 key 不存在),实际 {} 个",
zero_count
);
let final_val = dao.get("counter").await.unwrap();
assert!(
final_val.is_none(),
"decr 到 0 后 key 应被删除,实际存在: {:?}",
final_val
);
}
#[tokio::test]
async fn mock_decr_basic_semantics() {
let dao = MockDao::new();
assert_eq!(dao.decr("missing").await.unwrap(), 0);
assert!(
dao.get("missing").await.unwrap().is_none(),
"decr 不存在的 key 不应创建 key"
);
dao.set("counter", "3", 3600).await.unwrap();
assert_eq!(dao.decr("counter").await.unwrap(), 2);
assert_eq!(dao.decr("counter").await.unwrap(), 1);
assert_eq!(dao.decr("counter").await.unwrap(), 0);
assert!(
dao.get("counter").await.unwrap().is_none(),
"从 1 decr 到 0 应删除 key(new_val == 0 分支)"
);
assert_eq!(dao.decr("counter").await.unwrap(), 0);
dao.set("zero_counter", "0", 3600).await.unwrap();
assert_eq!(
dao.decr("zero_counter").await.unwrap(),
0,
"cur_val == 0 时返回 0(不递减为负)"
);
assert_eq!(
dao.get("zero_counter").await.unwrap(),
Some("0".to_string()),
"cur_val == 0 时 decr 不删除 key(提前返回,不进入 new_val == 0 分支)"
);
}
#[tokio::test]
async fn mock_decr_non_numeric_value_returns_error() {
let dao = MockDao::new();
dao.set("bad_counter", "not_a_number", 3600).await.unwrap();
let result = dao.decr("bad_counter").await;
assert!(result.is_err(), "非数字值应返回 Dao 错误");
match result.err().unwrap() {
GarrisonError::Dao(msg) => {
assert!(
msg.contains("dao-decr-parse-u64"),
"错误消息应含 dao-decr-parse-u64,实际: {}",
msg
);
},
other => panic!("期望 GarrisonError::Dao,实际: {:?}", other),
}
}
pub struct MinimalDao {
store: Mutex<HashMap<String, String>>,
}
impl Default for MinimalDao {
fn default() -> Self {
Self::new()
}
}
impl MinimalDao {
pub fn new() -> Self {
Self {
store: Mutex::new(HashMap::new()),
}
}
}
#[async_trait]
impl GarrisonDao for MinimalDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
Ok(self.store.lock().get(key).cloned())
}
async fn set(&self, key: &str, value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
self.store.lock().insert(key.to_string(), value.to_string());
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
match self.store.lock().get_mut(key) {
Some(existing) => {
*existing = value.to_string();
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-missing::{}", key))),
}
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Ok(()) }
async fn delete(&self, key: &str) -> GarrisonResult<()> {
self.store.lock().remove(key);
Ok(())
}
crate::atomic_test_fallback!();
}
#[tokio::test]
async fn default_set_permanent_delegates_to_set_with_ttl_zero() {
let dao = MinimalDao::new();
dao.set_permanent("perm_key", "perm_value").await.unwrap();
let val = dao.get("perm_key").await.unwrap();
assert_eq!(val.as_deref(), Some("perm_value"));
}
#[tokio::test]
async fn default_get_timeout_returns_not_implemented() {
let dao = MinimalDao::new();
dao.set("key", "value", 3600).await.unwrap();
let result = dao.get_timeout("key").await;
assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
}
#[tokio::test]
async fn default_keys_returns_not_implemented() {
let dao = MinimalDao::new();
dao.set("key1", "v1", 0).await.unwrap();
let result = dao.keys("*").await;
assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
}
#[tokio::test]
async fn default_vacuum_expired_returns_zero_no_op() {
let dao = MinimalDao::new();
dao.set("vacuum_default_key", "v", 0).await.unwrap();
assert_eq!(dao.vacuum_expired().await.unwrap(), 0);
assert_eq!(
dao.get("vacuum_default_key").await.unwrap().as_deref(),
Some("v"),
"no-op 默认实现不应删除任何行"
);
}
#[tokio::test]
async fn default_rename_get_set_permanent_delete() {
let dao = MinimalDao::new();
dao.set("old_key", "old_value", 0).await.unwrap();
dao.rename("old_key", "new_key").await.unwrap();
assert!(dao.get("old_key").await.unwrap().is_none());
assert_eq!(
dao.get("new_key").await.unwrap().as_deref(),
Some("old_value")
);
}
#[tokio::test]
async fn default_rename_missing_key_returns_invalid_param() {
let dao = MinimalDao::new();
let result = dao.rename("nonexistent", "new_key").await;
assert!(matches!(result, Err(GarrisonError::InvalidParam(_))));
}
#[tokio::test]
async fn default_find_social_binding_returns_not_implemented() {
let dao = MinimalDao::new();
let result = dao.find_social_binding(0, "wechat", "wx_openid").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("dao-not-implemented")),
"find_social_binding 默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn default_insert_social_binding_returns_not_implemented() {
let dao = MinimalDao::new();
let result = dao
.insert_social_binding(0, "1001", "wechat", "wx_openid", None, 1700000000)
.await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("dao-not-implemented")),
"insert_social_binding 默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn default_compare_and_update_if_greater_returns_not_implemented() {
let dao = MinimalDao::new();
let result = dao.compare_and_update_if_greater("key", 1, 60).await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("dao-not-implemented")),
"compare_and_update_if_greater 默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn decr_required_method_fallback_semantics() {
let dao = MinimalDao::new();
dao.set("counter", "5", 60).await.unwrap();
assert_eq!(dao.decr("counter").await.unwrap(), 4);
assert_eq!(
dao.get("counter").await.unwrap().as_deref(),
Some("4"),
"递减后值 > 0 时应保留 key"
);
dao.set("counter2", "1", 60).await.unwrap();
assert_eq!(dao.decr("counter2").await.unwrap(), 0);
assert!(
dao.get("counter2").await.unwrap().is_none(),
"递减后值为 0 时应删除 key"
);
}
#[tokio::test]
async fn in_memory_incr_non_numeric_value_errors_explicitly() {
let dao = InMemoryDao::new();
dao.set("rate:polluted", "not-a-number", 60).await.unwrap();
let result = dao.incr("rate:polluted", 60).await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-incr-parse-u64")),
"incr 对非数字值应显式报错而非静默重置,实际: {:?}",
result
);
assert_eq!(
dao.get("rate:polluted").await.unwrap().as_deref(),
Some("not-a-number")
);
}
#[tokio::test]
async fn default_get_and_delete_returns_value_and_removes_key() {
let dao = MinimalDao::new();
dao.set("k1", "v1", 60).await.unwrap();
let val = dao.get_and_delete("k1").await.unwrap();
assert_eq!(val, Some("v1".to_string()));
assert!(dao.get("k1").await.unwrap().is_none());
}
#[tokio::test]
async fn default_get_and_delete_missing_key_returns_none() {
let dao = MinimalDao::new();
let val = dao.get_and_delete("nope").await.unwrap();
assert!(val.is_none());
}
#[tokio::test]
async fn fallback_set_if_absent_new_key_returns_true() {
let dao = MinimalDao::new();
let ok = dao.set_if_absent("k1", "v1", 60).await.unwrap();
assert!(ok, "key 不存在时应写入成功返回 true");
assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("v1"));
}
#[tokio::test]
async fn fallback_set_if_absent_existing_key_returns_false() {
let dao = MinimalDao::new();
dao.set("k1", "original", 60).await.unwrap();
let ok = dao.set_if_absent("k1", "new_value", 60).await.unwrap();
assert!(!ok, "key 已存在时应返回 false");
assert_eq!(
dao.get("k1").await.unwrap().as_deref(),
Some("original"),
"值不应被覆盖"
);
}
#[tokio::test]
async fn fallback_cas_match_returns_true() {
let dao = MinimalDao::new();
dao.set("k1", "old", 60).await.unwrap();
let ok = dao
.compare_and_swap("k1", Some("old"), "new", 60)
.await
.unwrap();
assert!(ok, "值匹配时 CAS 应返回 true");
assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("new"));
}
#[tokio::test]
async fn fallback_cas_mismatch_returns_false() {
let dao = MinimalDao::new();
dao.set("k1", "actual", 60).await.unwrap();
let ok = dao
.compare_and_swap("k1", Some("expected"), "new", 60)
.await
.unwrap();
assert!(!ok, "值不匹配时 CAS 应返回 false");
assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("actual"));
}
#[tokio::test]
async fn fallback_cas_none_expected_absent_creates() {
let dao = MinimalDao::new();
let ok = dao
.compare_and_swap("k1", None, "initial", 60)
.await
.unwrap();
assert!(ok, "key 不存在 + expected=None 时应成功");
assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("initial"));
}
#[tokio::test]
async fn fallback_cas_permanent_ttl_uses_set_permanent() {
let dao = MinimalDao::new();
let ok = dao.compare_and_swap("k1", None, "perm", 0).await.unwrap();
assert!(ok);
assert_eq!(dao.get("k1").await.unwrap().as_deref(), Some("perm"));
}
#[tokio::test]
async fn fallback_incr_new_key_initializes_to_one() {
let dao = MinimalDao::new();
let val = dao.incr("counter", 60).await.unwrap();
assert_eq!(val, 1, "新键应初始化为 1");
}
#[tokio::test]
async fn fallback_incr_existing_key_increments() {
let dao = MinimalDao::new();
dao.set("counter", "10", 60).await.unwrap();
let val = dao.incr("counter", 60).await.unwrap();
assert_eq!(val, 11, "已存在键 10 应递增为 11");
}
#[tokio::test]
async fn fallback_incr_non_numeric_returns_error() {
let dao = MinimalDao::new();
dao.set("bad", "not_num", 60).await.unwrap();
let result = dao.incr("bad", 60).await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref m)) if m.contains("dao-incr-parse-u64")),
"非数字值应返回 Dao 错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn fallback_decr_missing_key_returns_zero() {
let dao = MinimalDao::new();
let val = dao.decr("nope").await.unwrap();
assert_eq!(val, 0, "key 不存在时应返回 0");
}
#[tokio::test]
async fn fallback_decr_zero_returns_zero() {
let dao = MinimalDao::new();
dao.set("counter", "0", 60).await.unwrap();
let val = dao.decr("counter").await.unwrap();
assert_eq!(val, 0, "值为 0 时应返回 0");
}
#[tokio::test]
async fn fallback_rename_missing_key_errors() {
let dao = MinimalDao::new();
let result = dao.rename("nope", "new_key").await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("dao-key-missing")),
"key 不存在时 rename 应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn default_get_with_ttl_existing_key_returns_value() {
let dao = MinimalDao::new();
dao.set("k1", "v1", 3600).await.unwrap();
let result = dao.get_with_ttl("k1").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(_))),
"MinimalDao get_with_ttl 应传播 get_timeout 的 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn default_get_with_ttl_missing_key_returns_none() {
let dao = MinimalDao::new();
let result = dao.get_with_ttl("nope").await.unwrap();
assert!(result.is_none(), "不存在的键应返回 None");
}
#[tokio::test]
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn default_query_role_hierarchy_edges_returns_not_implemented() {
let dao = MinimalDao::new();
let result = dao.query_role_hierarchy_edges(0).await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref m)) if m.contains("dao-not-implemented")),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn default_insert_role_hierarchy_edge_returns_not_implemented() {
let dao = MinimalDao::new();
let result = dao.insert_role_hierarchy_edge(0, "admin", "owner").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref m)) if m.contains("dao-not-implemented")),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
async fn default_delete_role_hierarchy_edge_returns_not_implemented() {
let dao = MinimalDao::new();
let result = dao.delete_role_hierarchy_edge(0, "admin", "owner").await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref m)) if m.contains("dao-not-implemented")),
"默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[test]
fn redis_config_default_returns_single_mode() {
let config = RedisConfig::default();
assert_eq!(
config.mode,
RedisDeploymentMode::Single {
url: "redis://127.0.0.1:6379".to_string()
}
);
assert_eq!(config.password, None);
assert_eq!(config.db, 0);
assert_eq!(config.connection_timeout_secs, 5);
assert_eq!(config.pool_size, 10);
}
#[test]
fn redis_config_serde_roundtrip() {
let config = RedisConfig {
mode: RedisDeploymentMode::Cluster {
urls: vec![
"redis://10.0.0.1:6379".to_string(),
"redis://10.0.0.2:6379".to_string(),
"redis://10.0.0.3:6379".to_string(),
],
},
password: Some("secret".to_string()),
db: 1,
connection_timeout_secs: 10,
pool_size: 20,
};
let json = serde_json::to_string(&config).unwrap();
let deserialized: RedisConfig = serde_json::from_str(&json).unwrap();
assert_eq!(config.mode, deserialized.mode);
assert_eq!(config.password, deserialized.password);
assert_eq!(config.db, deserialized.db);
assert_eq!(
config.connection_timeout_secs,
deserialized.connection_timeout_secs
);
assert_eq!(config.pool_size, deserialized.pool_size);
}
#[test]
fn redis_config_serde_partial_override() {
let json = r#"{"mode":{"mode":"cluster","urls":["redis://10.0.0.1:6379"]}}"#;
let config: RedisConfig = serde_json::from_str(json).unwrap();
match config.mode {
RedisDeploymentMode::Cluster { urls } => {
assert_eq!(urls, vec!["redis://10.0.0.1:6379".to_string()]);
},
_ => panic!("期望 Cluster 模式"),
}
assert_eq!(config.password, None);
assert_eq!(config.db, 0);
assert_eq!(config.connection_timeout_secs, 5);
assert_eq!(config.pool_size, 10);
}
#[test]
fn redis_deployment_mode_display() {
let single = RedisDeploymentMode::Single {
url: "redis://127.0.0.1:6379".to_string(),
};
assert!(format!("{}", single).contains("single"));
assert!(format!("{}", single).contains("redis://127.0.0.1:6379"));
let sentinel = RedisDeploymentMode::Sentinel {
primary_name: "mymaster".to_string(),
urls: vec!["redis://s1:26379".to_string()],
};
let s = format!("{}", sentinel);
assert!(s.contains("sentinel"));
assert!(s.contains("mymaster"));
let cluster = RedisDeploymentMode::Cluster {
urls: vec!["redis://c1:6379".to_string(), "redis://c2:6379".to_string()],
};
let c = format!("{}", cluster);
assert!(c.contains("cluster"));
assert!(c.contains("2 nodes"));
let ms = RedisDeploymentMode::PrimaryReplica {
primary_url: "redis://primary:6379".to_string(),
replica_urls: vec!["redis://replica1:6379".to_string()],
};
let m = format!("{}", ms);
assert!(m.contains("primary-replica"));
assert!(m.contains("primary:6379"));
assert!(m.contains("1 replicas"));
}
#[test]
fn redis_deployment_mode_eq() {
let a = RedisDeploymentMode::Single {
url: "redis://127.0.0.1:6379".to_string(),
};
let b = RedisDeploymentMode::Single {
url: "redis://127.0.0.1:6379".to_string(),
};
let c = RedisDeploymentMode::Single {
url: "redis://10.0.0.1:6379".to_string(),
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[cfg(feature = "cache-redis")]
#[tokio::test(flavor = "multi_thread")]
async fn with_redis_config_stores_config() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
assert!(
dao.redis_config().is_none(),
"新建实例的 redis_config 应为 None"
);
let config = RedisConfig {
mode: RedisDeploymentMode::Sentinel {
primary_name: "mymaster".to_string(),
urls: vec![
"redis://s1:26379".to_string(),
"redis://s2:26379".to_string(),
"redis://s3:26379".to_string(),
],
},
password: Some("pass123".to_string()),
db: 2,
connection_timeout_secs: 15,
pool_size: 50,
};
let dao = dao.with_redis_config(config);
let stored = dao.redis_config().expect("with_redis_config 后应有配置");
assert!(matches!(
&stored.mode,
RedisDeploymentMode::Sentinel { primary_name, urls }
if primary_name == "mymaster" && urls.len() == 3
));
assert_eq!(stored.password, Some("pass123".to_string()));
assert_eq!(stored.db, 2);
assert_eq!(stored.connection_timeout_secs, 15);
assert_eq!(stored.pool_size, 50);
}
#[cfg(feature = "cache-redis")]
#[tokio::test(flavor = "multi_thread")]
async fn without_redis_config_returns_none() {
let dao = GarrisonDaoOxcache::new().await.unwrap();
assert!(
dao.redis_config().is_none(),
"未调用 with_redis_config 时 redis_config 应为 None"
);
}
#[tokio::test]
async fn default_incr_initializes_new_key() {
let dao = MinimalDao::new();
let result = dao.incr("counter", 3600).await.unwrap();
assert_eq!(result, 1, "新键应初始化为 1");
let val = dao.get("counter").await.unwrap();
assert_eq!(val.as_deref(), Some("1"));
}
#[tokio::test]
async fn default_incr_increments_existing_key() {
let dao = MinimalDao::new();
dao.set("counter", "5", 3600).await.unwrap();
let result = dao.incr("counter", 3600).await.unwrap();
assert_eq!(result, 6, "已存在键 5 应递增为 6");
let result = dao.incr("counter", 3600).await.unwrap();
assert_eq!(result, 7, "已存在键 6 应递增为 7");
}
#[tokio::test]
async fn default_incr_rejects_non_numeric_value() {
let dao = MinimalDao::new();
dao.set("bad_counter", "not_a_number", 3600).await.unwrap();
let result = dao.incr("bad_counter", 3600).await;
assert!(
result.is_err(),
"非数字值必须显式报错,禁止静默回退为 0 导致计数器重置(Rule 12)"
);
}
#[tokio::test]
async fn default_eval_lua_returns_not_implemented() {
let dao = MinimalDao::new();
let result = dao
.eval_lua("return 1", vec!["k".to_string()], vec!["a".to_string()])
.await;
assert!(
matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("dao-not-implemented")),
"eval_lua 默认实现应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn minimal_dao_default_equals_new() {
let dao = MinimalDao::default();
dao.set("k", "v", 60).await.unwrap();
let got = dao.get("k").await.unwrap();
assert_eq!(got.as_deref(), Some("v"));
}
#[tokio::test]
async fn cas_match_replaces_value() {
let dao = MockDao::new();
dao.set("k", "old", 60).await.unwrap();
let ok = dao
.compare_and_swap("k", Some("old"), "new", 60)
.await
.unwrap();
assert!(ok, "值匹配时 CAS 应返回 true");
assert_eq!(dao.get("k").await.unwrap().as_deref(), Some("new"));
}
#[tokio::test]
async fn cas_mismatch_returns_false() {
let dao = MockDao::new();
dao.set("k", "actual", 60).await.unwrap();
let ok = dao
.compare_and_swap("k", Some("expected"), "new", 60)
.await
.unwrap();
assert!(!ok, "值不匹配时 CAS 应返回 false");
assert_eq!(
dao.get("k").await.unwrap().as_deref(),
Some("actual"),
"值不应被修改"
);
}
#[tokio::test]
async fn cas_none_expected_key_absent_creates() {
let dao = MockDao::new();
let ok = dao
.compare_and_swap("k", None, "initial", 60)
.await
.unwrap();
assert!(ok, "key 不存在 + expected=None 时 CAS 应成功");
assert_eq!(dao.get("k").await.unwrap().as_deref(), Some("initial"));
}
#[tokio::test]
async fn cas_none_expected_key_exists_returns_false() {
let dao = MockDao::new();
dao.set("k", "existing", 60).await.unwrap();
let ok = dao.compare_and_swap("k", None, "new", 60).await.unwrap();
assert!(!ok, "key 已存在 + expected=None 时 CAS 应返回 false");
assert_eq!(dao.get("k").await.unwrap().as_deref(), Some("existing"));
}
#[tokio::test]
async fn cas_some_expected_key_absent_returns_false() {
let dao = MockDao::new();
let ok = dao
.compare_and_swap("k", Some("old"), "new", 60)
.await
.unwrap();
assert!(!ok, "key 不存在 + expected=Some 时 CAS 应返回 false");
assert!(dao.get("k").await.unwrap().is_none(), "不应创建 key");
}
#[tokio::test]
async fn cas_permanent_ttl() {
let dao = MockDao::new();
let ok = dao
.compare_and_swap("k", None, "permanent", 0)
.await
.unwrap();
assert!(ok);
assert_eq!(dao.get("k").await.unwrap().as_deref(), Some("permanent"));
}
#[tokio::test]
async fn cas_concurrent_only_one_succeeds() {
let mock = MockDao::new();
mock.set("k", "v1", 60).await.unwrap();
let dao = Arc::new(mock);
let dao1 = dao.clone();
let dao2 = dao.clone();
let (r1, r2) = tokio::join!(
dao1.compare_and_swap("k", Some("v1"), "from-task-1", 60),
dao2.compare_and_swap("k", Some("v1"), "from-task-2", 60),
);
let ok1 = r1.unwrap();
let ok2 = r2.unwrap();
assert!(
ok1 ^ ok2,
"并发 CAS 同一值应仅一个成功(XOR),实际: ok1={}, ok2={}",
ok1,
ok2
);
}
#[test]
fn redis_deployment_mode_default_returns_single_localhost() {
let mode = RedisDeploymentMode::default();
assert_eq!(
mode,
RedisDeploymentMode::Single {
url: "redis://127.0.0.1:6379".to_string()
}
);
assert!(
format!("{}", mode).starts_with("single("),
"默认模式 Display 应以 'single(' 开头,实际: {}",
mode
);
}
#[tokio::test]
async fn in_memory_get_timeout_returns_none_after_expiry() {
let dao = MockDao::new();
dao.set("exp_ttl", "v", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let timeout = dao.get_timeout("exp_ttl").await.unwrap();
assert!(timeout.is_none(), "已过期键的 get_timeout 应返回 None");
}
#[tokio::test]
async fn in_memory_keys_skips_expired_keys() {
let dao = MockDao::new();
dao.set("expired_key", "v1", 1).await.unwrap();
dao.set_permanent("alive_key", "v2").await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let keys = dao.keys("*").await.unwrap();
assert!(
!keys.iter().any(|k| k == "expired_key"),
"已过期 key 不应出现在 keys() 结果中,实际: {:?}",
keys
);
assert!(
keys.iter().any(|k| k == "alive_key"),
"存活 key 应出现在 keys() 结果中"
);
}
#[tokio::test]
async fn in_memory_get_and_delete_expired_returns_none() {
let dao = MockDao::new();
dao.set("gd_expired", "v", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let got = dao.get_and_delete("gd_expired").await.unwrap();
assert!(got.is_none(), "已过期 key 的 get_and_delete 应返回 None");
}
#[tokio::test]
async fn in_memory_set_if_absent_reclaims_after_expiry() {
let dao = MockDao::new();
dao.set("sia_key", "old", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
let claimed = dao.set_if_absent("sia_key", "new", 3600).await.unwrap();
assert!(claimed, "key 过期后 set_if_absent 应重新获准写入");
assert_eq!(dao.get("sia_key").await.unwrap().as_deref(), Some("new"));
}
#[tokio::test]
async fn in_memory_set_if_absent_existing_permanent_returns_false() {
let dao = MockDao::new();
dao.set_permanent("sia_perm", "v").await.unwrap();
let claimed = dao.set_if_absent("sia_perm", "w", 3600).await.unwrap();
assert!(!claimed, "已存在的永久键 set_if_absent 应返回 false");
}
#[tokio::test]
async fn in_memory_incr_initializes_new_key_with_ttl() {
let dao = MockDao::new();
let v = dao.incr("incr_new", 3600).await.unwrap();
assert_eq!(v, 1, "新键 incr 应初始化为 1");
let timeout = dao.get_timeout("incr_new").await.unwrap();
assert!(timeout.is_some(), "incr 初始化应设置 TTL");
}
#[tokio::test]
async fn in_memory_increments_permanent_key_keeps_permanent() {
let dao = MockDao::new();
dao.set_permanent("incr_perm", "5").await.unwrap();
let v = dao.incr("incr_perm", 3600).await.unwrap();
assert_eq!(v, 6);
let timeout = dao.get_timeout("incr_perm").await.unwrap();
assert!(timeout.is_none(), "永久键 incr 不应新增 TTL");
}
#[tokio::test]
async fn in_memory_incr_parse_error_returns_dao_error() {
let dao = MockDao::new();
dao.set("incr_bad", "not-a-number", 3600).await.unwrap();
let result = dao.incr("incr_bad", 3600).await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-incr-parse-u64")),
"非数字现存值 incr 应返回 dao-incr-parse-u64 错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn in_memory_incr_overflow_returns_error() {
let dao = MockDao::new();
dao.set("incr_max", &u64::MAX.to_string(), 3600)
.await
.unwrap();
let result = dao.incr("incr_max", 3600).await;
assert!(
matches!(
result,
Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-incr-overflow-u64")
),
"u64::MAX 自增应返回 dao-incr-overflow-u64 错误,实际: {:?}",
result
);
}
#[tokio::test]
async fn in_memory_decr_semantics_matrix() {
let dao = MockDao::new();
assert_eq!(dao.decr("decr_missing").await.unwrap(), 0);
dao.set("decr_expired", "3", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
assert_eq!(dao.decr("decr_expired").await.unwrap(), 0);
assert!(dao.get("decr_expired").await.unwrap().is_none());
dao.set_permanent("decr_zero", "0").await.unwrap();
assert_eq!(dao.decr("decr_zero").await.unwrap(), 0);
dao.set("decr_to_zero", "1", 3600).await.unwrap();
assert_eq!(dao.decr("decr_to_zero").await.unwrap(), 0);
assert!(dao.get("decr_to_zero").await.unwrap().is_none());
dao.set("decr_keep_ttl", "3", 3600).await.unwrap();
assert_eq!(dao.decr("decr_keep_ttl").await.unwrap(), 2);
let timeout = dao.get_timeout("decr_keep_ttl").await.unwrap();
assert!(timeout.is_some(), "decr 后应保留原 TTL");
}
#[tokio::test]
async fn in_memory_decr_parse_error_returns_dao_error() {
let dao = MockDao::new();
dao.set("decr_bad_ttl", "abc", 3600).await.unwrap();
let result = dao.decr("decr_bad_ttl").await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-decr-parse-u64")),
"TTL 键 parse 失败应返回 dao-decr-parse-u64,实际: {:?}",
result
);
dao.set_permanent("decr_bad_perm", "xyz").await.unwrap();
let result = dao.decr("decr_bad_perm").await;
assert!(
matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-decr-parse-u64")),
"永久键 parse 失败应返回 dao-decr-parse-u64,实际: {:?}",
result
);
}
#[tokio::test]
async fn in_memory_compare_and_update_if_greater_matrix() {
let dao = MockDao::new();
assert!(dao
.compare_and_update_if_greater("nc_new", 5, 60)
.await
.unwrap());
assert_eq!(dao.get("nc_new").await.unwrap().as_deref(), Some("5"));
assert!(dao.get_timeout("nc_new").await.unwrap().is_some());
assert!(dao
.compare_and_update_if_greater("nc_new", 8, 60)
.await
.unwrap());
assert_eq!(dao.get("nc_new").await.unwrap().as_deref(), Some("8"));
assert!(!dao
.compare_and_update_if_greater("nc_new", 8, 60)
.await
.unwrap());
assert_eq!(dao.get("nc_new").await.unwrap().as_deref(), Some("8"));
dao.set_permanent("nc_perm", "1").await.unwrap();
assert!(dao
.compare_and_update_if_greater("nc_perm", 2, 60)
.await
.unwrap());
assert_eq!(dao.get("nc_perm").await.unwrap().as_deref(), Some("2"));
assert!(
dao.get_timeout("nc_perm").await.unwrap().is_some(),
"现实现将永久键升级为 TTL 键(与 incr 的永久键语义不一致,见注释)"
);
dao.set("nc_bad_ttl", "oops", 3600).await.unwrap();
let result = dao.compare_and_update_if_greater("nc_bad_ttl", 9, 60).await;
assert!(
matches!(
result,
Err(GarrisonError::Dao(ref msg))
if msg.contains("dao-compare-and-update-parse-u64")
),
"TTL 键 parse 失败应显性报错,实际: {:?}",
result
);
dao.set_permanent("nc_bad_perm", "oops").await.unwrap();
let result = dao
.compare_and_update_if_greater("nc_bad_perm", 9, 60)
.await;
assert!(
matches!(
result,
Err(GarrisonError::Dao(ref msg))
if msg.contains("dao-compare-and-update-parse-u64")
),
"永久键 parse 失败应显性报错,实际: {:?}",
result
);
dao.set("nc_expired", "7", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
assert!(dao
.compare_and_update_if_greater("nc_expired", 3, 60)
.await
.unwrap());
assert_eq!(dao.get("nc_expired").await.unwrap().as_deref(), Some("3"));
}
#[tokio::test]
async fn in_memory_compare_and_swap_matrix() {
let dao = MockDao::new();
assert!(dao
.compare_and_swap("cas_new", None, "v1", 3600)
.await
.unwrap());
assert!(dao.get_timeout("cas_new").await.unwrap().is_some());
assert!(!dao
.compare_and_swap("cas_new", Some("wrong"), "v2", 3600)
.await
.unwrap());
assert_eq!(dao.get("cas_new").await.unwrap().as_deref(), Some("v1"));
assert!(dao
.compare_and_swap("cas_new", Some("v1"), "v2", 3600)
.await
.unwrap());
assert_eq!(dao.get("cas_new").await.unwrap().as_deref(), Some("v2"));
assert!(!dao
.compare_and_swap("cas_new", None, "v3", 3600)
.await
.unwrap());
dao.set("cas_expired", "old", 1).await.unwrap();
tokio::time::sleep(Duration::from_secs(2)).await;
assert!(dao
.compare_and_swap("cas_expired", None, "fresh", 0)
.await
.unwrap());
assert!(dao.get_timeout("cas_expired").await.unwrap().is_none());
assert_eq!(
dao.get("cas_expired").await.unwrap().as_deref(),
Some("fresh")
);
}
#[tokio::test]
async fn in_memory_eval_lua_incr_mode() {
let dao = MockDao::new();
let script =
"local v = redis.call('INCR', KEYS[1]) redis.call('EXPIRE', KEYS[1], ARGV[2]) return v";
let keys = vec!["lua_incr_key".to_string()];
let r1 = dao
.eval_lua(
script,
keys.clone(),
vec!["ignored".to_string(), "600".to_string()],
)
.await
.unwrap();
assert_eq!(r1, vec!["1".to_string()]);
let r2 = dao
.eval_lua(
script,
keys.clone(),
vec!["ignored".to_string(), "600".to_string()],
)
.await
.unwrap();
assert_eq!(r2, vec!["2".to_string()], "连续 eval_lua 应递增计数");
assert!(dao.get_timeout("lua_incr_key").await.unwrap().is_some());
}
#[tokio::test]
async fn in_memory_eval_lua_incr_mode_param_validation() {
let dao = MockDao::new();
let script = "INCR + EXPIRE";
let result = dao
.eval_lua(script, vec![], vec!["0".to_string(), "600".to_string()])
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.contains("missing-keys-1")),
"缺 KEYS[1] 应返回 InvalidParam,实际: {:?}",
result
);
let result = dao
.eval_lua(script, vec!["k".to_string()], vec!["0".to_string()])
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.contains("argv-2-ttl")),
"缺 ARGV[2] 应返回 InvalidParam,实际: {:?}",
result
);
let result = dao
.eval_lua(
script,
vec!["k".to_string()],
vec!["0".to_string(), "not-a-number".to_string()],
)
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.contains("parse-failed")),
"ARGV[2] 非数字应返回 parse-failed InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn in_memory_eval_lua_sliding_window_threshold_and_filter() {
let dao = MockDao::new();
let script = "redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', window_start)";
let key = "lua_sliding_key".to_string();
let keys = vec![key.clone(), format!("{key}:seq")];
let window_ms: u64 = 5_000;
let args = vec![window_ms.to_string(), "2".to_string()];
dao.set_permanent(&key, "1,5000,4999").await.unwrap();
let out = dao
.eval_lua(script, keys.clone(), args.clone())
.await
.unwrap();
assert_eq!(
(out[0].as_str(), out[1].as_str()),
("1", "0"),
"旧时间戳被过滤后未达阈值应放行(allowed/count)"
);
let out = dao
.eval_lua(script, keys.clone(), args.clone())
.await
.unwrap();
assert_eq!(
(out[0].as_str(), out[1].as_str()),
("1", "1"),
"窗口内第 2 个时间戳仍应放行"
);
let out = dao.eval_lua(script, keys, args).await.unwrap();
assert_eq!(
(out[0].as_str(), out[1].as_str()),
("0", "2"),
"达到阈值后应拦截(count 保持,不追加)"
);
let reset: u64 = out[2].parse().expect("reset_time 应为可解析的 u64");
assert!(reset > 0, "reset_time 应非零");
}
#[tokio::test]
async fn in_memory_eval_lua_sliding_window_same_ms_no_overwrite() {
let dao = MockDao::new();
let script = "ZREMRANGEBYSCORE";
let now: u64 = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let key = "lua_same_ms".to_string();
dao.set_permanent(&key, &format!("{now},{now}"))
.await
.unwrap();
let keys = vec![key.clone(), format!("{key}:seq")];
let out = dao
.eval_lua(script, keys, vec!["5000".to_string(), "2".to_string()])
.await
.unwrap();
assert_eq!(
(out[0].as_str(), out[1].as_str()),
("0", "2"),
"同毫秒两个成员都应计数(max=2 即拦),覆盖语义会使 count 只到 1"
);
}
#[tokio::test]
async fn in_memory_eval_lua_sliding_window_param_validation() {
let dao = MockDao::new();
let script = "ZREMRANGEBYSCORE";
let result = dao
.eval_lua(script, vec![], vec!["1".to_string(), "1".to_string()])
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.contains("rl-missing-keys-1")),
"缺 KEYS[1] 应返回 InvalidParam,实际: {:?}",
result
);
let result = dao
.eval_lua(
script,
vec!["k".to_string()],
vec!["1".to_string(), "1".to_string()],
)
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.contains("rl-missing-keys-2-seq")),
"缺 KEYS[2] 应返回 InvalidParam,实际: {:?}",
result
);
let result = dao
.eval_lua(
script,
vec!["k".to_string(), "k:seq".to_string()],
vec!["nan".to_string(), "1".to_string()],
)
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.contains("parse-failed")),
"ARGV[1] 非数字应返回 parse-failed InvalidParam,实际: {:?}",
result
);
let result = dao
.eval_lua(
script,
vec!["k".to_string(), "k:seq".to_string()],
vec!["1".to_string(), "nan".to_string()],
)
.await;
assert!(
matches!(result, Err(GarrisonError::InvalidParam(ref msg)) if msg.contains("rl-argv-2-max")),
"ARGV[2] 非数字应返回 InvalidParam,实际: {:?}",
result
);
}
#[tokio::test]
async fn in_memory_eval_lua_unsupported_script_returns_not_implemented() {
let dao = MockDao::new();
let result = dao
.eval_lua(
"return redis.call('GET', KEYS[1])",
vec!["k".to_string()],
vec![],
)
.await;
assert!(
matches!(
result,
Err(GarrisonError::NotImplemented(ref msg))
if msg.contains("dao-eval-lua-unsupported-script")
),
"不支持的脚本应返回 NotImplemented,实际: {:?}",
result
);
}
#[tokio::test]
async fn in_memory_eval_lua_sliding_window_sets_window_ttl() {
let dao = MockDao::new();
let script = "ZREMRANGEBYSCORE";
let keys = vec![
"lua_sliding_perm".to_string(),
"lua_sliding_perm:seq".to_string(),
];
let args = vec!["5000".to_string(), u64::MAX.to_string()];
assert_eq!(
dao.eval_lua(script, keys, args).await.unwrap()[0],
"1".to_string(),
"未达阈值应放行"
);
assert!(
dao.get_timeout("lua_sliding_perm").await.unwrap().is_some(),
"sliding window 写入的键应带窗口推导 TTL(非永久键)"
);
}
}