cal-redis 0.1.80

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

use super::CallableCache;
use crate::proxy::{get_proxies, get_proxy_by_id};
use cal_core::Proxy;
use redis::RedisError;
use std::sync::Arc;

impl CallableCache {
    /// Retrieves a proxy by its ID, first checking the local cache and then Redis.
    ///
    /// # Arguments
    /// * `id` - Proxy ID to look up
    ///
    /// # Returns
    /// * `Result<Option<Proxy>, RedisError>` - Proxy if found, None if not found, or a Redis error
    pub async fn get_proxy_by_id(&mut self, id: &str) -> Result<Option<Arc<Proxy>>, RedisError> {
        println!("[CallableCache::get_proxy_by_id] Getting proxy by ID: {}", id);
        if let Some(proxy) = self.local_cache.proxies.get(id) {
            println!("[CallableCache::get_proxy_by_id] Found proxy in local cache");
            Ok(Some(proxy))
        } else {
            // If proxy identifier not in local cache, try Redis
            println!("[CallableCache::get_proxy_by_id] Proxy not in local cache, fetching from Redis");
            match get_proxy_by_id(self.remote_cache.connection.clone(), id).await? {
                Some(proxy) => {
                    println!("[CallableCache::get_proxy_by_id] Found proxy in Redis: {}", proxy.ip);
                    self.local_cache
                        .proxies
                        .insert(id.to_string(), Arc::new(proxy.clone()));
                    Ok(Some(Arc::new(proxy)))
                }
                None => {
                    println!("[CallableCache::get_proxy_by_id] Proxy not found in Redis");
                    Ok(None)
                }
            }
        }
    }

    pub async fn get_proxies(&mut self) -> Result<Arc<Vec<Proxy>>, RedisError> {
        println!("[CallableCache::get_proxies] Getting all proxies from Redis");
        let proxies = get_proxies(self.remote_cache.connection.clone()).await?;
        println!("[CallableCache::get_proxies] Retrieved {} proxies from Redis", proxies.len());
        for proxy in &proxies {
            self.local_cache
                .proxies
                .insert(proxy.id.clone(), Arc::new(proxy.clone()));
        }
        Ok(Arc::new(proxies))
    }

    pub async fn get_proxies_local(self) -> Result<Arc<Vec<Proxy>>, RedisError> {
        println!("[CallableCache::get_proxies_local] Getting proxies from local cache");
        // Collect the Proxy values and clone the inner Proxy data
        let proxies: Vec<Proxy> = self
            .local_cache
            .proxies
            .iter()
            .map(|(_, value)| (*value).clone()) // Dereference the Arc and clone the inner Proxy
            .collect();

        println!("[CallableCache::get_proxies_local] Found {} proxies in local cache", proxies.len());
        // Wrap the Vec<Proxy> in an Arc
        Ok(Arc::new(proxies))
    }
}