chore(ws): add some docs and impl debug (#2219)

This commit is contained in:
Matthias Seitz 2023-03-05 21:17:43 +01:00 committed by GitHub
parent a4f1a7bb3d
commit 89b23647f1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 16 deletions

View File

@ -1,3 +1,13 @@
use super::{
backend::{BackendDriver, WsBackend},
ActiveSub, ConnectionDetails, InFlight, Instruction, Notification, PubSubItem, Response, SubId,
WsClient, WsClientError,
};
use crate::JsonRpcError;
use ethers_core::types::U256;
use futures_channel::{mpsc, oneshot};
use futures_util::{select_biased, StreamExt};
use serde_json::value::RawValue;
use std::{ use std::{
collections::{BTreeMap, HashMap}, collections::{BTreeMap, HashMap},
sync::{ sync::{
@ -6,19 +16,6 @@ use std::{
}, },
}; };
use ethers_core::types::U256;
use futures_channel::{mpsc, oneshot};
use futures_util::{select_biased, StreamExt};
use serde_json::value::RawValue;
use crate::JsonRpcError;
use super::{
backend::{BackendDriver, WsBackend},
ActiveSub, ConnectionDetails, InFlight, Instruction, Notification, PubSubItem, Response, SubId,
WsClient, WsClientError,
};
pub type SharedChannelMap = Arc<Mutex<HashMap<U256, mpsc::UnboundedReceiver<Box<RawValue>>>>>; pub type SharedChannelMap = Arc<Mutex<HashMap<U256, mpsc::UnboundedReceiver<Box<RawValue>>>>>;
pub const DEFAULT_RECONNECTS: usize = 5; pub const DEFAULT_RECONNECTS: usize = 5;

View File

@ -3,7 +3,9 @@
mod backend; mod backend;
mod manager; mod manager;
use manager::{RequestManager, SharedChannelMap}; use manager::{RequestManager, SharedChannelMap};
use std::fmt;
mod types; mod types;
pub use types::ConnectionDetails; pub use types::ConnectionDetails;
@ -12,18 +14,17 @@ pub(self) use types::*;
mod error; mod error;
pub use error::*; pub use error::*;
use crate::{JsonRpcClient, ProviderError, PubsubClient};
use async_trait::async_trait; use async_trait::async_trait;
use ethers_core::types::U256; use ethers_core::types::U256;
use futures_channel::{mpsc, oneshot}; use futures_channel::{mpsc, oneshot};
use serde::{de::DeserializeOwned, Serialize}; use serde::{de::DeserializeOwned, Serialize};
use serde_json::value::RawValue; use serde_json::value::RawValue;
use crate::{JsonRpcClient, ProviderError, PubsubClient};
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use crate::Authorization; use crate::Authorization;
#[derive(Debug, Clone)] #[derive(Clone)]
pub struct WsClient { pub struct WsClient {
// Used to send instructions to the `RequestManager` // Used to send instructions to the `RequestManager`
instructions: mpsc::UnboundedSender<Instruction>, instructions: mpsc::UnboundedSender<Instruction>,
@ -32,12 +33,14 @@ pub struct WsClient {
} }
impl WsClient { impl WsClient {
/// Establishes a new websocket connection
pub async fn connect(conn: impl Into<ConnectionDetails>) -> Result<Self, WsClientError> { pub async fn connect(conn: impl Into<ConnectionDetails>) -> Result<Self, WsClientError> {
let (man, this) = RequestManager::connect(conn.into()).await?; let (man, this) = RequestManager::connect(conn.into()).await?;
man.spawn(); man.spawn();
Ok(this) Ok(this)
} }
/// Establishes a new websocket connection with auto-reconnects.
pub async fn connect_with_reconnects( pub async fn connect_with_reconnects(
conn: impl Into<ConnectionDetails>, conn: impl Into<ConnectionDetails>,
reconnects: usize, reconnects: usize,
@ -66,6 +69,12 @@ impl WsClient {
} }
} }
impl fmt::Debug for WsClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ws").finish_non_exhaustive()
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl JsonRpcClient for WsClient { impl JsonRpcClient for WsClient {
@ -104,6 +113,31 @@ impl PubsubClient for WsClient {
impl crate::Provider<WsClient> { impl crate::Provider<WsClient> {
/// Direct connection to a websocket endpoint. Defaults to 5 reconnects. /// Direct connection to a websocket endpoint. Defaults to 5 reconnects.
///
/// # Examples
///
/// Connect to server via URL
///
/// ```
/// use ethers_providers::{Ws, Provider};
/// use ethers_providers::Middleware;
/// # async fn t() {
/// let ws = Provider::<Ws>::connect("ws://localhost:8545").await.unwrap();
/// let _num = ws.get_block_number().await.unwrap();
/// # }
/// ```
///
/// Connect with authentication, see also [Self::connect_with_auth]
///
/// ```
/// use ethers_providers::{Ws, Provider, Middleware, ConnectionDetails, Authorization };
/// # async fn t() {
/// let auth = Authorization::basic("user", "pass");
/// let opts = ConnectionDetails::new("ws://localhost:8545", Some(auth));
/// let ws = Provider::<Ws>::connect(opts).await.unwrap();
/// let _num = ws.get_block_number().await.unwrap();
/// # }
/// ```
pub async fn connect(url: impl Into<ConnectionDetails>) -> Result<Self, ProviderError> { pub async fn connect(url: impl Into<ConnectionDetails>) -> Result<Self, ProviderError> {
let ws = crate::Ws::connect(url).await?; let ws = crate::Ws::connect(url).await?;
Ok(Self::new(ws)) Ok(Self::new(ws))