Skip to main content

platform_module_remote/
config.rs

1#[derive(Debug, Clone, PartialEq, Eq)]
2pub struct RemoteModuleConfig {
3    pub name: String,
4    pub base_url: String,
5    pub transport: RemoteModuleTransport,
6    pub auth_token: Option<String>,
7    pub timeout_ms: u64,
8}
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum RemoteModuleTransport {
12    HttpJson,
13    Grpc,
14}
15
16impl RemoteModuleConfig {
17    #[must_use]
18    pub fn new(name: impl Into<String>, base_url: impl Into<String>) -> Self {
19        let (transport, base_url) = normalize_base_url(base_url.into());
20        Self {
21            name: name.into(),
22            base_url,
23            transport,
24            auth_token: None,
25            timeout_ms: 5_000,
26        }
27    }
28
29    #[must_use]
30    pub fn with_auth_token(mut self, token: impl Into<String>) -> Self {
31        self.auth_token = Some(token.into());
32        self
33    }
34
35    #[must_use]
36    pub fn with_timeout_ms(mut self, timeout_ms: u64) -> Self {
37        self.timeout_ms = timeout_ms;
38        self
39    }
40}
41
42fn normalize_base_url(base_url: String) -> (RemoteModuleTransport, String) {
43    let trimmed = base_url.trim().trim_end_matches('/');
44    match trimmed.strip_prefix("grpc://") {
45        Some(rest) => (
46            RemoteModuleTransport::Grpc,
47            format!("http://{}", rest.trim_end_matches('/')),
48        ),
49        None => match trimmed.strip_prefix("grpcs://") {
50            Some(rest) => (
51                RemoteModuleTransport::Grpc,
52                format!("https://{}", rest.trim_end_matches('/')),
53            ),
54            None => (RemoteModuleTransport::HttpJson, trimmed.to_owned()),
55        },
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn defaults_to_http_json_transport() {
65        let config =
66            RemoteModuleConfig::new("remote-crm", "http://127.0.0.1:4100/lenso/module/v1/");
67
68        assert_eq!(config.transport, RemoteModuleTransport::HttpJson);
69        assert_eq!(config.base_url, "http://127.0.0.1:4100/lenso/module/v1");
70    }
71
72    #[test]
73    fn grpc_scheme_selects_grpc_transport() {
74        let config = RemoteModuleConfig::new("remote-crm", "grpc://127.0.0.1:50051/");
75
76        assert_eq!(config.transport, RemoteModuleTransport::Grpc);
77        assert_eq!(config.base_url, "http://127.0.0.1:50051");
78    }
79
80    #[test]
81    fn grpcs_scheme_selects_grpc_transport_with_tls_endpoint() {
82        let config = RemoteModuleConfig::new("remote-crm", "grpcs://remote.example.test:50051/");
83
84        assert_eq!(config.transport, RemoteModuleTransport::Grpc);
85        assert_eq!(config.base_url, "https://remote.example.test:50051");
86    }
87}