myc_adapters_shared_lib/models/
config.rs

1use super::RedisConfig;
2
3use mycelium_base::utils::errors::{execution_err, MappedErrors};
4use redis::Client;
5use shaku::{Component, Interface};
6use std::sync::Arc;
7
8pub trait SharedClientProvider: Interface + Send + Sync {
9    fn get_redis_client(&self) -> Arc<Client>;
10    fn get_redis_config(&self) -> Arc<RedisConfig>;
11}
12
13#[derive(Component)]
14#[shaku(interface = SharedClientProvider)]
15#[derive(Clone)]
16pub struct SharedClientImpl {
17    redis_client: Arc<Client>,
18    redis_config: Arc<RedisConfig>,
19}
20
21impl SharedClientProvider for SharedClientImpl {
22    fn get_redis_client(&self) -> Arc<Client> {
23        self.redis_client.clone()
24    }
25
26    fn get_redis_config(&self) -> Arc<RedisConfig> {
27        self.redis_config.clone()
28    }
29}
30
31impl SharedClientImpl {
32    pub async fn new(
33        redis_config: RedisConfig,
34    ) -> Result<Arc<Self>, MappedErrors> {
35        let redis_url = format!(
36            "{}://:{}@{}:{}",
37            redis_config.protocol.async_get_or_error().await?,
38            redis_config.password.async_get_or_error().await?,
39            redis_config.hostname.async_get_or_error().await?,
40            match redis_config.to_owned().port {
41                Some(port) => port.async_get_or_error().await?,
42                None => 6379,
43            }
44        );
45
46        let client = Client::open(redis_url).map_err(|err| {
47            execution_err(format!("Failed to connect to redis: {err}"))
48        })?;
49
50        Ok(Arc::new(Self {
51            redis_client: Arc::new(client),
52            redis_config: Arc::new(redis_config),
53        }))
54    }
55}