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
//! json in/out, automatic retries
use log::{info, warn};
use serde::Serialize;
use serde_json::Value;

use crate::{
    buyer_service::BuyRequest, checker_service::ChecksRequest,
    seller_service::SellRequest, util::env,
};
pub struct HttpClient {
    client: reqwest::Client,
}

impl Default for HttpClient {
    fn default() -> Self {
        Self::new()
    }
}

impl HttpClient {
    pub fn new() -> HttpClient {
        HttpClient {
            client: reqwest::Client::new(),
        }
    }

    pub async fn buy(
        &self,
        buy_request: &BuyRequest,
    ) -> Result<(), reqwest::Error> {
        let url = env("BUYER_URL") + "/buy";
        self._post(&url, buy_request).await
    }

    pub async fn checks(
        &self,
        checks_request: &ChecksRequest,
    ) -> Result<(), reqwest::Error> {
        let url = env("CHECKER_URL") + "/checks";
        self._post(&url, checks_request).await
    }

    pub async fn sell(
        &self,
        sell_request: &SellRequest,
    ) -> Result<(), reqwest::Error> {
        let url = env("SELLER_URL") + "/sell";
        self._post(&url, sell_request).await
    }

    async fn _post<T: Serialize + ?Sized>(
        &self,
        url: &str,
        payload: &T,
    ) -> Result<(), reqwest::Error> {
        let mut backoff = 1;
        for _ in 0..5 {
            match self.client.post(url).json(&payload).send().await {
                Ok(response) => {
                    info!(
                        "{} response: {}",
                        url,
                        serde_json::to_string_pretty(
                            &response
                                .json::<Value>()
                                .await
                                .expect("parse json")
                        )
                        .expect("pretty response")
                    );
                    break;
                }
                Err(e) => {
                    warn!("{} error, backing off: {}", url, e);
                    tokio::time::sleep(tokio::time::Duration::from_secs(
                        backoff,
                    ))
                    .await;
                    backoff *= 2;
                }
            }
        }

        Ok(())
    }
}