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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use super::error::RestError;
use anyhow::anyhow;
use either::Either;
use exc_core::ExchangeError;
use http::StatusCode;
use serde::{de::DeserializeOwned, Deserialize};

/// Instrument.
pub mod instrument;

/// Candle.
pub mod candle;

/// Listen key.
pub mod listen_key;

/// Error message.
pub mod error_message;

/// Trading.
pub mod trading;

use self::trading::Order;
pub use self::{
    candle::Candle, error_message::ErrorMessage, instrument::ExchangeInfo, listen_key::ListenKey,
};

/// Candles.
pub type Candles = Vec<Candle>;

/// Unknown response.
pub type Unknown = serde_json::Value;

/// Binance rest api response data.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum Data {
    /// Candles.
    Candles(Vec<Candle>),
    /// Exchange info.
    ExchangeInfo(ExchangeInfo),
    /// Listen key.
    ListenKey(ListenKey),
    /// Error Message.
    Error(ErrorMessage),
    /// Order.
    Order(Order),
    /// Unknwon.
    Unknwon(Unknown),
}

impl TryFrom<Data> for Unknown {
    type Error = RestError;

    fn try_from(value: Data) -> Result<Self, Self::Error> {
        match value {
            Data::Unknwon(u) => Ok(u),
            _ => Err(RestError::UnexpectedResponseType(anyhow::anyhow!(
                "{value:?}"
            ))),
        }
    }
}

/// Binance rest api response.
#[derive(Debug)]
pub struct RestResponse<T> {
    data: T,
}

impl<T> RestResponse<T> {
    /// Into inner data.
    pub fn into_inner(self) -> T {
        self.data
    }

    /// Convert into a response of the given type.
    pub fn into_response<U>(self) -> Result<U, RestError>
    where
        U: TryFrom<T, Error = RestError>,
    {
        U::try_from(self.into_inner())
    }

    pub(crate) async fn from_http(resp: http::Response<hyper::Body>) -> Result<Self, RestError>
    where
        T: DeserializeOwned,
    {
        let status = resp.status();
        tracing::trace!("http response status: {}", resp.status());
        let bytes = hyper::body::to_bytes(resp.into_body())
            .await
            .map_err(RestError::from);
        let value =
            bytes.and_then(
                |bytes| match serde_json::from_slice::<serde_json::Value>(&bytes) {
                    Ok(value) => Ok(Either::Left(value)),
                    Err(_) => match std::str::from_utf8(&bytes) {
                        Ok(text) => Ok(Either::Right(text.to_string())),
                        Err(err) => Err(err.into()),
                    },
                },
            );
        match status {
            StatusCode::TOO_MANY_REQUESTS => Err(RestError::Exchange(ExchangeError::RateLimited(
                anyhow!("too many requests"),
            ))),
            StatusCode::IM_A_TEAPOT => Err(RestError::Exchange(ExchangeError::RateLimited(
                anyhow!("I'm a teapot"),
            ))),
            StatusCode::SERVICE_UNAVAILABLE => Err(RestError::Exchange(match value {
                Ok(msg) => ExchangeError::Unavailable(anyhow!("{msg}")),
                Err(err) => ExchangeError::Unavailable(anyhow!("failed to read msg: {err}")),
            })),
            StatusCode::FORBIDDEN => match value {
                Ok(Either::Left(value)) => Err(RestError::Exchange(ExchangeError::Forbidden(
                    anyhow!("{value}"),
                ))),
                Ok(Either::Right(_)) => Err(RestError::Exchange(ExchangeError::Forbidden(
                    anyhow!("no msg"),
                ))),
                Err(err) => Err(RestError::Exchange(ExchangeError::Forbidden(anyhow!(
                    "failed to parse msg: {err}"
                )))),
            },
            _ => match value {
                Ok(Either::Left(value)) => match serde_json::from_value::<T>(value) {
                    Ok(data) => Ok(Self { data }),
                    Err(err) => Err(err.into()),
                },
                Ok(Either::Right(text)) => Err(RestError::Text(text)),
                Err(err) => Err(err),
            },
        }
    }
}