batata-client 0.0.2

Rust client for Batata/Nacos service discovery and configuration management
Documentation

use dashmap::DashMap;

use crate::api::config::ConfigInfo;
use crate::common::build_config_key;

/// Local configuration cache
pub struct ConfigCache {
    /// Cached configurations: key -> ConfigInfo
    configs: DashMap<String, ConfigInfo>,
}

impl ConfigCache {
    pub fn new() -> Self {
        Self {
            configs: DashMap::new(),
        }
    }

    /// Get configuration from cache
    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())
    }

    /// Put configuration into cache
    pub fn put(&self, config: ConfigInfo) {
        let key = config.key();
        self.configs.insert(key, config);
    }

    /// Remove configuration from cache
    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)
    }

    /// Check if configuration exists in cache
    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)
    }

    /// Get MD5 of cached configuration
    pub fn get_md5(&self, data_id: &str, group: &str, tenant: &str) -> Option<String> {
        self.get(data_id, group, tenant).map(|c| c.md5)
    }

    /// Get all cached configuration keys
    pub fn keys(&self) -> Vec<String> {
        self.configs.iter().map(|r| r.key().clone()).collect()
    }

    /// Clear all cached configurations
    pub fn clear(&self) {
        self.configs.clear();
    }

    /// Get cache size
    pub fn len(&self) -> usize {
        self.configs.len()
    }

    /// Check if cache is empty
    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", ""));
    }
}