cal_redis/cache/
trunk.rs

1// File: cal-redis/src/cache/trunk.rs
2
3use super::CallableCache;
4use crate::{get_trunk, get_trunks};
5use cal_core::Trunk;
6use redis::RedisError;
7
8impl CallableCache {
9    /// Retrieves all trunks for an account.
10    ///
11    /// # Arguments
12    /// * `account_id` - Account ID
13    ///
14    /// # Returns
15    /// * `Result<Vec<Trunk>, RedisError>` - List of trunks or a Redis error
16    pub async fn get_trunks(self, account_id: &str) -> Result<Vec<Trunk>, RedisError> {
17        println!("[CallableCache::get_trunks] Getting all trunks for account: {}", account_id);
18        // Get from Redis and update local cache
19        let trunks = get_trunks(self.remote_cache.connection.clone(), account_id).await?;
20        println!("[CallableCache::get_trunks] Retrieved {} trunks from Redis", trunks.len());
21
22        // Cache each trunk locally for future use
23        for trunk in &trunks {
24            let cache_key = format!("{}:{}", account_id, trunk.id);
25            println!("[CallableCache::get_trunks] Caching trunk: {} with key: {}", trunk.ip, cache_key);
26            self.local_cache.trunks.insert(cache_key, trunk.clone());
27        }
28
29        Ok(trunks)
30    }
31
32    /// Retrieves a specific trunk for an account.
33    ///
34    /// # Arguments
35    /// * `account_id` - Account ID
36    /// * `trunk_id` - Trunk ID to retrieve
37    ///
38    /// # Returns
39    /// * `Result<Option<Trunk>, RedisError>` - The trunk if found, None if not found, or a Redis error
40    pub async fn get_trunk(
41        self,
42        account_id: &str,
43        trunk_id: &str,
44    ) -> Result<Option<Trunk>, RedisError> {
45        println!("[CallableCache::get_trunk] Getting trunk - Account: {}, Trunk ID: {}", account_id, trunk_id);
46        // Try local cache first
47        let cache_key = format!("{}:{}", account_id, trunk_id);
48        if let Some(trunk) = self.local_cache.trunks.get(&cache_key) {
49            println!("[CallableCache::get_trunk] Found trunk in local cache");
50            return Ok(Some(trunk));
51        }
52
53        // If not in local cache, try Redis
54        println!("[CallableCache::get_trunk] Trunk not in local cache, fetching from Redis");
55        match get_trunk(self.remote_cache.connection.clone(), account_id, trunk_id).await? {
56            Some(trunk) => {
57                println!("[CallableCache::get_trunk] Found trunk in Redis: {}", trunk.ip);
58                // Cache for future use
59                self.local_cache.trunks.insert(cache_key, trunk.clone());
60                Ok(Some(trunk))
61            }
62            None => {
63                println!("[CallableCache::get_trunk] Trunk not found in Redis");
64                Ok(None)
65            }
66        }
67    }
68}