#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(test)]
mod tests;
pub use http::{HeaderMap, HeaderValue};
pub use jsonrpsee_core::client::Client as WsClient;
pub use jsonrpsee_core::client::async_client::PingConfig;
pub use jsonrpsee_core::client::async_client::RpcService;
pub use jsonrpsee_core::middleware::RpcServiceBuilder;
use jsonrpsee_core::middleware::layer::RpcLoggerLayer;
pub use jsonrpsee_types as types;
use jsonrpsee_client_transport::ws::{AsyncRead, AsyncWrite, WsTransportClientBuilder};
use jsonrpsee_core::TEN_MB_SIZE_BYTES;
use jsonrpsee_core::client::{ClientBuilder, Error, IdKind, MaybeSend, TransportReceiverT, TransportSenderT};
use jsonrpsee_core::traits::MessageEncryption;
use std::time::Duration;
use url::Url;
type Logger = tower::layer::util::Stack<RpcLoggerLayer, tower::layer::util::Identity>;
#[cfg(feature = "tls")]
pub use jsonrpsee_client_transport::ws::CustomCertStore;
#[cfg(feature = "tls")]
use jsonrpsee_client_transport::ws::CertificateStore;
#[derive(Clone, Debug)]
pub struct WsClientBuilder<RpcMiddleware = Logger> {
#[cfg(feature = "tls")]
certificate_store: CertificateStore,
max_request_size: u32,
max_response_size: u32,
request_timeout: Duration,
connection_timeout: Duration,
ping_config: Option<PingConfig>,
headers: http::HeaderMap,
max_concurrent_requests: usize,
max_buffer_capacity_per_subscription: usize,
max_redirections: usize,
id_kind: IdKind,
tcp_no_delay: bool,
service_builder: RpcServiceBuilder<RpcMiddleware>,
message_encryption: Option<std::sync::Arc<dyn MessageEncryption>>,
}
impl Default for WsClientBuilder {
fn default() -> Self {
Self {
#[cfg(feature = "tls")]
certificate_store: CertificateStore::Native,
max_request_size: TEN_MB_SIZE_BYTES,
max_response_size: TEN_MB_SIZE_BYTES,
request_timeout: Duration::from_secs(60),
connection_timeout: Duration::from_secs(10),
ping_config: None,
headers: HeaderMap::new(),
max_concurrent_requests: 256,
max_buffer_capacity_per_subscription: 1024,
max_redirections: 5,
id_kind: IdKind::Number,
tcp_no_delay: true,
service_builder: RpcServiceBuilder::default().rpc_logger(1024),
message_encryption: None,
}
}
}
impl WsClientBuilder {
pub fn new() -> WsClientBuilder {
WsClientBuilder::default()
}
}
impl<RpcMiddleware> WsClientBuilder<RpcMiddleware> {
#[cfg(feature = "tls")]
pub fn with_custom_cert_store(mut self, cfg: CustomCertStore) -> Self {
self.certificate_store = CertificateStore::Custom(cfg);
self
}
pub fn max_request_size(mut self, size: u32) -> Self {
self.max_request_size = size;
self
}
pub fn max_response_size(mut self, size: u32) -> Self {
self.max_response_size = size;
self
}
pub fn request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = timeout;
self
}
pub fn connection_timeout(mut self, timeout: Duration) -> Self {
self.connection_timeout = timeout;
self
}
pub fn enable_ws_ping(mut self, cfg: PingConfig) -> Self {
self.ping_config = Some(cfg);
self
}
pub fn disable_ws_ping(mut self) -> Self {
self.ping_config = None;
self
}
pub fn set_headers(mut self, headers: http::HeaderMap) -> Self {
self.headers = headers;
self
}
pub fn max_concurrent_requests(mut self, max: usize) -> Self {
self.max_concurrent_requests = max;
self
}
pub fn max_buffer_capacity_per_subscription(mut self, max: usize) -> Self {
self.max_buffer_capacity_per_subscription = max;
self
}
pub fn max_redirections(mut self, redirect: usize) -> Self {
self.max_redirections = redirect;
self
}
pub fn id_format(mut self, kind: IdKind) -> Self {
self.id_kind = kind;
self
}
pub fn set_tcp_no_delay(mut self, no_delay: bool) -> Self {
self.tcp_no_delay = no_delay;
self
}
pub fn set_message_encryption<E: MessageEncryption>(mut self, encryption: E) -> Self {
self.message_encryption = Some(std::sync::Arc::new(encryption));
self
}
pub fn set_rpc_middleware<T>(self, service_builder: RpcServiceBuilder<T>) -> WsClientBuilder<T> {
WsClientBuilder {
#[cfg(feature = "tls")]
certificate_store: self.certificate_store,
max_request_size: self.max_request_size,
max_response_size: self.max_response_size,
request_timeout: self.request_timeout,
connection_timeout: self.connection_timeout,
ping_config: self.ping_config,
headers: self.headers,
max_concurrent_requests: self.max_concurrent_requests,
max_buffer_capacity_per_subscription: self.max_buffer_capacity_per_subscription,
max_redirections: self.max_redirections,
id_kind: self.id_kind,
tcp_no_delay: self.tcp_no_delay,
service_builder,
message_encryption: self.message_encryption,
}
}
pub fn build_with_transport<S, R, Svc>(self, sender: S, receiver: R) -> WsClient<Svc>
where
S: TransportSenderT + Send,
R: TransportReceiverT + Send,
RpcMiddleware: tower::Layer<RpcService, Service = Svc> + Clone + Send + Sync + 'static,
{
let Self {
max_concurrent_requests,
request_timeout,
ping_config,
max_buffer_capacity_per_subscription,
id_kind,
tcp_no_delay,
service_builder,
..
} = self;
let mut client = ClientBuilder::default()
.max_buffer_capacity_per_subscription(max_buffer_capacity_per_subscription)
.request_timeout(request_timeout)
.max_concurrent_requests(max_concurrent_requests)
.id_format(id_kind)
.set_tcp_no_delay(tcp_no_delay)
.set_rpc_middleware(service_builder);
if let Some(cfg) = ping_config {
client = client.enable_ws_ping(cfg);
}
client.build_with_tokio(sender, receiver)
}
pub async fn build_with_stream<S, T>(self, url: impl AsRef<str>, data_stream: T) -> Result<WsClient<S>, Error>
where
T: AsyncRead + AsyncWrite + Unpin + MaybeSend + 'static,
RpcMiddleware: tower::Layer<RpcService, Service = S> + Clone + Send + Sync + 'static,
{
let transport_builder = WsTransportClientBuilder {
#[cfg(feature = "tls")]
certificate_store: self.certificate_store.clone(),
connection_timeout: self.connection_timeout,
headers: self.headers.clone(),
max_request_size: self.max_request_size,
max_response_size: self.max_response_size,
max_redirections: self.max_redirections,
tcp_no_delay: self.tcp_no_delay,
message_encryption: self.message_encryption.clone(),
};
let uri = Url::parse(url.as_ref()).map_err(|e| Error::Transport(e.into()))?;
let (sender, receiver) =
transport_builder.build_with_stream(uri, data_stream).await.map_err(|e| Error::Transport(e.into()))?;
let ws_client = self.build_with_transport(sender, receiver);
Ok(ws_client)
}
pub async fn build<S>(self, url: impl AsRef<str>) -> Result<WsClient<S>, Error>
where
RpcMiddleware: tower::Layer<RpcService, Service = S> + Clone + Send + Sync + 'static,
{
let transport_builder = WsTransportClientBuilder {
#[cfg(feature = "tls")]
certificate_store: self.certificate_store.clone(),
connection_timeout: self.connection_timeout,
headers: self.headers.clone(),
max_request_size: self.max_request_size,
max_response_size: self.max_response_size,
max_redirections: self.max_redirections,
tcp_no_delay: self.tcp_no_delay,
message_encryption: self.message_encryption.clone(),
};
let uri = Url::parse(url.as_ref()).map_err(|e| Error::Transport(e.into()))?;
let (sender, receiver) = transport_builder.build(uri).await.map_err(|e| Error::Transport(e.into()))?;
let ws_client = self.build_with_transport(sender, receiver);
Ok(ws_client)
}
}