cal_redis/cache/
proxy.rs

1// File: cal-redis/src/cache/proxy.rs
2
3use super::CallableCache;
4use crate::proxy::{get_proxies, get_proxy_by_id};
5use cal_core::Proxy;
6use redis::RedisError;
7use std::sync::Arc;
8
9impl CallableCache {
10    /// Retrieves a proxy by its ID, first checking the local cache and then Redis.
11    ///
12    /// # Arguments
13    /// * `id` - Proxy ID to look up
14    ///
15    /// # Returns
16    /// * `Result<Option<Proxy>, RedisError>` - Proxy if found, None if not found, or a Redis error
17    pub async fn get_proxy_by_id(&mut self, id: &str) -> Result<Option<Arc<Proxy>>, RedisError> {
18        println!("[CallableCache::get_proxy_by_id] Getting proxy by ID: {}", id);
19        if let Some(proxy) = self.local_cache.proxies.get(id) {
20            println!("[CallableCache::get_proxy_by_id] Found proxy in local cache");
21            Ok(Some(proxy))
22        } else {
23            // If proxy identifier not in local cache, try Redis
24            println!("[CallableCache::get_proxy_by_id] Proxy not in local cache, fetching from Redis");
25            match get_proxy_by_id(self.remote_cache.connection.clone(), id).await? {
26                Some(proxy) => {
27                    println!("[CallableCache::get_proxy_by_id] Found proxy in Redis: {}", proxy.ip);
28                    self.local_cache
29                        .proxies
30                        .insert(id.to_string(), Arc::new(proxy.clone()));
31                    Ok(Some(Arc::new(proxy)))
32                }
33                None => {
34                    println!("[CallableCache::get_proxy_by_id] Proxy not found in Redis");
35                    Ok(None)
36                }
37            }
38        }
39    }
40
41    pub async fn get_proxies(&mut self) -> Result<Arc<Vec<Proxy>>, RedisError> {
42        println!("[CallableCache::get_proxies] Getting all proxies from Redis");
43        let proxies = get_proxies(self.remote_cache.connection.clone()).await?;
44        println!("[CallableCache::get_proxies] Retrieved {} proxies from Redis", proxies.len());
45        for proxy in &proxies {
46            self.local_cache
47                .proxies
48                .insert(proxy.id.clone(), Arc::new(proxy.clone()));
49        }
50        Ok(Arc::new(proxies))
51    }
52
53    pub async fn get_proxies_local(self) -> Result<Arc<Vec<Proxy>>, RedisError> {
54        println!("[CallableCache::get_proxies_local] Getting proxies from local cache");
55        // Collect the Proxy values and clone the inner Proxy data
56        let proxies: Vec<Proxy> = self
57            .local_cache
58            .proxies
59            .iter()
60            .map(|(_, value)| (*value).clone()) // Dereference the Arc and clone the inner Proxy
61            .collect();
62
63        println!("[CallableCache::get_proxies_local] Found {} proxies in local cache", proxies.len());
64        // Wrap the Vec<Proxy> in an Arc
65        Ok(Arc::new(proxies))
66    }
67}