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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
use crate::{config::Configuration, Error, ErrorResponse, Result};
use bytes::Bytes;
use either::{Either, Left, Right};
use futures::{self, Stream, TryStream, TryStreamExt};
use http::{self, StatusCode};
use serde::de::DeserializeOwned;
use serde_json::{self, Value};
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct StatusDetails {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub group: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub kind: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub uid: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub causes: Vec<StatusCause>,
#[serde(default, skip_serializing_if = "num::Zero::is_zero")]
pub retry_after_seconds: u32,
}
#[derive(Deserialize, Debug)]
pub struct StatusCause {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub message: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub field: String,
}
#[derive(Deserialize, Debug)]
pub struct Status {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub status: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub message: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<StatusDetails>,
#[serde(default, skip_serializing_if = "num::Zero::is_zero")]
pub code: u16,
}
#[derive(Clone)]
pub struct APIClient {
configuration: Configuration,
}
impl APIClient {
pub fn new(configuration: Configuration) -> Self {
APIClient { configuration }
}
async fn send(&self, request: http::Request<Vec<u8>>) -> Result<reqwest::Response> {
let (parts, body) = request.into_parts();
let uri_str = format!("{}{}", self.configuration.base_path, parts.uri);
trace!("{} {}", parts.method, uri_str);
let req = match parts.method {
http::Method::GET => self.configuration.client.get(&uri_str),
http::Method::POST => self.configuration.client.post(&uri_str),
http::Method::DELETE => self.configuration.client.delete(&uri_str),
http::Method::PUT => self.configuration.client.put(&uri_str),
http::Method::PATCH => self.configuration.client.patch(&uri_str),
other => return Err(Error::InvalidMethod(other.to_string())),
}
.headers(parts.headers)
.body(body)
.build()?;
let res = self.configuration.client.execute(req).await?;
Ok(res)
}
pub async fn request<T>(&self, request: http::Request<Vec<u8>>) -> Result<T>
where
T: DeserializeOwned,
{
let res: reqwest::Response = self.send(request).await?;
trace!("{} {}", res.status().as_str(), res.url());
let s = res.status();
let text = res.text().await?;
handle_api_errors(&text, s)?;
serde_json::from_str(&text).map_err(|e| {
warn!("{}, {:?}", text, e);
Error::SerdeError(e)
})
}
pub async fn request_text(&self, request: http::Request<Vec<u8>>) -> Result<String> {
let res: reqwest::Response = self.send(request).await?;
trace!("{} {}", res.status().as_str(), res.url());
let s = res.status();
let text = res.text().await?;
handle_api_errors(&text, s)?;
Ok(text)
}
pub async fn request_text_stream(
&self,
request: http::Request<Vec<u8>>,
) -> Result<impl Stream<Item = Result<Bytes>>> {
let res: reqwest::Response = self.send(request).await?;
trace!("{} {}", res.status().as_str(), res.url());
Ok(res.bytes_stream().map_err(Error::ReqwestError))
}
pub async fn request_status<T>(&self, request: http::Request<Vec<u8>>) -> Result<Either<T, Status>>
where
T: DeserializeOwned,
{
let res: reqwest::Response = self.send(request).await?;
trace!("{} {}", res.status().as_str(), res.url());
let s = res.status();
let text = res.text().await?;
handle_api_errors(&text, s)?;
let v: Value = serde_json::from_str(&text)?;
if v["kind"] == "Status" {
trace!("Status from {}", text);
Ok(Right(serde_json::from_str::<Status>(&text).map_err(|e| {
warn!("{}, {:?}", text, e);
Error::SerdeError(e)
})?))
} else {
Ok(Left(serde_json::from_str::<T>(&text).map_err(|e| {
warn!("{}, {:?}", text, e);
Error::SerdeError(e)
})?))
}
}
pub async fn request_events<T>(
&self,
request: http::Request<Vec<u8>>,
) -> Result<impl TryStream<Item = Result<T>>>
where
T: DeserializeOwned,
{
let res: reqwest::Response = self.send(request).await?;
trace!("Streaming from {} -> {}", res.url(), res.status().as_str());
trace!("headers: {:?}", res.headers());
let stream = futures::stream::try_unfold((res, Vec::new()), |(mut resp, _buff)| {
async {
let mut buff = _buff;
loop {
trace!("Await chunk");
match resp.chunk().await {
Ok(Some(chunk)) => {
trace!("Some chunk of len {}", chunk.len());
buff.extend_from_slice(&chunk);
if chunk.contains(&b'\n') {
let mut new_buff = Vec::new();
let mut items = Vec::new();
for line in buff.split(|x| x == &b'\n') {
new_buff.extend_from_slice(&line);
match serde_json::from_slice(&new_buff) {
Ok(val) => {
new_buff.clear();
items.push(Ok(val));
}
Err(e) => {
if !e.is_eof() {
warn!("Failed to parse: {}", String::from_utf8_lossy(line));
new_buff.clear();
items.push(Err(Error::SerdeError(e)));
}
}
}
}
return Ok(Some((items, (resp, new_buff))));
}
}
Ok(None) => {
trace!("None chunk");
return Ok(None);
}
Err(e) => {
if e.is_timeout() {
warn!("timeout in poll: {}", e);
return Ok(None);
}
let inner = e.to_string();
if inner.contains("unexpected EOF during chunk") {
warn!("eof in poll: {}", e);
return Ok(None);
} else {
error!("err poll: {:?} - {}", e, inner);
return Err(Error::ReqwestError(e));
}
}
}
}
}
});
Ok(stream.map_ok(futures::stream::iter).try_flatten())
}
}
fn handle_api_errors(text: &str, s: StatusCode) -> Result<()> {
if s.is_client_error() || s.is_server_error() {
if let Ok(errdata) = serde_json::from_str::<ErrorResponse>(text) {
debug!("Unsuccessful: {:?}", errdata);
Err(Error::Api(errdata))
} else {
warn!("Unsuccessful data error parse: {}", text);
let ae = ErrorResponse {
status: s.to_string(),
code: s.as_u16(),
message: format!("{:?}", text),
reason: "Failed to parse error data".into(),
};
debug!("Unsuccessful: {:?} (reconstruct)", ae);
Err(Error::Api(ae))
}
} else {
Ok(())
}
}