diff --git a/src/infra/http_resolver.rs b/src/infra/http_resolver.rs new file mode 100644 index 0000000..7c9b981 --- /dev/null +++ b/src/infra/http_resolver.rs @@ -0,0 +1,93 @@ +use std::net::Ipv4Addr; +use std::time::Duration; +use ureq::Agent; + +use crate::domain::errors::ResolveError; +use crate::domain::models::IpDiscoveryResult; +use crate::domain::traits::IpResolver; +use crate::domain::validation::{is_valid_public_ipv4, next_provider_index}; + +/// Resolves the public WAN IPv4 address by querying a sequence of HTTP echo services. +pub struct HttpIpResolver { + urls: Vec, + agent: Agent, +} + +impl HttpIpResolver { + pub fn new(urls: Vec, timeout: Duration) -> Self { + let config = ureq::config::Config::builder() + .timeout_global(Some(timeout)) + .build(); + let agent = Agent::new_with_config(config); + Self { urls, agent } + } +} + +impl IpResolver for HttpIpResolver { + fn resolve(&self, last_index: Option) -> Result { + let n = self.urls.len(); + if n == 0 { + return Err(ResolveError::NoProvidersConfigured); + } + + let start_index = next_provider_index(last_index, n).unwrap_or(0); + let mut errors = Vec::new(); + + for offset in 0..n { + let current_index = (start_index + offset) % n; + let url = &self.urls[current_index]; + + log::debug!("Attempting IP discovery with provider '{}' (index {})", url, current_index); + + let resp = self + .agent + .get(url) + .header("User-Agent", "ddns-monitor/0.1.0") + .call(); + + let mut response = match resp { + Ok(r) => r, + Err(e) => { + let err_msg = format!("{}: HTTP error: {}", url, e); + log::warn!("{}", err_msg); + errors.push(err_msg); + continue; + } + }; + + let body_str = match response.body_mut().read_to_string() { + Ok(s) => s, + Err(e) => { + let err_msg = format!("{}: failed reading response body: {}", url, e); + log::warn!("{}", err_msg); + errors.push(err_msg); + continue; + } + }; + + let trimmed = body_str.trim(); + match trimmed.parse::() { + Ok(ip) => { + if is_valid_public_ipv4(ip) { + return Ok(IpDiscoveryResult { + ip, + provider: url.clone(), + provider_index: current_index, + }); + } else { + let err_msg = format!("{}: received non-public IP '{}'", url, trimmed); + log::warn!("{}", err_msg); + errors.push(err_msg); + } + } + Err(e) => { + let err_msg = format!("{}: invalid IPv4 string '{}': {}", url, trimmed, e); + log::warn!("{}", err_msg); + errors.push(err_msg); + } + } + } + + Err(ResolveError::AllProvidersFailed(errors.join("; "))) + } +} diff --git a/src/infra/mod.rs b/src/infra/mod.rs new file mode 100644 index 0000000..a20f3c7 --- /dev/null +++ b/src/infra/mod.rs @@ -0,0 +1 @@ +pub mod http_resolver; diff --git a/src/lib.rs b/src/lib.rs index 88a66ac..ed2e524 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ pub mod config; pub mod domain; +pub mod infra; pub mod service; diff --git a/tests/http_resolver_test.rs b/tests/http_resolver_test.rs new file mode 100644 index 0000000..cc703c8 --- /dev/null +++ b/tests/http_resolver_test.rs @@ -0,0 +1,94 @@ +use ddns_monitor::domain::traits::IpResolver; +use ddns_monitor::infra::http_resolver::HttpIpResolver; +use std::net::Ipv4Addr; +use std::time::Duration; + +#[test] +fn test_http_resolver_success() { + let mut server = mockito::Server::new(); + let _m = server + .mock("GET", "/ip") + .with_status(200) + .with_header("content-type", "text/plain") + .with_body("93.184.216.34\n") + .create(); + + let url = format!("{}/ip", server.url()); + let resolver = HttpIpResolver::new(vec![url.clone()], Duration::from_secs(2)); + + let res = resolver.resolve(None).expect("resolve succeeded"); + assert_eq!(res.ip, Ipv4Addr::new(93, 184, 216, 34)); + assert_eq!(res.provider, url); + assert_eq!(res.provider_index, 0); +} + +#[test] +fn test_http_resolver_fallback_on_invalid_ip() { + let mut server1 = mockito::Server::new(); + let _m1 = server1 + .mock("GET", "/ip") + .with_status(200) + .with_body("192.168.1.1\n") // Private IP - invalid for public WAN + .create(); + + let mut server2 = mockito::Server::new(); + let _m2 = server2 + .mock("GET", "/ip") + .with_status(200) + .with_body("198.51.100.22\n") // Valid public IP + .create(); + + let url1 = format!("{}/ip", server1.url()); + let url2 = format!("{}/ip", server2.url()); + + let resolver = HttpIpResolver::new(vec![url1, url2.clone()], Duration::from_secs(2)); + + let res = resolver.resolve(None).expect("resolve fallback succeeded"); + assert_eq!(res.ip, Ipv4Addr::new(198, 51, 100, 22)); + assert_eq!(res.provider, url2); + assert_eq!(res.provider_index, 1); +} + +#[test] +fn test_http_resolver_rotation_starting_point() { + let mut server1 = mockito::Server::new(); + let _m1 = server1 + .mock("GET", "/ip") + .with_status(200) + .with_body("93.184.216.1\n") + .create(); + + let mut server2 = mockito::Server::new(); + let _m2 = server2 + .mock("GET", "/ip") + .with_status(200) + .with_body("93.184.216.2\n") + .create(); + + let url1 = format!("{}/ip", server1.url()); + let url2 = format!("{}/ip", server2.url()); + + let resolver = HttpIpResolver::new(vec![url1, url2.clone()], Duration::from_secs(2)); + + // last_index was 0, so next rotation MUST query server2 (index 1) first! + let res = resolver.resolve(Some(0)).expect("resolve rotated"); + assert_eq!(res.ip, Ipv4Addr::new(93, 184, 216, 2)); + assert_eq!(res.provider, url2); + assert_eq!(res.provider_index, 1); +} + +#[test] +fn test_http_resolver_all_failed() { + let mut server = mockito::Server::new(); + let _m = server + .mock("GET", "/ip") + .with_status(500) + .with_body("Internal Server Error") + .create(); + + let url = format!("{}/ip", server.url()); + let resolver = HttpIpResolver::new(vec![url], Duration::from_secs(1)); + + let res = resolver.resolve(None); + assert!(res.is_err()); +}