reconn-rpc-client: parse URL before connecting (#1789)

* reconn-rpc-client: parse URL before connecting

It was hard to figure whether one simply entered a faulty URL
and it tried to reconnect according to the retry policy.

With this change we first parse url and then try to reconnect.
This will detect invalid directly instead of waiting for the retry
to complete.

* clippy fix

* wasm: &str -> Url
This commit is contained in:
Niklas Adolfsson
2024-09-30 16:40:20 +02:00
committed by GitHub
parent dff16c6194
commit 72db833def
3 changed files with 122 additions and 167 deletions
@@ -77,6 +77,7 @@ use tokio::sync::{
mpsc::{self, UnboundedReceiver, UnboundedSender},
oneshot, Notify,
};
use url::Url;
use utils::display_close_reason;
// re-exports
@@ -359,10 +360,11 @@ where
}
/// Build and connect to the target.
pub async fn build(self, url: String) -> Result<RpcClient, RpcError> {
pub async fn build(self, url: impl AsRef<str>) -> Result<RpcClient, RpcError> {
let url = Url::parse(url.as_ref()).map_err(|e| RpcError::Transport(Box::new(e)))?;
let (tx, rx) = mpsc::unbounded_channel();
let client = Retry::new(self.retry_policy.clone(), || {
platform::ws_client(url.as_ref(), &self)
platform::ws_client(&url, &self)
})
.await?;
@@ -462,7 +464,7 @@ impl RpcClientT for RpcClient {
async fn background_task<P>(
mut client: Arc<WsClient>,
mut rx: UnboundedReceiver<Op>,
url: String,
url: Url,
client_builder: RpcClientBuilder<P>,
) where
P: Iterator<Item = Duration> + Send + 'static + Clone,
@@ -610,7 +612,7 @@ async fn subscription_handler(
}
struct ReconnectParams<'a, P> {
url: &'a str,
url: &'a Url,
client_builder: &'a RpcClientBuilder<P>,
close_reason: RpcError,
}
@@ -5,6 +5,7 @@
use crate::backend::rpc::reconnecting_rpc_client::{RpcClientBuilder, RpcError};
use jsonrpsee::core::client::Client;
use std::sync::Arc;
use url::Url;
#[cfg(feature = "native")]
pub use tokio::spawn;
@@ -14,7 +15,7 @@ pub use wasm_bindgen_futures::spawn_local as spawn;
#[cfg(feature = "native")]
pub async fn ws_client<P>(
url: &str,
url: &Url,
builder: &RpcClientBuilder<P>,
) -> Result<Arc<Client>, RpcError> {
use jsonrpsee::ws_client::WsClientBuilder;
@@ -50,14 +51,14 @@ pub async fn ws_client<P>(
ws_client_builder = ws_client_builder.enable_ws_ping(*ping);
}
let client = ws_client_builder.build(url).await?;
let client = ws_client_builder.build(url.as_str()).await?;
Ok(Arc::new(client))
}
#[cfg(feature = "web")]
pub async fn ws_client<P>(
url: &str,
url: &Url,
builder: &RpcClientBuilder<P>,
) -> Result<Arc<Client>, RpcError> {
use jsonrpsee::wasm_client::WasmClientBuilder;
@@ -77,7 +78,7 @@ pub async fn ws_client<P>(
.request_timeout(*request_timeout)
.id_format(*id_kind);
let client = ws_client_builder.build(url).await?;
let client = ws_client_builder.build(url.as_str()).await?;
Ok(Arc::new(client))
}