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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use reqwest::{Client, Method, RequestBuilder, Response, StatusCode};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt;
use url::Url;
pub trait Request: Serialize + Send {
const METHOD: Method;
const PATH: &'static str;
const HAS_PAYLOAD: bool = true;
type Response: DeserializeOwned;
}
#[derive(Debug, Deserialize, Clone, Copy)]
pub enum ErrorKind {
Network,
InvalidContentMatch,
BadContent,
BadStatus,
}
#[derive(Debug)]
pub struct Error {
method: Method,
url: Url,
status: String,
err: String,
content: String,
error_kind: ErrorKind,
}
type Result<T> = std::result::Result<T, Error>;
pub struct HttpClient {
base_url: String,
client: Client,
}
impl HttpClient {
pub fn new(url: &str) -> Self {
Self {
base_url: url.to_owned(),
client: Client::new(),
}
}
pub fn url(&self, path: &str) -> String {
format!("{}{}", self.base_url, path)
}
pub fn unsigned<R: Request>(&self, _req: &R, url: &Url, body: &str) -> RequestBuilder {
let request = self.client.request(R::METHOD, url.clone());
match body.is_empty() {
true => request,
false => request.header("content-type", "application/json"),
}
}
pub async fn request<R>(&self, req: R, logger: Option<&slog::Logger>) -> Result<R::Response>
where
R: Request,
R::Response: DeserializeOwned,
{
let url = self.url(R::PATH);
let mut url = Url::parse(&url).expect("failed to parse url");
if matches!(R::METHOD, Method::GET | Method::DELETE) && R::HAS_PAYLOAD {
url.set_query(Some(
&serde_urlencoded::to_string(&req).expect("failed to encode url payload"),
));
}
let body = match R::METHOD {
Method::PUT | Method::POST => {
serde_json::to_string(&req).expect("failed to json encode body payload")
}
_ => "".to_string(),
};
let request = self.unsigned(&req, &url, &body);
if let Some(log) = logger {
slog::debug!(log, "HttpClient {} {}", R::METHOD, url);
}
let response = request
.header("user-agent", "quantmind-trading")
.body(body)
.send()
.await
.unwrap();
self.handle_response::<R::Response>(&R::METHOD, &url, response)
.await
}
async fn handle_response<T: DeserializeOwned>(
&self,
method: &Method,
url: &Url,
resp: Response,
) -> Result<T> {
let status = resp.status();
match resp.text().await {
Ok(content) => {
if status.is_success() {
serde_json::from_str::<T>(&content).map_err(|err| {
Error::new(
method.clone(),
url.clone(),
status,
ErrorKind::InvalidContentMatch,
err.to_string(),
content,
)
})
} else {
Err(Error::new(
method.clone(),
url.clone(),
status,
ErrorKind::BadStatus,
"".to_string(),
content,
))
}
}
Err(err) => Err(Error::new(
method.clone(),
url.clone(),
status,
ErrorKind::BadContent,
err.to_string(),
"".to_string(),
)),
}
}
}
fn trim(text: String, len: usize) -> String {
let text_len = text.len();
match text_len > len + 3 {
true => {
let mut msg = text;
msg.truncate(len);
msg.push_str(&format!("...({} more characters)", text_len - len));
msg
}
false => text,
}
}
impl Error {
pub fn new(
method: Method,
url: Url,
status: StatusCode,
error_kind: ErrorKind,
err: String,
content: String,
) -> Self {
Error {
method,
url,
status: status.as_str().to_string(),
err,
error_kind,
content: trim(content, 1000),
}
}
pub fn kind(&self) -> ErrorKind {
self.error_kind
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"fluid::http::Error {} {} - response status {}\n{:?} {}\n{}",
self.method, self.url, self.status, self.error_kind, self.err, self.content
)
}
}