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
use hyper::StatusCode;
use thiserror::Error;

#[derive(Clone)]
pub struct ProxyClient {
    address: String,
    debug: bool,
}

impl ProxyClient {
    pub fn new(address: String) -> Self {
        Self {
            address,
            debug: false,
        }
    }

    pub fn enable_debug(&mut self) {
        self.debug = true;
    }

    pub fn disable_debug(&mut self) {
        self.debug = false;
    }

    pub fn print_response(&self, response: &reqwest::blocking::Response) {
        if self.debug {
            println!("Response: {:?}", response);
        }
    }

    pub fn print_request_path(&self, path: &str) {
        if self.debug {
            println!("Request: {}", path);
        }
    }

    pub fn health(&self) -> Result<(), Error> {
        let status_code = reqwest::blocking::get(self.path("health")).map(|r| r.status())?;

        if status_code != StatusCode::OK {
            Err(Error::ServerIsNotUp(status_code))
        } else {
            Ok(())
        }
    }

    pub fn block0(&self) -> Result<Vec<u8>, Error> {
        let response = reqwest::blocking::get(self.path("api/v0/block0"))?;
        self.print_response(&response);
        Ok(response.bytes()?.to_vec())
    }

    fn path(&self, path: &str) -> String {
        let path = format!("{}/{}", self.address, path);
        self.print_request_path(&path);
        path
    }
}

#[derive(Debug, Error)]
pub enum Error {
    #[error("could not deserialize response {text}, due to: {source}")]
    CannotDeserializeResponse {
        source: serde_json::Error,
        text: String,
    },
    #[error("could not send reqeuest")]
    Request(#[from] reqwest::Error),
    #[error("server is not up: {0}")]
    ServerIsNotUp(StatusCode),
    #[error("Error code recieved: {0}")]
    StatusCode(StatusCode),
}