cal_redis/cache/
device.rs

1// File: cal-redis/src/cache/device.rs
2
3use crate::cache::CallableCache;
4use crate::{get_device, get_device_by_ident, get_devices};
5use cal_core::device::device::DeviceStruct;
6use redis::RedisError;
7use std::sync::Arc;
8
9impl CallableCache {
10    pub async fn get_device_by_ident(
11        self,
12        account_id: &str,
13        ident: &str,
14    ) -> Result<Option<Arc<DeviceStruct>>, RedisError> {
15        println!("[CallableCache::get_device_by_ident] Looking up device - Account: {}, Ident: {}", account_id, ident);
16        // Create a composite key for the account-device_ident combination
17        let key = format!("{}:{}", account_id, ident);
18
19        // Try to get the Device ID from the local ddi-device cache
20        if let Some(device_id) = self.local_cache.device_idents.get(&key) {
21            println!("[CallableCache::get_device_by_ident] Found device_id in local cache: {}", device_id);
22            // If we have a device ID, try to get device  from the local device cache
23            if let Some(device) = self.local_cache.devices.get(device_id.as_str()) {
24                println!("[CallableCache::get_device_by_ident] Found device in local cache");
25                self.local_cache.devices.insert(device_id, device.clone());
26                return Ok(Some(device));
27            }
28
29            // If device not in local cache, but we have the ID, fetch from Redis
30            println!("[CallableCache::get_device_by_ident] Device not in local cache, fetching from Redis");
31            match get_device(
32                self.remote_cache.connection.clone(),
33                account_id,
34                device_id.as_str(),
35            )
36                .await?
37            {
38                Some(device) => {
39                    println!("[CallableCache::get_device_by_ident] Found device in Redis: {}", device.name);
40                    // Cache the retrieved device ident for future use
41                    self.local_cache
42                        .devices
43                        .insert(device_id, Arc::new(device.clone()));
44                    self.local_cache
45                        .device_idents
46                        .insert(ident.to_string(), device.id.clone());
47                    Ok(Some(Arc::new(device)))
48                }
49                None => {
50                    println!("[CallableCache::get_device_by_ident] Device not found in Redis");
51                    Ok(None)
52                }
53            }
54        } else {
55            // If account-device_ident combination not in local cache, try Redis
56            println!("[CallableCache::get_device_by_ident] Device ident not in local cache, checking Redis");
57            match get_device_by_ident(self.remote_cache.connection.clone(), account_id, ident)
58                .await?
59            {
60                Some(device) => {
61                    println!("[CallableCache::get_device_by_ident] Found device in Redis by ident: {}", device.name);
62                    // Cache the retrieved account for future use
63                    self.local_cache
64                        .devices
65                        .insert(device.id.clone(), Arc::new(device.clone()));
66                    self.local_cache
67                        .device_idents
68                        .insert(device.id.clone().to_string(), device.id.clone());
69                    Ok(Some(Arc::new(device)))
70                }
71                None => {
72                    println!("[CallableCache::get_device_by_ident] No device found for ident");
73                    Ok(None)
74                }
75            }
76        }
77    }
78
79    /// Retrieves all devices for an account.
80    ///
81    /// # Arguments
82    /// * `account_id` - Account ID
83    ///
84    /// # Returns
85    /// * `Result<Vec<DeviceStruct>, RedisError>` - List of devices or a Redis error
86    pub async fn get_devices(self, account_id: &str) -> Result<Arc<Vec<DeviceStruct>>, RedisError> {
87        println!("[CallableCache::get_devices] Getting all devices for account: {}", account_id);
88        // Get from Redis and update local cache
89        let devices = get_devices(self.remote_cache.connection.clone(), account_id).await?;
90        println!("[CallableCache::get_devices] Retrieved {} devices from Redis", devices.len());
91
92        // Cache each device locally for future use
93        for device in &devices {
94            let cache_key = format!("{}:{}", account_id, device.id);
95            println!("[CallableCache::get_devices] Caching device: {} with key: {}", device.name, cache_key);
96            self.local_cache
97                .devices
98                .insert(cache_key, Arc::new(device.clone()));
99        }
100
101        Ok(Arc::new(devices))
102    }
103
104    /// Retrieves a specific device for an account.
105    ///
106    /// # Arguments
107    /// * `account_id` - Account ID
108    /// * `device_id` - Device ID to retrieve
109    ///
110    /// # Returns
111    /// * `Result<Option<DeviceStruct>, RedisError>` - The device if found, None if not found, or a Redis error
112    pub async fn get_device(
113        self,
114        account_id: &str,
115        device_id: &str,
116    ) -> Result<Option<Arc<DeviceStruct>>, RedisError> {
117        println!("[CallableCache::get_device] Getting device - Account: {}, Device ID: {}", account_id, device_id);
118        // Try local cache first
119        let cache_key = format!("{}:{}", account_id, device_id);
120        if let Some(device) = self.local_cache.devices.get(&cache_key) {
121            println!("[CallableCache::get_device] Found device in local cache");
122            return Ok(Some(device));
123        }
124
125        // If not in local cache, try Redis
126        println!("[CallableCache::get_device] Device not in local cache, fetching from Redis");
127        match get_device(self.remote_cache.connection.clone(), account_id, device_id).await? {
128            Some(device) => {
129                println!("[CallableCache::get_device] Found device in Redis: {}", device.name);
130                // Cache for future use
131                self.local_cache
132                    .devices
133                    .insert(cache_key, Arc::new(device.clone()));
134                Ok(Some(Arc::new(device)))
135            }
136            None => {
137                println!("[CallableCache::get_device] Device not found in Redis");
138                Ok(None)
139            }
140        }
141    }
142}