use dashmap::DashMap;
use crate::api::config::ConfigInfo;
use crate::common::build_config_key;
pub struct ConfigCache {
configs: DashMap<String, ConfigInfo>,
}
impl ConfigCache {
pub fn new() -> Self {
Self {
configs: DashMap::new(),
}
}
pub fn get(&self, data_id: &str, group: &str, tenant: &str) -> Option<ConfigInfo> {
let key = build_config_key(data_id, group, tenant);
self.configs.get(&key).map(|r| r.value().clone())
}
pub fn put(&self, config: ConfigInfo) {
let key = config.key();
self.configs.insert(key, config);
}
pub fn remove(&self, data_id: &str, group: &str, tenant: &str) -> Option<ConfigInfo> {
let key = build_config_key(data_id, group, tenant);
self.configs.remove(&key).map(|(_, v)| v)
}
pub fn contains(&self, data_id: &str, group: &str, tenant: &str) -> bool {
let key = build_config_key(data_id, group, tenant);
self.configs.contains_key(&key)
}
pub fn get_md5(&self, data_id: &str, group: &str, tenant: &str) -> Option<String> {
self.get(data_id, group, tenant).map(|c| c.md5)
}
pub fn keys(&self) -> Vec<String> {
self.configs.iter().map(|r| r.key().clone()).collect()
}
pub fn clear(&self) {
self.configs.clear();
}
pub fn len(&self) -> usize {
self.configs.len()
}
pub fn is_empty(&self) -> bool {
self.configs.is_empty()
}
}
impl Default for ConfigCache {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_cache() {
let cache = ConfigCache::new();
let mut config = ConfigInfo::new("test-data-id", "DEFAULT_GROUP", "");
config.update_content("test content");
cache.put(config.clone());
assert!(cache.contains("test-data-id", "DEFAULT_GROUP", ""));
let cached = cache.get("test-data-id", "DEFAULT_GROUP", "").unwrap();
assert_eq!(cached.content, "test content");
cache.remove("test-data-id", "DEFAULT_GROUP", "");
assert!(!cache.contains("test-data-id", "DEFAULT_GROUP", ""));
}
}