Skip to main content

ombrac_client/config/
json.rs

1use std::error::Error;
2
3use serde::{Deserialize, Serialize};
4
5#[cfg(feature = "tracing")]
6use crate::config::LoggingConfig;
7use crate::config::{EndpointConfig, TransportConfig};
8
9/// JSON configuration file structure
10#[derive(Deserialize, Serialize, Debug, Default)]
11#[serde(rename_all = "snake_case")]
12pub struct JsonConfig {
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub secret: Option<String>,
15
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub server: Option<String>,
18
19    /// Authentication option for protocol extensions
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub auth_option: Option<String>,
22
23    pub endpoint: Option<EndpointConfig>,
24
25    pub transport: Option<TransportConfig>,
26
27    #[cfg(feature = "tracing")]
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub logging: Option<LoggingConfig>,
30}
31
32impl JsonConfig {
33    /// Load configuration from a JSON string
34    ///
35    /// # Arguments
36    ///
37    /// * `json_str` - A JSON string containing the configuration
38    ///
39    /// # Returns
40    ///
41    /// A `JsonConfig` instance, or an error if parsing fails
42    pub fn from_json_str(json_str: &str) -> Result<Self, Box<dyn Error>> {
43        let config: JsonConfig = serde_json::from_str(json_str)?;
44        Ok(config)
45    }
46
47    /// Load configuration from a JSON file
48    ///
49    /// # Arguments
50    ///
51    /// * `config_path` - Path to the JSON configuration file
52    ///
53    /// # Returns
54    ///
55    /// A `JsonConfig` instance, or an error if the file doesn't exist or parsing fails
56    pub fn from_file(config_path: &std::path::Path) -> Result<Self, Box<dyn Error>> {
57        if !config_path.exists() {
58            return Err(format!("Configuration file not found: {}", config_path.display()).into());
59        }
60
61        let content = std::fs::read_to_string(config_path)?;
62        Self::from_json_str(&content)
63    }
64}