aboutsummaryrefslogtreecommitdiff
path: root/src/ip_service.rs
blob: ee1a092249febcbf266691b3325da2a7b3613ea0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use serde_with::DisplayFromStr;
use reqwest::Url;
use std::error::Error;
use std::net::IpAddr;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use crate::ip_service::IpServiceProvider::IDENTME;

#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum IpServiceProvider {
    IDENTME(IdentMe)
}

impl Default for IpServiceProvider {
    fn default() -> Self {
        IDENTME(IdentMe::default())
    }
}

pub struct IpService {}

impl IpService {
    pub(crate) async fn resolve(config: &impl IpServiceConfiguration) -> Result<IpAddr, Box<dyn Error>> {
        let response = reqwest::get(config.get_service_url()).await.unwrap();
        Ok(IpAddr::from_str(&response.text().await.unwrap())?)
    }
}

pub trait IpServiceConfiguration {
    fn get_service_url(&self) -> Url;
}

#[serde_as]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct IdentMe {
    #[serde_as(as = "DisplayFromStr")]
    url: Url
}

impl Default for IdentMe {
    fn default() -> Self {
        Self { url: Url::parse("https://v4.ident.me/").unwrap() }
    }
}

impl IpServiceConfiguration for IdentMe {
    fn get_service_url(&self) -> Url {
        self.url.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    async fn setup_ipv4_service(service_path: &str, response: &str) -> MockServer {
        let service = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(service_path))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("Content-Type", "text/plain; charset=utf-8")
                    .set_body_string(response),
            )
            .mount(&service)
            .await;

        service
    }

    #[tokio::test]
    async fn successful_ipv4_address_resolution() -> Result<(), Box<dyn Error>> {
        let service_path = "get-my-ip-address";
        let service_response = "17.5.7.8";

        let ip_service = setup_ipv4_service(service_path, service_response).await;
        let service_config = MockConfig::new(&ip_service, service_path);

        let actual = IpService::resolve(&service_config).await?;
        assert_eq!(actual, IpAddr::V4(Ipv4Addr::new(17, 5, 7, 8)));

        assert_eq!(1, ip_service.received_requests().await.unwrap().len());

        Ok(())
    }

    struct MockConfig {
        service_url: Url,
    }

    impl MockConfig {
        fn new(server: &MockServer, path: &str) -> Self {
            Self {
                service_url: Url::parse(format!("{}/{}", server.uri(), path).as_str()).unwrap(),
            }
        }
    }
    impl IpServiceConfiguration for MockConfig {
        fn get_service_url(&self) -> Url {
            self.service_url.clone()
        }
    }
}