Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,26 @@ path = "src/lib.rs"
serde = { version = "1.0", features = ["derive"] }
bitcoin = { version = "0.32", features = ["serde", "std"], default-features = false }
hex = { version = "0.2", package = "hex-conservative" }
log = "^0.4"
log = { version = "^0.4" }
minreq = { version = "2.11.0", features = ["json-using-serde"], optional = true }
reqwest = { version = "0.11", features = ["json"], default-features = false, optional = true }
async-std = { version = "1.13.0", optional = true }
tokio = { version = "1.38.1", features = ["time"], default-features = false, optional = true }

[dev-dependencies]
serde_json = "1.0"
tokio = { version = "1.20.1", features = ["full"] }
tokio = { version = "1.38.1", features = ["full"] }
electrsd = { version = "0.28.0", features = ["legacy", "esplora_a33e97e1", "bitcoind_25_0"] }
lazy_static = "1.4.0"
async-std = { version = "1.13.0"}

[features]
default = ["blocking", "async", "async-https"]
default = ["blocking", "async", "async-https", "tokio"]
blocking = ["minreq", "minreq/proxy"]
blocking-https = ["blocking", "minreq/https"]
blocking-https-rustls = ["blocking", "minreq/https-rustls"]
blocking-https-native = ["blocking", "minreq/https-native"]
blocking-https-bundled = ["blocking", "minreq/https-bundled"]
async = ["async-std", "reqwest", "reqwest/socks"]
async = ["reqwest", "reqwest/socks", "tokio?/time"]
async-https = ["async", "reqwest/default-tls"]
async-https-native = ["async", "reqwest/native-tls"]
async-https-rustls = ["async", "reqwest/rustls-tls"]
Expand Down
29 changes: 25 additions & 4 deletions src/async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@

//! Esplora by way of `reqwest` HTTP client.

use async_std::task;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::str::FromStr;

use bitcoin::consensus::{deserialize, serialize, Decodable, Encodable};
Expand All @@ -33,16 +33,17 @@ use crate::{
};

#[derive(Debug, Clone)]
pub struct AsyncClient {
pub struct AsyncClient<S = DefaultSleeper> {
/// The URL of the Esplora Server.
url: String,
/// The inner [`reqwest::Client`] to make HTTP requests.
client: Client,
/// Number of times to retry a request
max_retries: usize,
sleep_fn: PhantomData<S>,
}

impl AsyncClient {
impl<S: Sleeper> AsyncClient<S> {
/// Build an async client from a builder
pub fn from_builder(builder: Builder) -> Result<Self, Error> {
let mut client_builder = Client::builder();
Expand Down Expand Up @@ -73,6 +74,7 @@ impl AsyncClient {
url: builder.base_url,
client: client_builder.build()?,
max_retries: builder.max_retries,
sleep_fn: PhantomData,
})
}

Expand All @@ -82,6 +84,7 @@ impl AsyncClient {
url,
client,
max_retries: crate::DEFAULT_MAX_RETRIES,
sleep_fn: PhantomData,
}
}

Expand Down Expand Up @@ -434,7 +437,7 @@ impl AsyncClient {
loop {
match self.client.get(url).send().await? {
resp if attempts < self.max_retries && is_status_retryable(resp.status()) => {
task::sleep(delay).await;
S::sleep(delay).await;
attempts += 1;
delay *= 2;
}
Expand All @@ -447,3 +450,21 @@ impl AsyncClient {
fn is_status_retryable(status: reqwest::StatusCode) -> bool {
RETRYABLE_ERROR_CODES.contains(&status.as_u16())
}

pub trait Sleeper: 'static {
type Sleep: std::future::Future<Output = ()>;

fn sleep(dur: std::time::Duration) -> Self::Sleep;
}

#[derive(Default)]
pub struct DefaultSleeper;

#[cfg(any(test, feature = "tokio"))]
impl Sleeper for DefaultSleeper {
type Sleep = tokio::time::Sleep;

fn sleep(dur: std::time::Duration) -> Self::Sleep {
tokio::time::sleep(dur)
}
}
48 changes: 45 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
//! Here is an example of how to create an asynchronous client.
//!
//! ```no_run
//! # #[cfg(feature = "async")]
//! # #[cfg(all(feature = "async", feature = "tokio"))]
//! # {
//! use esplora_client::Builder;
//! let builder = Builder::new("https://blockstream.info/testnet/api");
Expand Down Expand Up @@ -178,11 +178,17 @@ impl Builder {
BlockingClient::from_builder(self)
}

// Build an asynchronous client from builder
#[cfg(feature = "async")]
/// Build an asynchronous client from builder
#[cfg(all(feature = "async", feature = "tokio"))]
pub fn build_async(self) -> Result<AsyncClient, Error> {
AsyncClient::from_builder(self)
}

/// Build an asynchronous client from builder
#[cfg(feature = "async")]
pub fn build_async_with_sleeper<S: r#async::Sleeper>(self) -> Result<AsyncClient<S>, Error> {
AsyncClient::from_builder(self)
}
}

/// Errors that can happen during a request to `Esplora` servers.
Expand Down Expand Up @@ -253,6 +259,8 @@ mod test {
use electrsd::{bitcoind, bitcoind::BitcoinD, ElectrsD};
use lazy_static::lazy_static;
use std::env;
#[cfg(all(feature = "async", not(feature = "tokio")))]
use std::{future::Future, pin::Pin};
use tokio::sync::Mutex;
#[cfg(all(feature = "blocking", feature = "async"))]
use {
Expand Down Expand Up @@ -320,8 +328,15 @@ mod test {
let blocking_client = builder.build_blocking();

let builder_async = Builder::new(&format!("http://{}", esplora_url));

#[cfg(feature = "tokio")]
let async_client = builder_async.build_async().unwrap();

#[cfg(not(feature = "tokio"))]
let async_client = builder_async
.build_async_with_sleeper::<r#async::DefaultSleeper>()
.unwrap();

(blocking_client, async_client)
}

Expand Down Expand Up @@ -992,4 +1007,31 @@ mod test {
let tx_async = async_client.get_tx(&txid).await.unwrap();
assert_eq!(tx, tx_async);
}

#[cfg(all(feature = "async", feature = "tokio"))]
#[test]
fn test_default_tokio_sleeper() {
let builder = Builder::new("https://blockstream.info/testnet/api");
let client = builder.build_async();
assert!(client.is_ok());
}
#[cfg(all(feature = "async", not(feature = "tokio")))]
struct CustomRuntime;

#[cfg(all(feature = "async", not(feature = "tokio")))]
impl r#async::Sleeper for CustomRuntime {
type Sleep = Pin<Box<dyn Future<Output = ()>>>;

fn sleep(dur: std::time::Duration) -> Self::Sleep {
Box::pin(async_std::task::sleep(dur))
}
}

#[cfg(all(feature = "async", not(feature = "tokio")))]
#[test]
fn test_custom_runtime() {
let builder = Builder::new("https://blockstream.info/testnet/api");
let client = builder.build_async_with_sleeper::<CustomRuntime>();
assert!(client.is_ok());
}
}
Loading