Skip to content

Commit a4b945a

Browse files
committed
fix: is_status_retryable() function and post_request_hex() function causing failure to some tests.
1 parent 2997b16 commit a4b945a

File tree

3 files changed

+35
-104
lines changed

3 files changed

+35
-104
lines changed

Cargo.toml

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ bitcoin = { version = "0.32", features = ["serde", "std"], default-features = fa
2222
hex = { version = "0.2", package = "hex-conservative" }
2323
log = "^0.4"
2424
minreq = { version = "2.11.0", features = ["json-using-serde"], optional = true }
25-
reqwest = { version = "0.12", features = ["json"], default-features = false, optional = true }
2625
async_minreq = { git = "https://github.com/BEULAHEVANJALIN/async-minreq.git" }
2726
serde_json = "1.0.140"
2827

@@ -44,8 +43,8 @@ blocking-https-native = ["blocking", "minreq/https-native"]
4443
blocking-https-bundled = ["blocking", "minreq/https-bundled"]
4544

4645
tokio = ["dep:tokio"]
47-
async = ["reqwest", "reqwest/socks", "tokio?/time"]
48-
async-https = ["async", "reqwest/default-tls"]
49-
async-https-native = ["async", "reqwest/native-tls"]
50-
async-https-rustls = ["async", "reqwest/rustls-tls"]
51-
async-https-rustls-manual-roots = ["async", "reqwest/rustls-tls-manual-roots"]
46+
async = [ "tokio?/time"]
47+
async-https = ["async"]
48+
async-https-native = ["async"]
49+
async-https-rustls = ["async"]
50+
async-https-rustls-manual-roots = ["async"]

src/async.rs

Lines changed: 25 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@
1414
use std::collections::HashMap;
1515
use std::marker::PhantomData;
1616
use std::str::FromStr;
17-
use std::time::Duration;//-----------------------added----------------
18-
use std::convert::TryInto;//-------------------added-----------------
19-
2017
use bitcoin::consensus::{deserialize, serialize, Decodable, Encodable};
2118
use bitcoin::hashes::{sha256, Hash};
2219
use bitcoin::hex::{DisplayHex, FromHex};
@@ -64,58 +61,22 @@ pub struct AsyncClient<S = DefaultSleeper> {
6461
impl<S: Sleeper> AsyncClient<S> {
6562
/// Build an async client from a builder
6663
pub fn from_builder(builder: Builder) -> Result<Self, Error> {
67-
68-
//----------------------------------------not needed since no client struct in async minreq------------------------------------
69-
// let mut client_builder = Client::builder();
70-
71-
// #[cfg(not(target_arch = "wasm32"))]
72-
// if let Some(proxy) = &builder.proxy {
73-
// client_builder = client_builder.proxy(reqwest::Proxy::all(proxy)?);
74-
// }
75-
76-
// #[cfg(not(target_arch = "wasm32"))]
77-
// if let Some(timeout) = builder.timeout {
78-
// client_builder = client_builder.timeout(core::time::Duration::from_secs(timeout));
79-
// }
80-
81-
// if !builder.headers.is_empty() {
82-
// let mut headers = header::HeaderMap::new();
83-
// for (k, v) in builder.headers {
84-
// let header_name = header::HeaderName::from_lowercase(k.to_lowercase().as_bytes())
85-
// .map_err(|_| Error::InvalidHttpHeaderName(k))?;
86-
// let header_value = header::HeaderValue::from_str(&v)
87-
// .map_err(|_| Error::InvalidHttpHeaderValue(v))?;
88-
// headers.insert(header_name, header_value);
89-
// }
90-
// client_builder = client_builder.default_headers(headers);
91-
// }
92-
93-
// Ok(AsyncClient {
94-
// url: builder.base_url,
95-
// client: client_builder.build()?,
96-
// max_retries: builder.max_retries,
97-
// marker: PhantomData,
98-
// })
99-
100-
//--------------------------------------------------------------------------------------
10164
Ok(AsyncClient {
10265
url: builder.base_url,
10366
max_retries: builder.max_retries,
10467
headers: builder.headers,
10568
marker: PhantomData,
10669
})
107-
108-
10970
}
11071

111-
pub fn from_client(url: String, client: Client) -> Self {
72+
pub fn from_client(url: String, headers: HashMap<String, String>,) -> Self {
11273
AsyncClient {
11374
url,
11475
headers,
11576
max_retries: crate::DEFAULT_MAX_RETRIES,
11677
marker: PhantomData,
11778
}
118-
}
79+
}
11980
/// Make an HTTP GET request to given URL, deserializing to any `T` that
12081
/// implement [`bitcoin::consensus::Decodable`].
12182
///
@@ -131,13 +92,12 @@ impl<S: Sleeper> AsyncClient<S> {
13192
let url = format!("{}{}", self.url, path);
13293
let response = self.get_with_retry(&url).await?;
13394

134-
if !(response.status_code==200) {
95+
if response.status_code>299 {
13596
return Err(Error::HttpResponse {
13697
status: response.status_code as u16,
13798
message: response.as_str().unwrap().to_string(),
13899
});
139100
}
140-
141101
Ok(deserialize::<T>(&response.as_bytes())?)
142102
}
143103

@@ -171,13 +131,12 @@ impl<S: Sleeper> AsyncClient<S> {
171131
let url = format!("{}{}", self.url, path);
172132
let response = self.get_with_retry(&url).await?;
173133

174-
if !(response.status_code==200) {
134+
if response.status_code>299 {
175135
return Err(Error::HttpResponse {
176136
status: response.status_code as u16,
177137
message: response.as_str().unwrap().to_string(),
178138
});
179139
}
180-
181140
serde_json::from_str(&response.as_str().unwrap().to_string()).map_err(Error::Json)
182141
}
183142

@@ -213,13 +172,12 @@ impl<S: Sleeper> AsyncClient<S> {
213172
let url = format!("{}{}", self.url, path);
214173
let response = self.get_with_retry(&url).await?;
215174

216-
if !(response.status_code==200) {
175+
if response.status_code>299 {
217176
return Err(Error::HttpResponse {
218177
status: response.status_code as u16,
219178
message:response.as_str().unwrap().to_string(),
220179
});
221180
}
222-
223181
let hex_str =response.as_str().unwrap().to_string();
224182
Ok(deserialize(&Vec::from_hex(&hex_str)?)?)
225183
}
@@ -250,13 +208,12 @@ impl<S: Sleeper> AsyncClient<S> {
250208
let url = format!("{}{}", self.url, path);
251209
let response = self.get_with_retry(&url).await?;
252210

253-
if !(response.status_code==200) {
211+
if response.status_code>299 {
254212
return Err(Error::HttpResponse {
255213
status: response.status_code as u16,
256214
message:response.as_str().unwrap().to_string(),
257215
});
258216
}
259-
// let x=response.as_str().unwrap().to_string();
260217
Ok(response.as_str().unwrap().to_string())
261218
}
262219

@@ -293,7 +250,13 @@ impl<S: Sleeper> AsyncClient<S> {
293250
request = request.with_header(key, value);
294251
}
295252

296-
let _ = request.send().await.map_err(Error::AsyncMinreq)?;
253+
let response = request.send().await.map_err(Error::AsyncMinreq)?;
254+
if response.status_code>299{
255+
return Err(Error::HttpResponse {
256+
status: response.status_code as u16,
257+
message: response.as_str().unwrap().to_string(),
258+
});
259+
}
297260
Ok(())
298261
}
299262

@@ -489,39 +452,26 @@ impl<S: Sleeper> AsyncClient<S> {
489452

490453
loop {
491454
let mut request = Request::new(Method::Get, url);
492-
// Apply headers from the builder.
455+
// Applying headers from the builder.
493456
for (key, value) in &self.headers {
494457
request = request.with_header(key, value);
495458
}
496-
// request.
497-
498-
let res = request.send().await.map_err(Error::AsyncMinreq);
499-
500-
match res {
501-
Ok(body) => {
502-
503-
504-
return Ok(body);
505-
506-
},
507-
Err(e) => {
508-
509-
if attempts < self.max_retries {
510-
S::sleep(delay).await;
511-
attempts += 1;
512-
delay *= 2;
513-
continue;
514-
}
515-
return Err(e);
459+
460+
match request.send().await? {
461+
resp if attempts < self.max_retries && is_status_retryable(resp.status_code) => {
462+
S::sleep(delay).await;
463+
attempts += 1;
464+
delay *= 2;
516465
}
466+
resp => return Ok(resp),
517467
}
518468
}
519469
}
520470
}
521471

522-
// fn is_status_retryable(status: reqwest::StatusCode) -> bool {
523-
// RETRYABLE_ERROR_CODES.contains(&status.as_u16())
524-
// }
472+
fn is_status_retryable(status: i32) -> bool {
473+
RETRYABLE_ERROR_CODES.contains(&(status as u16))
474+
}
525475

526476
pub trait Sleeper: 'static {
527477
type Sleep: std::future::Future<Output = ()>;
@@ -538,4 +488,4 @@ impl Sleeper for DefaultSleeper {
538488
fn sleep(dur: std::time::Duration) -> Self::Sleep {
539489
tokio::time::sleep(dur)
540490
}
541-
}
491+
}

src/lib.rs

Lines changed: 5 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -200,15 +200,11 @@ pub enum Error {
200200
/// Error during `minreq` HTTP request
201201
#[cfg(feature = "blocking")]
202202
Minreq(::minreq::Error),
203-
/// Error during reqwest HTTP request
204-
//-----------------------------------------------changed------------------------------
205-
// #[cfg(feature = "async")]
206-
// Reqwest(::reqwest::Error),
203+
/// Error during async_minreq HTTP request
207204
#[cfg(feature = "async")]
208205
AsyncMinreq(async_minreq::Error),
206+
/// JSON Error
209207
Json(serde_json::Error),
210-
211-
212208
/// HTTP response error
213209
HttpResponse { status: u16, message: String },
214210
/// Invalid number returned
@@ -253,26 +249,12 @@ macro_rules! impl_error {
253249
}
254250
};
255251
}
256-
257252
impl std::error::Error for Error {}
258253
#[cfg(feature = "blocking")]
259254
impl_error!(::minreq::Error, Minreq, Error);
260-
261-
//---------------------------------------------changed------------------------------
262255
#[cfg(feature = "async")]
263-
// impl_error!(::reqwest::Error, Reqwest, Error);
264-
impl std::convert::From<async_minreq::Error> for Error {
265-
fn from(err: async_minreq::Error) -> Self {
266-
Error::AsyncMinreq(err)
267-
}
268-
}
269-
270-
impl std::convert::From<serde_json::Error> for Error {
271-
fn from(err: serde_json::Error) -> Self {
272-
Error::Json(err)
273-
}
274-
}
275-
// impl_error!(::reqwest::Error, Reqwest, Error);
256+
impl_error!(::async_minreq::Error, AsyncMinreq, Error);
257+
impl_error!(::serde_json::Error, Json, Error);
276258
impl_error!(std::num::ParseIntError, Parsing, Error);
277259
impl_error!(bitcoin::consensus::encode::Error, BitcoinEncoding, Error);
278260
impl_error!(bitcoin::hex::HexToArrayError, HexToArray, Error);
@@ -1105,4 +1087,4 @@ mod test {
11051087
assert_eq!(address_txs_blocking, address_txs_async);
11061088
assert_eq!(address_txs_async[0].txid, txid);
11071089
}
1108-
}
1090+
}

0 commit comments

Comments
 (0)