|
| 1 | +use std::fmt; |
| 2 | +use std::net::SocketAddr; |
| 3 | + |
| 4 | +use reqwest::Url as ServiceUrl; |
| 5 | +use serde::Deserialize; |
| 6 | +use url; |
| 7 | + |
| 8 | +/// It parses the configuration from a JSON format. |
| 9 | +/// |
| 10 | +/// # Errors |
| 11 | +/// |
| 12 | +/// Will return an error if the configuration is not valid. |
| 13 | +/// |
| 14 | +/// # Panics |
| 15 | +/// |
| 16 | +/// Will panic if unable to read the configuration file. |
| 17 | +pub fn parse_from_json(json: &str) -> Result<Configuration, ConfigurationError> { |
| 18 | + let plain_config: PlainConfiguration = serde_json::from_str(json).map_err(ConfigurationError::JsonParseError)?; |
| 19 | + Configuration::try_from(plain_config) |
| 20 | +} |
| 21 | + |
| 22 | +/// DTO for the configuration to serialize/deserialize configuration. |
| 23 | +/// |
| 24 | +/// Configuration does not need to be valid. |
| 25 | +#[derive(Deserialize)] |
| 26 | +struct PlainConfiguration { |
| 27 | + pub udp_trackers: Vec<String>, |
| 28 | + pub http_trackers: Vec<String>, |
| 29 | + pub health_checks: Vec<String>, |
| 30 | +} |
| 31 | + |
| 32 | +/// Validated configuration |
| 33 | +pub struct Configuration { |
| 34 | + pub udp_trackers: Vec<SocketAddr>, |
| 35 | + pub http_trackers: Vec<ServiceUrl>, |
| 36 | + pub health_checks: Vec<ServiceUrl>, |
| 37 | +} |
| 38 | + |
| 39 | +#[derive(Debug)] |
| 40 | +pub enum ConfigurationError { |
| 41 | + JsonParseError(serde_json::Error), |
| 42 | + InvalidUdpAddress(std::net::AddrParseError), |
| 43 | + InvalidUrl(url::ParseError), |
| 44 | +} |
| 45 | + |
| 46 | +impl fmt::Display for ConfigurationError { |
| 47 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 48 | + match self { |
| 49 | + ConfigurationError::JsonParseError(e) => write!(f, "JSON parse error: {e}"), |
| 50 | + ConfigurationError::InvalidUdpAddress(e) => write!(f, "Invalid UDP address: {e}"), |
| 51 | + ConfigurationError::InvalidUrl(e) => write!(f, "Invalid URL: {e}"), |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl TryFrom<PlainConfiguration> for Configuration { |
| 57 | + type Error = ConfigurationError; |
| 58 | + |
| 59 | + fn try_from(plain_config: PlainConfiguration) -> Result<Self, Self::Error> { |
| 60 | + let udp_trackers = plain_config |
| 61 | + .udp_trackers |
| 62 | + .into_iter() |
| 63 | + .map(|s| s.parse::<SocketAddr>().map_err(ConfigurationError::InvalidUdpAddress)) |
| 64 | + .collect::<Result<Vec<_>, _>>()?; |
| 65 | + |
| 66 | + let http_trackers = plain_config |
| 67 | + .http_trackers |
| 68 | + .into_iter() |
| 69 | + .map(|s| s.parse::<ServiceUrl>().map_err(ConfigurationError::InvalidUrl)) |
| 70 | + .collect::<Result<Vec<_>, _>>()?; |
| 71 | + |
| 72 | + let health_checks = plain_config |
| 73 | + .health_checks |
| 74 | + .into_iter() |
| 75 | + .map(|s| s.parse::<ServiceUrl>().map_err(ConfigurationError::InvalidUrl)) |
| 76 | + .collect::<Result<Vec<_>, _>>()?; |
| 77 | + |
| 78 | + Ok(Configuration { |
| 79 | + udp_trackers, |
| 80 | + http_trackers, |
| 81 | + health_checks, |
| 82 | + }) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +#[cfg(test)] |
| 87 | +mod tests { |
| 88 | + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; |
| 89 | + |
| 90 | + use super::*; |
| 91 | + |
| 92 | + #[test] |
| 93 | + fn configuration_should_be_build_from_plain_serializable_configuration() { |
| 94 | + let dto = PlainConfiguration { |
| 95 | + udp_trackers: vec!["127.0.0.1:8080".to_string()], |
| 96 | + http_trackers: vec!["http://127.0.0.1:8080".to_string()], |
| 97 | + health_checks: vec!["http://127.0.0.1:8080/health".to_string()], |
| 98 | + }; |
| 99 | + |
| 100 | + let config = Configuration::try_from(dto).expect("A valid configuration"); |
| 101 | + |
| 102 | + assert_eq!( |
| 103 | + config.udp_trackers, |
| 104 | + vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080)] |
| 105 | + ); |
| 106 | + assert_eq!( |
| 107 | + config.http_trackers, |
| 108 | + vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] |
| 109 | + ); |
| 110 | + assert_eq!( |
| 111 | + config.health_checks, |
| 112 | + vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] |
| 113 | + ); |
| 114 | + } |
| 115 | + |
| 116 | + mod building_configuration_from_plan_configuration { |
| 117 | + use crate::checker::config::{Configuration, PlainConfiguration}; |
| 118 | + |
| 119 | + #[test] |
| 120 | + fn it_should_fail_when_a_tracker_udp_address_is_invalid() { |
| 121 | + let plain_config = PlainConfiguration { |
| 122 | + udp_trackers: vec!["invalid_address".to_string()], |
| 123 | + http_trackers: vec![], |
| 124 | + health_checks: vec![], |
| 125 | + }; |
| 126 | + |
| 127 | + assert!(Configuration::try_from(plain_config).is_err()); |
| 128 | + } |
| 129 | + |
| 130 | + #[test] |
| 131 | + fn it_should_fail_when_a_tracker_http_address_is_invalid() { |
| 132 | + let plain_config = PlainConfiguration { |
| 133 | + udp_trackers: vec![], |
| 134 | + http_trackers: vec!["not_a_url".to_string()], |
| 135 | + health_checks: vec![], |
| 136 | + }; |
| 137 | + |
| 138 | + assert!(Configuration::try_from(plain_config).is_err()); |
| 139 | + } |
| 140 | + |
| 141 | + #[test] |
| 142 | + fn it_should_fail_when_a_health_check_http_address_is_invalid() { |
| 143 | + let plain_config = PlainConfiguration { |
| 144 | + udp_trackers: vec![], |
| 145 | + http_trackers: vec![], |
| 146 | + health_checks: vec!["not_a_url".to_string()], |
| 147 | + }; |
| 148 | + |
| 149 | + assert!(Configuration::try_from(plain_config).is_err()); |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments