cal-redis 0.1.80

Callable Redis Implementation
Documentation
// File: cal-redis/src/cache/trunk.rs

use super::CallableCache;
use crate::{get_trunk, get_trunks};
use cal_core::Trunk;
use redis::RedisError;

impl CallableCache {
    /// Retrieves all trunks for an account.
    ///
    /// # Arguments
    /// * `account_id` - Account ID
    ///
    /// # Returns
    /// * `Result<Vec<Trunk>, RedisError>` - List of trunks or a Redis error
    pub async fn get_trunks(self, account_id: &str) -> Result<Vec<Trunk>, RedisError> {
        println!("[CallableCache::get_trunks] Getting all trunks for account: {}", account_id);
        // Get from Redis and update local cache
        let trunks = get_trunks(self.remote_cache.connection.clone(), account_id).await?;
        println!("[CallableCache::get_trunks] Retrieved {} trunks from Redis", trunks.len());

        // Cache each trunk locally for future use
        for trunk in &trunks {
            let cache_key = format!("{}:{}", account_id, trunk.id);
            println!("[CallableCache::get_trunks] Caching trunk: {} with key: {}", trunk.ip, cache_key);
            self.local_cache.trunks.insert(cache_key, trunk.clone());
        }

        Ok(trunks)
    }

    /// Retrieves a specific trunk for an account.
    ///
    /// # Arguments
    /// * `account_id` - Account ID
    /// * `trunk_id` - Trunk ID to retrieve
    ///
    /// # Returns
    /// * `Result<Option<Trunk>, RedisError>` - The trunk if found, None if not found, or a Redis error
    pub async fn get_trunk(
        self,
        account_id: &str,
        trunk_id: &str,
    ) -> Result<Option<Trunk>, RedisError> {
        println!("[CallableCache::get_trunk] Getting trunk - Account: {}, Trunk ID: {}", account_id, trunk_id);
        // Try local cache first
        let cache_key = format!("{}:{}", account_id, trunk_id);
        if let Some(trunk) = self.local_cache.trunks.get(&cache_key) {
            println!("[CallableCache::get_trunk] Found trunk in local cache");
            return Ok(Some(trunk));
        }

        // If not in local cache, try Redis
        println!("[CallableCache::get_trunk] Trunk not in local cache, fetching from Redis");
        match get_trunk(self.remote_cache.connection.clone(), account_id, trunk_id).await? {
            Some(trunk) => {
                println!("[CallableCache::get_trunk] Found trunk in Redis: {}", trunk.ip);
                // Cache for future use
                self.local_cache.trunks.insert(cache_key, trunk.clone());
                Ok(Some(trunk))
            }
            None => {
                println!("[CallableCache::get_trunk] Trunk not found in Redis");
                Ok(None)
            }
        }
    }
}