batata_client/config/
cache.rs

1
2use dashmap::DashMap;
3
4use crate::api::config::ConfigInfo;
5use crate::common::build_config_key;
6
7/// Local configuration cache
8pub struct ConfigCache {
9    /// Cached configurations: key -> ConfigInfo
10    configs: DashMap<String, ConfigInfo>,
11}
12
13impl ConfigCache {
14    pub fn new() -> Self {
15        Self {
16            configs: DashMap::new(),
17        }
18    }
19
20    /// Get configuration from cache
21    pub fn get(&self, data_id: &str, group: &str, tenant: &str) -> Option<ConfigInfo> {
22        let key = build_config_key(data_id, group, tenant);
23        self.configs.get(&key).map(|r| r.value().clone())
24    }
25
26    /// Put configuration into cache
27    pub fn put(&self, config: ConfigInfo) {
28        let key = config.key();
29        self.configs.insert(key, config);
30    }
31
32    /// Remove configuration from cache
33    pub fn remove(&self, data_id: &str, group: &str, tenant: &str) -> Option<ConfigInfo> {
34        let key = build_config_key(data_id, group, tenant);
35        self.configs.remove(&key).map(|(_, v)| v)
36    }
37
38    /// Check if configuration exists in cache
39    pub fn contains(&self, data_id: &str, group: &str, tenant: &str) -> bool {
40        let key = build_config_key(data_id, group, tenant);
41        self.configs.contains_key(&key)
42    }
43
44    /// Get MD5 of cached configuration
45    pub fn get_md5(&self, data_id: &str, group: &str, tenant: &str) -> Option<String> {
46        self.get(data_id, group, tenant).map(|c| c.md5)
47    }
48
49    /// Get all cached configuration keys
50    pub fn keys(&self) -> Vec<String> {
51        self.configs.iter().map(|r| r.key().clone()).collect()
52    }
53
54    /// Clear all cached configurations
55    pub fn clear(&self) {
56        self.configs.clear();
57    }
58
59    /// Get cache size
60    pub fn len(&self) -> usize {
61        self.configs.len()
62    }
63
64    /// Check if cache is empty
65    pub fn is_empty(&self) -> bool {
66        self.configs.is_empty()
67    }
68}
69
70impl Default for ConfigCache {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn test_config_cache() {
82        let cache = ConfigCache::new();
83
84        let mut config = ConfigInfo::new("test-data-id", "DEFAULT_GROUP", "");
85        config.update_content("test content");
86
87        cache.put(config.clone());
88
89        assert!(cache.contains("test-data-id", "DEFAULT_GROUP", ""));
90
91        let cached = cache.get("test-data-id", "DEFAULT_GROUP", "").unwrap();
92        assert_eq!(cached.content, "test content");
93
94        cache.remove("test-data-id", "DEFAULT_GROUP", "");
95        assert!(!cache.contains("test-data-id", "DEFAULT_GROUP", ""));
96    }
97}