summa_core/configs/
config_proxy.rs

1use std::sync::Arc;
2
3use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
4
5use crate::errors::SummaResult;
6
7#[async_trait]
8pub trait ConfigProxy<TConfig>: Send + Sync {
9    async fn read<'a>(&'a self) -> Box<dyn ConfigReadProxy<TConfig> + 'a>;
10    async fn write<'a>(&'a self) -> Box<dyn ConfigWriteProxy<TConfig> + 'a>;
11}
12
13pub trait ConfigReadProxy<TConfig>: Send + Sync {
14    fn get(&self) -> &TConfig;
15}
16
17#[async_trait]
18pub trait ConfigWriteProxy<TConfig>: Send + Sync {
19    fn get(&self) -> &TConfig;
20    fn get_mut(&mut self) -> &mut TConfig;
21    async fn commit(&self) -> SummaResult<()>;
22}
23
24pub struct DirectProxy<TConfig> {
25    config: Arc<RwLock<TConfig>>,
26}
27
28impl<TConfig> DirectProxy<TConfig> {
29    pub fn new(config: TConfig) -> DirectProxy<TConfig> {
30        DirectProxy {
31            config: Arc::new(RwLock::new(config)),
32        }
33    }
34}
35
36impl<TConfig: Default> Default for DirectProxy<TConfig> {
37    fn default() -> Self {
38        DirectProxy {
39            config: Arc::new(RwLock::new(TConfig::default())),
40        }
41    }
42}
43
44#[async_trait]
45impl<TConfig: Send + Sync> ConfigProxy<TConfig> for DirectProxy<TConfig> {
46    async fn read<'a>(&'a self) -> Box<dyn ConfigReadProxy<TConfig> + 'a> {
47        Box::new(DirectReadProxy {
48            config: self.config.read().await,
49        })
50    }
51
52    async fn write<'a>(&'a self) -> Box<dyn ConfigWriteProxy<TConfig> + 'a> {
53        Box::new(DirectWriteProxy {
54            config: self.config.write().await,
55        })
56    }
57}
58
59pub struct DirectReadProxy<'a, TConfig: Send + Sync> {
60    config: RwLockReadGuard<'a, TConfig>,
61}
62
63impl<TConfig: Send + Sync> ConfigReadProxy<TConfig> for DirectReadProxy<'_, TConfig> {
64    fn get(&self) -> &TConfig {
65        &self.config
66    }
67}
68
69pub struct DirectWriteProxy<'a, TConfig: Send + Sync> {
70    config: RwLockWriteGuard<'a, TConfig>,
71}
72
73#[async_trait]
74impl<TConfig: Send + Sync> ConfigWriteProxy<TConfig> for DirectWriteProxy<'_, TConfig> {
75    fn get(&self) -> &TConfig {
76        &self.config
77    }
78
79    fn get_mut(&mut self) -> &mut TConfig {
80        &mut self.config
81    }
82
83    async fn commit(&self) -> SummaResult<()> {
84        Ok(())
85    }
86}