myc_notifier/repositories/
config.rs

1use crate::models::{ClientProvider, QueueConfig, SmtpConfig};
2
3use lettre::{transport::smtp::authentication::Credentials, SmtpTransport};
4use myc_adapters_shared_lib::models::{
5    RedisClientWrapper, RedisConfig, SharedClientProvider,
6};
7use mycelium_base::utils::errors::{execution_err, MappedErrors};
8use redis::Client;
9use shaku::Component;
10use std::sync::Arc;
11
12#[derive(Component)]
13#[shaku(interface = ClientProvider)]
14#[derive(Clone)]
15pub struct NotifierClientImpl {
16    #[shaku(inject)]
17    redis_client: Arc<dyn SharedClientProvider>,
18    smtp_client: Arc<SmtpTransport>,
19    queue_config: Arc<QueueConfig>,
20}
21
22impl ClientProvider for NotifierClientImpl {
23    fn get_queue_config(&self) -> Arc<QueueConfig> {
24        self.queue_config.clone()
25    }
26
27    fn get_smtp_client(&self) -> Arc<SmtpTransport> {
28        self.smtp_client.clone()
29    }
30
31    fn get_redis_config(&self) -> Arc<RedisConfig> {
32        self.redis_client.get_redis_config().clone()
33    }
34
35    fn get_redis_client(&self) -> Arc<Client> {
36        self.redis_client.get_redis_client().clone()
37    }
38}
39
40impl NotifierClientImpl {
41    pub async fn new(
42        queue_config: QueueConfig,
43        redis_config: RedisConfig,
44        smtp_config: SmtpConfig,
45    ) -> Result<Arc<Self>, MappedErrors> {
46        let queue_url = format!(
47            "{}://:{}@{}",
48            redis_config.protocol.async_get_or_error().await?,
49            redis_config.password.async_get_or_error().await?,
50            redis_config.hostname.async_get_or_error().await?
51        );
52
53        let queue_client = RedisClientWrapper::new(
54            Client::open(queue_url).map_err(|err| {
55                execution_err(format!("Failed to connect to queue: {err}"))
56            })?,
57            redis_config,
58        );
59
60        let host = smtp_config.host.async_get_or_error().await?;
61        let username = smtp_config.username.async_get_or_error().await?;
62        let password = smtp_config.password.async_get_or_error().await?;
63        let credentials = Credentials::new(username, password);
64        let port = smtp_config.port.async_get_or_error().await?;
65
66        let smtp_client = SmtpTransport::relay(&host)
67            .map_err(|err| {
68                execution_err(format!("Failed to connect to SMTP: {err}"))
69            })?
70            .credentials(credentials)
71            .port(port)
72            .build();
73
74        Ok(Arc::new(Self {
75            redis_client: Arc::new(queue_client),
76            smtp_client: Arc::new(smtp_client),
77            queue_config: Arc::new(queue_config),
78        }))
79    }
80}