DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: initial-tcp-experimentation emerwen/emerwen-types/src/lib.rs -rw-r--r-- 1.5 KiB
1225af8eJonni Liljamo feat: more experimentation 13 days ago
                                                                                
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
use std::{net::IpAddr, time::Duration};

#[derive(Debug, PartialEq)]
pub enum TargetMethod {
    Ping,
    GET { ok_codes: Vec<u16> },
}

pub struct Target {
    pub id: u16,
    pub addr: String,
    /// Check interval in ms
    pub interval: u32,
    pub method: TargetMethod,
}

pub enum CheckResponse {
    Ping { duration: Duration },
    GET { status_code: u16 },
}

impl Target {
    /// Check the target using the assigned method.
    ///
    /// # Errors
    ///
    /// Errors should be treated as "unknown".
    ///
    /// Returns an error if:
    /// - IpAddr parse fails
    /// - reqwest fails to send the request
    pub async fn check(&self) -> Result<(bool, Option<CheckResponse>), Box<dyn std::error::Error>> {
        match &self.method {
            TargetMethod::Ping => {
                let ip: IpAddr = self.addr.parse()?;
                match surge_ping::ping(ip, &[0u8; 8]).await {
                    Ok((_, duration)) => Ok((true, Some(CheckResponse::Ping { duration }))),
                    Err(_) => Ok((false, None)),
                }
            }
            TargetMethod::GET { ok_codes } => {
                let response = reqwest::get(self.addr.clone()).await?;
                let status_code = response.status().as_u16();
                if ok_codes.contains(&status_code) {
                    Ok((true, Some(CheckResponse::GET { status_code })))
                } else {
                    Ok((false, None))
                }
            }
        }
    }
}