Skip to main content

jsonrpsee_ws_client/
lib.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! # jsonrpsee-ws-client
28//!
29//! `jsonrpsee-ws-client` is a [JSON RPC](https://www.jsonrpc.org/specification) WebSocket client library that's is built for `async/await`.
30//!
31//! ## Async runtime support
32//!
33//! This library uses `tokio` as the runtime and does not support other runtimes.
34
35#![cfg_attr(not(test), warn(unused_crate_dependencies))]
36#![cfg_attr(docsrs, feature(doc_cfg))]
37
38#[cfg(test)]
39mod tests;
40
41pub use http::{HeaderMap, HeaderValue};
42pub use jsonrpsee_core::client::Client as WsClient;
43pub use jsonrpsee_core::client::async_client::PingConfig;
44pub use jsonrpsee_core::client::async_client::RpcService;
45pub use jsonrpsee_core::middleware::RpcServiceBuilder;
46use jsonrpsee_core::middleware::layer::RpcLoggerLayer;
47pub use jsonrpsee_types as types;
48
49use jsonrpsee_client_transport::ws::{AsyncRead, AsyncWrite, WsTransportClientBuilder};
50use jsonrpsee_core::TEN_MB_SIZE_BYTES;
51use jsonrpsee_core::client::{ClientBuilder, Error, IdKind, MaybeSend, TransportReceiverT, TransportSenderT};
52use jsonrpsee_core::traits::MessageEncryption;
53use std::time::Duration;
54use url::Url;
55
56type Logger = tower::layer::util::Stack<RpcLoggerLayer, tower::layer::util::Identity>;
57
58#[cfg(feature = "tls")]
59pub use jsonrpsee_client_transport::ws::CustomCertStore;
60
61#[cfg(feature = "tls")]
62use jsonrpsee_client_transport::ws::CertificateStore;
63
64/// Builder for [`WsClient`].
65///
66/// # Examples
67///
68/// ```no_run
69///
70/// use jsonrpsee_ws_client::{WsClientBuilder, HeaderMap, HeaderValue};
71///
72/// #[tokio::main]
73/// async fn main() {
74///     // Build custom headers used during the handshake process.
75///     let mut headers = HeaderMap::new();
76///     headers.insert("Any-Header-You-Like", HeaderValue::from_static("42"));
77///
78///     // Build client
79///     let client = WsClientBuilder::default()
80///          .set_headers(headers)
81///          .build("wss://localhost:443")
82///          .await
83///          .unwrap();
84///
85///     // use client....
86/// }
87///
88/// ```
89#[derive(Clone, Debug)]
90pub struct WsClientBuilder<RpcMiddleware = Logger> {
91	#[cfg(feature = "tls")]
92	certificate_store: CertificateStore,
93	max_request_size: u32,
94	max_response_size: u32,
95	request_timeout: Duration,
96	connection_timeout: Duration,
97	ping_config: Option<PingConfig>,
98	headers: http::HeaderMap,
99	max_concurrent_requests: usize,
100	max_buffer_capacity_per_subscription: usize,
101	max_redirections: usize,
102	id_kind: IdKind,
103	tcp_no_delay: bool,
104	service_builder: RpcServiceBuilder<RpcMiddleware>,
105	message_encryption: Option<std::sync::Arc<dyn MessageEncryption>>,
106}
107
108impl Default for WsClientBuilder {
109	fn default() -> Self {
110		Self {
111			#[cfg(feature = "tls")]
112			certificate_store: CertificateStore::Native,
113			max_request_size: TEN_MB_SIZE_BYTES,
114			max_response_size: TEN_MB_SIZE_BYTES,
115			request_timeout: Duration::from_secs(60),
116			connection_timeout: Duration::from_secs(10),
117			ping_config: None,
118			headers: HeaderMap::new(),
119			max_concurrent_requests: 256,
120			max_buffer_capacity_per_subscription: 1024,
121			max_redirections: 5,
122			id_kind: IdKind::Number,
123			tcp_no_delay: true,
124			service_builder: RpcServiceBuilder::default().rpc_logger(1024),
125			message_encryption: None,
126		}
127	}
128}
129
130impl WsClientBuilder {
131	/// Create a new WebSocket client builder.
132	pub fn new() -> WsClientBuilder {
133		WsClientBuilder::default()
134	}
135}
136
137impl<RpcMiddleware> WsClientBuilder<RpcMiddleware> {
138	/// Force to use a custom certificate store.
139	///
140	/// # Optional
141	///
142	/// This requires the optional `tls` feature.
143	///
144	/// # Example
145	///
146	/// ```no_run
147	/// use jsonrpsee_ws_client::{WsClientBuilder, CustomCertStore};
148	/// use rustls::{
149	///     client::danger::{self, HandshakeSignatureValid, ServerCertVerified},
150	///     pki_types::{CertificateDer, ServerName, UnixTime},
151	///     Error,
152	/// };
153	///
154	/// #[derive(Debug)]
155	/// struct NoCertificateVerification;
156	///
157	/// impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
158	///     fn verify_server_cert(
159	///         &self,
160	///         _: &CertificateDer<'_>,
161	///         _: &[CertificateDer<'_>],
162	///         _: &ServerName<'_>,
163	///         _: &[u8],
164	///         _: UnixTime,
165	///     ) -> Result<ServerCertVerified, Error> {
166	///         Ok(ServerCertVerified::assertion())
167	///     }
168	///
169	///     fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
170	///         vec![rustls::SignatureScheme::ECDSA_NISTP256_SHA256]
171	///     }
172	///
173	///     fn verify_tls12_signature(
174	///         &self,
175	///         _: &[u8],
176	///         _: &CertificateDer<'_>,
177	///         _: &rustls::DigitallySignedStruct,
178	///     ) -> Result<rustls::client::danger::HandshakeSignatureValid, Error> {
179	///         Ok(HandshakeSignatureValid::assertion())
180	///     }
181	///
182	///     fn verify_tls13_signature(
183	///         &self,
184	///         _: &[u8],
185	///         _: &CertificateDer<'_>,
186	///         _: &rustls::DigitallySignedStruct,
187	///     ) -> Result<HandshakeSignatureValid, Error> {
188	///         Ok(HandshakeSignatureValid::assertion())
189	///     }
190	/// }
191	///
192	/// let tls_cfg = CustomCertStore::builder()
193	///    .dangerous()
194	///    .with_custom_certificate_verifier(std::sync::Arc::new(NoCertificateVerification))
195	///    .with_no_client_auth();
196	///
197	/// // client builder with disabled certificate verification.
198	/// let client_builder = WsClientBuilder::new().with_custom_cert_store(tls_cfg);
199	/// ```
200	#[cfg(feature = "tls")]
201	pub fn with_custom_cert_store(mut self, cfg: CustomCertStore) -> Self {
202		self.certificate_store = CertificateStore::Custom(cfg);
203		self
204	}
205
206	/// See documentation [`WsTransportClientBuilder::max_request_size`] (default is 10 MB).
207	pub fn max_request_size(mut self, size: u32) -> Self {
208		self.max_request_size = size;
209		self
210	}
211
212	/// See documentation [`WsTransportClientBuilder::max_response_size`] (default is 10 MB).
213	pub fn max_response_size(mut self, size: u32) -> Self {
214		self.max_response_size = size;
215		self
216	}
217
218	/// See documentation [`ClientBuilder::request_timeout`] (default is 60 seconds).
219	pub fn request_timeout(mut self, timeout: Duration) -> Self {
220		self.request_timeout = timeout;
221		self
222	}
223
224	/// See documentation [`WsTransportClientBuilder::connection_timeout`] (default is 10 seconds).
225	pub fn connection_timeout(mut self, timeout: Duration) -> Self {
226		self.connection_timeout = timeout;
227		self
228	}
229
230	/// See documentation [`ClientBuilder::enable_ws_ping`] (disabled by default).
231	pub fn enable_ws_ping(mut self, cfg: PingConfig) -> Self {
232		self.ping_config = Some(cfg);
233		self
234	}
235
236	/// See documentation [`ClientBuilder::disable_ws_ping`]
237	pub fn disable_ws_ping(mut self) -> Self {
238		self.ping_config = None;
239		self
240	}
241
242	/// See documentation [`WsTransportClientBuilder::set_headers`] (default is none).
243	pub fn set_headers(mut self, headers: http::HeaderMap) -> Self {
244		self.headers = headers;
245		self
246	}
247
248	/// See documentation [`ClientBuilder::max_concurrent_requests`] (default is 256).
249	pub fn max_concurrent_requests(mut self, max: usize) -> Self {
250		self.max_concurrent_requests = max;
251		self
252	}
253
254	/// See documentation [`ClientBuilder::max_buffer_capacity_per_subscription`] (default is 1024).
255	pub fn max_buffer_capacity_per_subscription(mut self, max: usize) -> Self {
256		self.max_buffer_capacity_per_subscription = max;
257		self
258	}
259
260	/// See documentation [`WsTransportClientBuilder::max_redirections`] (default is 5).
261	pub fn max_redirections(mut self, redirect: usize) -> Self {
262		self.max_redirections = redirect;
263		self
264	}
265
266	/// See documentation for [`ClientBuilder::id_format`] (default is Number).
267	pub fn id_format(mut self, kind: IdKind) -> Self {
268		self.id_kind = kind;
269		self
270	}
271
272	/// See documentation [`ClientBuilder::set_tcp_no_delay`] (default is true).
273	pub fn set_tcp_no_delay(mut self, no_delay: bool) -> Self {
274		self.tcp_no_delay = no_delay;
275		self
276	}
277
278	/// Set message encryption implementation.
279	pub fn set_message_encryption<E: MessageEncryption>(mut self, encryption: E) -> Self {
280		self.message_encryption = Some(std::sync::Arc::new(encryption));
281		self
282	}
283
284	/// Set the RPC service builder.
285	pub fn set_rpc_middleware<T>(self, service_builder: RpcServiceBuilder<T>) -> WsClientBuilder<T> {
286		WsClientBuilder {
287			#[cfg(feature = "tls")]
288			certificate_store: self.certificate_store,
289			max_request_size: self.max_request_size,
290			max_response_size: self.max_response_size,
291			request_timeout: self.request_timeout,
292			connection_timeout: self.connection_timeout,
293			ping_config: self.ping_config,
294			headers: self.headers,
295			max_concurrent_requests: self.max_concurrent_requests,
296			max_buffer_capacity_per_subscription: self.max_buffer_capacity_per_subscription,
297			max_redirections: self.max_redirections,
298			id_kind: self.id_kind,
299			tcp_no_delay: self.tcp_no_delay,
300			service_builder,
301			message_encryption: self.message_encryption,
302		}
303	}
304
305	/// Build the [`WsClient`] with specified [`TransportSenderT`] [`TransportReceiverT`] parameters
306	///
307	/// ## Panics
308	///
309	/// Panics if being called outside of `tokio` runtime context.
310	pub fn build_with_transport<S, R, Svc>(self, sender: S, receiver: R) -> WsClient<Svc>
311	where
312		S: TransportSenderT + Send,
313		R: TransportReceiverT + Send,
314		RpcMiddleware: tower::Layer<RpcService, Service = Svc> + Clone + Send + Sync + 'static,
315	{
316		let Self {
317			max_concurrent_requests,
318			request_timeout,
319			ping_config,
320			max_buffer_capacity_per_subscription,
321			id_kind,
322			tcp_no_delay,
323			service_builder,
324			..
325		} = self;
326
327		let mut client = ClientBuilder::default()
328			.max_buffer_capacity_per_subscription(max_buffer_capacity_per_subscription)
329			.request_timeout(request_timeout)
330			.max_concurrent_requests(max_concurrent_requests)
331			.id_format(id_kind)
332			.set_tcp_no_delay(tcp_no_delay)
333			.set_rpc_middleware(service_builder);
334
335		if let Some(cfg) = ping_config {
336			client = client.enable_ws_ping(cfg);
337		}
338
339		client.build_with_tokio(sender, receiver)
340	}
341
342	/// Build the [`WsClient`] with specified data stream, using [`WsTransportClientBuilder::build_with_stream`].
343	///
344	/// ## Panics
345	///
346	/// Panics if being called outside of `tokio` runtime context.
347	pub async fn build_with_stream<S, T>(self, url: impl AsRef<str>, data_stream: T) -> Result<WsClient<S>, Error>
348	where
349		T: AsyncRead + AsyncWrite + Unpin + MaybeSend + 'static,
350		RpcMiddleware: tower::Layer<RpcService, Service = S> + Clone + Send + Sync + 'static,
351	{
352		let transport_builder = WsTransportClientBuilder {
353			#[cfg(feature = "tls")]
354			certificate_store: self.certificate_store.clone(),
355			connection_timeout: self.connection_timeout,
356			headers: self.headers.clone(),
357			max_request_size: self.max_request_size,
358			max_response_size: self.max_response_size,
359			max_redirections: self.max_redirections,
360			tcp_no_delay: self.tcp_no_delay,
361			message_encryption: self.message_encryption.clone(),
362		};
363
364		let uri = Url::parse(url.as_ref()).map_err(|e| Error::Transport(e.into()))?;
365		let (sender, receiver) =
366			transport_builder.build_with_stream(uri, data_stream).await.map_err(|e| Error::Transport(e.into()))?;
367
368		let ws_client = self.build_with_transport(sender, receiver);
369		Ok(ws_client)
370	}
371
372	/// Build the [`WsClient`] with specified URL to connect to, using the default
373	/// [`WsTransportClientBuilder::build_with_stream`], therefore with the default TCP as transport layer.
374	///
375	/// ## Panics
376	///
377	/// Panics if being called outside of `tokio` runtime context.
378	pub async fn build<S>(self, url: impl AsRef<str>) -> Result<WsClient<S>, Error>
379	where
380		RpcMiddleware: tower::Layer<RpcService, Service = S> + Clone + Send + Sync + 'static,
381	{
382		let transport_builder = WsTransportClientBuilder {
383			#[cfg(feature = "tls")]
384			certificate_store: self.certificate_store.clone(),
385			connection_timeout: self.connection_timeout,
386			headers: self.headers.clone(),
387			max_request_size: self.max_request_size,
388			max_response_size: self.max_response_size,
389			max_redirections: self.max_redirections,
390			tcp_no_delay: self.tcp_no_delay,
391			message_encryption: self.message_encryption.clone(),
392		};
393
394		let uri = Url::parse(url.as_ref()).map_err(|e| Error::Transport(e.into()))?;
395		let (sender, receiver) = transport_builder.build(uri).await.map_err(|e| Error::Transport(e.into()))?;
396
397		let ws_client = self.build_with_transport(sender, receiver);
398		Ok(ws_client)
399	}
400}