Skip to main content

caretta_sync_core/config/
rpc.rs

1use crate::utils::{emptiable::Emptiable, mergeable::Mergeable};
2#[cfg(feature = "cli")]
3use clap::Args;
4use serde::{Deserialize, Serialize};
5use url::Url;
6
7use crate::config::error::ConfigError;
8
9#[cfg(unix)]
10static DEFAULT_PORT: u16 = 54321;
11
12#[derive(Clone, Debug)]
13pub struct RpcConfig {
14    pub endpoint_url: Url,
15}
16
17impl TryFrom<PartialRpcConfig> for RpcConfig {
18    type Error = ConfigError;
19    fn try_from(config: PartialRpcConfig) -> Result<Self, Self::Error> {
20        Ok(Self {
21            endpoint_url: config
22                .endpoint_url
23                .ok_or(ConfigError::MissingConfig("endpoint".to_string()))?,
24        })
25    }
26}
27
28#[cfg_attr(feature = "cli", derive(Args))]
29#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
30pub struct PartialRpcConfig {
31    pub endpoint_url: Option<Url>,
32}
33
34impl PartialRpcConfig {
35    #[cfg(not(any(all(target_os = "ios", target_abi = "sim"), target_os = "windows")))]
36    pub fn default(app_name: &'static str) -> Self {
37        let username = whoami::username();
38        Self {
39            endpoint_url: Some(
40                Url::parse(
41                    &(String::from("unix://")
42                        + std::env::temp_dir()
43                            .join(username)
44                            .join(String::from(app_name) + ".sock")
45                            .to_str()
46                            .unwrap()),
47                )
48                .unwrap(),
49            ),
50        }
51    }
52    #[cfg(any(all(target_os = "ios", target_abi = "sim"), target_os = "windows"))]
53    pub fn default(app_name: &'static str) -> Self {
54        Self {
55            endpoint_url: Some(Url::parse("http://127.0.0.1:54321").unwrap()),
56        }
57    }
58}
59
60impl Emptiable for PartialRpcConfig {
61    fn empty() -> Self {
62        Self { endpoint_url: None }
63    }
64    fn is_empty(&self) -> bool {
65        self.endpoint_url.is_none()
66    }
67}
68
69impl From<RpcConfig> for PartialRpcConfig {
70    fn from(source: RpcConfig) -> Self {
71        Self {
72            endpoint_url: Some(source.endpoint_url),
73        }
74    }
75}
76
77impl Mergeable for PartialRpcConfig {
78    fn merge(&mut self, other: Self) {
79        if let Some(x) = other.endpoint_url {
80            self.endpoint_url = Some(x);
81        }
82    }
83}
84
85impl Mergeable for Option<PartialRpcConfig> {
86    fn merge(&mut self, mut other: Self) {
87        if let Some(x) = other.take() {
88            if let Some(y) = self.as_mut() {
89                y.merge(x);
90            } else {
91                let _ = self.insert(x);
92            }
93        };
94    }
95}