From cb3e37d3bfc7ceb1fbf6201106cbf5f57594b14d Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Sun, 5 Dec 2021 22:56:24 +0000 Subject: [PATCH 01/24] Nuke V2 --- http-client/src/client.rs | 5 +++-- http-client/src/tests.rs | 4 ++-- http-server/src/response.rs | 3 ++- http-server/src/server.rs | 5 ++--- proc-macros/src/render_client.rs | 8 ++++---- types/src/client.rs | 2 +- types/src/{ => error}/error.rs | 0 types/src/{v2 => error}/mod.rs | 18 +++++++----------- types/src/{v2/error.rs => error/rpc.rs} | 2 +- types/src/lib.rs | 18 ++++++++++++++---- types/src/{v2 => }/params.rs | 6 +++--- types/src/{v2 => }/request.rs | 2 +- types/src/{v2 => }/response.rs | 6 ++---- types/src/traits.rs | 2 +- utils/src/client.rs | 2 +- utils/src/server/helpers.rs | 12 +++++------- utils/src/server/rpc_module.rs | 18 +++++++----------- ws-client/src/client.rs | 7 ++++--- ws-client/src/helpers.rs | 7 +++---- ws-client/src/manager.rs | 4 ++-- ws-client/src/tests.rs | 4 ++-- ws-server/src/server.rs | 8 ++------ ws-server/src/tests.rs | 8 ++++---- 23 files changed, 73 insertions(+), 78 deletions(-) rename types/src/{ => error}/error.rs (100%) rename types/src/{v2 => error}/mod.rs (73%) rename types/src/{v2/error.rs => error/rpc.rs} (99%) rename types/src/{v2 => }/params.rs (99%) rename types/src/{v2 => }/request.rs (99%) rename types/src/{v2 => }/response.rs (96%) diff --git a/http-client/src/client.rs b/http-client/src/client.rs index 7d28994ea4..504e081c7a 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -27,8 +27,9 @@ use crate::transport::HttpTransportClient; use crate::types::{ traits::{Client, SubscriptionClient}, - v2::{Id, NotificationSer, ParamsSer, RequestSer, Response, RpcError}, - CertificateStore, Error, RequestIdManager, Subscription, TEN_MB_SIZE_BYTES, + RpcError, + CertificateStore, Error, Id, NotificationSer, ParamsSer, RequestIdManager, RequestSer, Response, Subscription, + TEN_MB_SIZE_BYTES, }; use async_trait::async_trait; use fnv::FnvHashMap; diff --git a/http-client/src/tests.rs b/http-client/src/tests.rs index d70bbc0218..2933eddfd0 100644 --- a/http-client/src/tests.rs +++ b/http-client/src/tests.rs @@ -26,8 +26,8 @@ use crate::types::{ traits::Client, - v2::{ErrorCode, ErrorObject, ParamsSer, RpcError}, - Error, JsonValue, + error::{Error, ErrorCode, ErrorObject, RpcError}, + JsonValue, ParamsSer, }; use crate::HttpClientBuilder; use jsonrpsee_test_utils::helpers::*; diff --git a/http-server/src/response.rs b/http-server/src/response.rs index 18f2313fdf..1491405493 100644 --- a/http-server/src/response.rs +++ b/http-server/src/response.rs @@ -26,7 +26,8 @@ //! Contains common builders for hyper responses. -use crate::types::v2::{ErrorCode, Id, RpcError, TwoPointZero}; +use crate::types::error::{ErrorCode, RpcError}; +use crate::types::{Id, TwoPointZero}; const JSON: &str = "application/json; charset=utf-8"; const TEXT: &str = "text/plain"; diff --git a/http-server/src/server.rs b/http-server/src/server.rs index 7ecb9f7025..790d7c0ab6 100644 --- a/http-server/src/server.rs +++ b/http-server/src/server.rs @@ -33,10 +33,9 @@ use hyper::{ Error as HyperError, }; use jsonrpsee_types::{ - error::{Error, GenericTransportError}, + error::{Error, ErrorCode, GenericTransportError}, middleware::Middleware, - v2::{ErrorCode, Id, Notification, Request}, - TEN_MB_SIZE_BYTES, + Id, Notification, Request, TEN_MB_SIZE_BYTES, }; use jsonrpsee_utils::http_helpers::read_body; use jsonrpsee_utils::server::{ diff --git a/proc-macros/src/render_client.rs b/proc-macros/src/render_client.rs index 8ec3020f29..fdc6f26e44 100644 --- a/proc-macros/src/render_client.rs +++ b/proc-macros/src/render_client.rs @@ -165,12 +165,12 @@ impl RpcDescription { quote! { (#param, #value) } }); quote! { - Some(types::v2::ParamsSer::Map( - std::collections::BTreeMap::<&str, #serde_json::Value>::from( - [#(#params),*] - ) + Some(types::ParamsSer::Map( + std::collections::BTreeMap::<&str, #serde_json::Value>::from( + [#(#params),*] ) ) + ) } } ParamKind::Array => { diff --git a/types/src/client.rs b/types/src/client.rs index c0a0cf0685..efa02c20c5 100644 --- a/types/src/client.rs +++ b/types/src/client.rs @@ -24,7 +24,7 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::{error::SubscriptionClosedError, v2::SubscriptionId, Error}; +use crate::{error::SubscriptionClosedError, Error, SubscriptionId}; use core::marker::PhantomData; use futures_channel::{mpsc, oneshot}; use futures_util::{future::FutureExt, sink::SinkExt, stream::StreamExt}; diff --git a/types/src/error.rs b/types/src/error/error.rs similarity index 100% rename from types/src/error.rs rename to types/src/error/error.rs diff --git a/types/src/v2/mod.rs b/types/src/error/mod.rs similarity index 73% rename from types/src/v2/mod.rs rename to types/src/error/mod.rs index d3dcfdb245..abe3e79976 100644 --- a/types/src/v2/mod.rs +++ b/types/src/error/mod.rs @@ -25,17 +25,13 @@ // DEALINGS IN THE SOFTWARE. //! Types to handle in- and outgoing JSON-RPC requests and subscriptions according to the [spec](https://www.jsonrpc.org/specification). +/// Error type. + +/// Main `Error` type. +mod error; /// JSON-RPC error related types. -pub mod error; -/// JSON_RPC params related types. -pub mod params; -/// JSON-RPC request object related types -pub mod request; -/// JSON-RPC response object related types. -pub mod response; +pub mod rpc; -pub use error::{ErrorCode, ErrorObject, RpcError}; -pub use params::{Id, Params, ParamsSequence, ParamsSer, SubscriptionId, TwoPointZero}; -pub use request::{InvalidRequest, Notification, NotificationSer, Request, RequestSer}; -pub use response::{Response, SubscriptionPayload, SubscriptionResponse}; +pub use rpc::{ErrorCode, ErrorObject, RpcError}; +pub use error::{Error, CallError, SubscriptionClosedError, GenericTransportError}; diff --git a/types/src/v2/error.rs b/types/src/error/rpc.rs similarity index 99% rename from types/src/v2/error.rs rename to types/src/error/rpc.rs index c5e1dc1ddd..dc702d12ed 100644 --- a/types/src/v2/error.rs +++ b/types/src/error/rpc.rs @@ -24,7 +24,7 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::params::{Id, TwoPointZero}; +use crate::params::{Id, TwoPointZero}; use beef::Cow; use serde::de::Deserializer; use serde::ser::Serializer; diff --git a/types/src/lib.rs b/types/src/lib.rs index a932e94d5c..71ef1bed1e 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -34,9 +34,6 @@ extern crate alloc; /// Ten megabytes. pub const TEN_MB_SIZE_BYTES: u32 = 10 * 1024 * 1024; -/// JSON-RPC v2.0 specification related types. -pub mod v2; - /// Error type. pub mod error; @@ -49,10 +46,20 @@ pub mod traits; /// Middleware trait and implementation. pub mod middleware; +/// JSON_RPC params related types. +pub mod params; + +/// JSON-RPC request object related types +pub mod request; + +/// JSON-RPC response object related types. +pub mod response; + pub use async_trait::async_trait; pub use beef::Cow; pub use client::*; -pub use error::{CallError, Error}; +pub use error::{CallError, Error, RpcError}; +pub use params::{Id, Params, ParamsSequence, ParamsSer, SubscriptionId, TwoPointZero}; pub use serde::{de::DeserializeOwned, Serialize}; pub use serde_json::{ to_value as to_json_value, value::to_raw_value as to_json_raw_value, value::RawValue as JsonRawValue, @@ -70,3 +77,6 @@ pub mod __reexports { /// JSON-RPC result. pub type RpcResult = std::result::Result; + +pub use request::{InvalidRequest, Notification, NotificationSer, Request, RequestSer}; +pub use response::{Response, SubscriptionPayload, SubscriptionResponse}; diff --git a/types/src/v2/params.rs b/types/src/params.rs similarity index 99% rename from types/src/v2/params.rs rename to types/src/params.rs index ea399be59b..d304bbe559 100644 --- a/types/src/v2/params.rs +++ b/types/src/params.rs @@ -199,7 +199,7 @@ impl<'a> ParamsSequence<'a> { /// Parse the next parameter to type `T` /// /// ``` - /// # use jsonrpsee_types::v2::params::Params; + /// # use jsonrpsee_types::params::Params; /// let params = Params::new(Some(r#"[true, 10, "foo"]"#)); /// let mut seq = params.sequence(); /// @@ -226,7 +226,7 @@ impl<'a> ParamsSequence<'a> { /// The result will be `None` for `null`, and for missing values in the supplied JSON array. /// /// ``` - /// # use jsonrpsee_types::v2::params::Params; + /// # use jsonrpsee_types::params::Params; /// let params = Params::new(Some(r#"[1, 2, null]"#)); /// let mut seq = params.sequence(); /// @@ -358,7 +358,7 @@ impl<'a> Id<'a> { #[cfg(test)] mod test { use super::{Cow, Id, JsonValue, Params, ParamsSer, SubscriptionId, TwoPointZero}; - use crate::v2::response::SubscriptionPayload; + use crate::response::SubscriptionPayload; #[test] fn id_deserialization() { diff --git a/types/src/v2/request.rs b/types/src/request.rs similarity index 99% rename from types/src/v2/request.rs rename to types/src/request.rs index e63ee3ef97..28d2f48092 100644 --- a/types/src/v2/request.rs +++ b/types/src/request.rs @@ -27,7 +27,7 @@ //! Types to handle JSON-RPC requests according to the [spec](https://www.jsonrpc.org/specification#request-object). //! Some types come with a "*Ser" variant that implements [`serde::Serialize`]; these are used in the client. -use crate::v2::params::{Id, ParamsSer, TwoPointZero}; +use crate::params::{Id, ParamsSer, TwoPointZero}; use beef::Cow; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; diff --git a/types/src/v2/response.rs b/types/src/response.rs similarity index 96% rename from types/src/v2/response.rs rename to types/src/response.rs index 1936614fa7..90aa530f0a 100644 --- a/types/src/v2/response.rs +++ b/types/src/response.rs @@ -26,10 +26,8 @@ //! Types pertaining to JSON-RPC responses. -use crate::v2::{ - params::{Id, SubscriptionId, TwoPointZero}, - request::Notification, -}; +use crate::params::{Id, SubscriptionId, TwoPointZero}; +use crate::request::Notification; use serde::{Deserialize, Serialize}; /// JSON-RPC successful response object as defined in the [spec](https://www.jsonrpc.org/specification#response_object). diff --git a/types/src/traits.rs b/types/src/traits.rs index 042c0e24d6..7392f7b326 100644 --- a/types/src/traits.rs +++ b/types/src/traits.rs @@ -24,7 +24,7 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::v2::ParamsSer; +use crate::ParamsSer; use crate::{Error, Subscription}; use async_trait::async_trait; use serde::de::DeserializeOwned; diff --git a/utils/src/client.rs b/utils/src/client.rs index e765472e6c..bcd8bf1a45 100644 --- a/utils/src/client.rs +++ b/utils/src/client.rs @@ -28,7 +28,7 @@ #[doc(hidden)] pub mod __reexports { - pub use jsonrpsee_types::{to_json_value, v2::ParamsSer}; + pub use jsonrpsee_types::{to_json_value, ParamsSer}; } #[macro_export] diff --git a/utils/src/server/helpers.rs b/utils/src/server/helpers.rs index 25d863f07e..06643a9e04 100644 --- a/utils/src/server/helpers.rs +++ b/utils/src/server/helpers.rs @@ -26,13 +26,11 @@ use futures_channel::mpsc; use futures_util::stream::StreamExt; -use jsonrpsee_types::error::{CallError, Error}; -use jsonrpsee_types::to_json_raw_value; -use jsonrpsee_types::v2::error::{OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG}; -use jsonrpsee_types::v2::{ - error::{CALL_EXECUTION_FAILED_CODE, UNKNOWN_ERROR_CODE}, - ErrorCode, ErrorObject, Id, InvalidRequest, Response, RpcError, TwoPointZero, -}; +use jsonrpsee_types::error::{CallError, Error, ErrorCode, ErrorObject, RpcError}; +use jsonrpsee_types::error::rpc::{OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG}; +use jsonrpsee_types::error::rpc::{CALL_EXECUTION_FAILED_CODE, UNKNOWN_ERROR_CODE}; +use jsonrpsee_types::{to_json_raw_value, Id, TwoPointZero}; +use jsonrpsee_types::{InvalidRequest, Response}; use serde::Serialize; use std::io; diff --git a/utils/src/server/rpc_module.rs b/utils/src/server/rpc_module.rs index 9ba5aaf7ed..2c4ca8dc7c 100644 --- a/utils/src/server/rpc_module.rs +++ b/utils/src/server/rpc_module.rs @@ -30,15 +30,12 @@ use beef::Cow; use futures_channel::{mpsc, oneshot}; use futures_util::{future::BoxFuture, FutureExt, StreamExt}; use jsonrpsee_types::to_json_raw_value; -use jsonrpsee_types::v2::error::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}; +use jsonrpsee_types::error::rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}; use jsonrpsee_types::{ - error::{Error, SubscriptionClosedError}, + error::{Error, SubscriptionClosedError, ErrorCode}, traits::ToRpcParams, - v2::{ - ErrorCode, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, - SubscriptionResponse, TwoPointZero, - }, - DeserializeOwned, + DeserializeOwned, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, + SubscriptionResponse, TwoPointZero, }; use parking_lot::Mutex; @@ -782,7 +779,7 @@ impl TestSubscription { /// # Panics /// /// If the decoding the value as `T` fails. - pub async fn next(&mut self) -> Option<(T, jsonrpsee_types::v2::SubscriptionId)> { + pub async fn next(&mut self) -> Option<(T, RpcSubscriptionId)> { let raw = self.rx.next().await?; let val: SubscriptionResponse = serde_json::from_str(&raw).expect("valid response in TestSubscription::next()"); @@ -799,7 +796,6 @@ impl Drop for TestSubscription { #[cfg(test)] mod tests { use super::*; - use jsonrpsee_types::v2; use serde::Deserialize; use std::collections::HashMap; @@ -980,7 +976,7 @@ mod tests { for i in (0..=2).rev() { let (val, id) = my_sub.next::().await.unwrap(); assert_eq!(val, std::char::from_digit(i, 10).unwrap()); - assert_eq!(id, v2::params::SubscriptionId::Num(my_sub.subscription_id())); + assert_eq!(id, RpcSubscriptionId::Num(my_sub.subscription_id())); } // The subscription is now closed by the server. @@ -1007,7 +1003,7 @@ mod tests { let mut my_sub: TestSubscription = module.test_subscription("my_sub", Vec::<()>::new()).await; let (val, id) = my_sub.next::().await.unwrap(); assert_eq!(&val, "lo"); - assert_eq!(id, v2::params::SubscriptionId::Num(my_sub.subscription_id())); + assert_eq!(id, RpcSubscriptionId::Num(my_sub.subscription_id())); // close the subscription to ensure it doesn't return any items. my_sub.close(); diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index aa7e90d0db..b190ed7679 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -27,9 +27,10 @@ use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; use crate::types::{ traits::{Client, SubscriptionClient}, - v2::{Id, Notification, NotificationSer, ParamsSer, RequestSer, Response, RpcError, SubscriptionResponse}, - BatchMessage, CertificateStore, Error, FrontToBack, RegisterNotificationMessage, RequestIdManager, RequestMessage, - Subscription, SubscriptionKind, SubscriptionMessage, TEN_MB_SIZE_BYTES, + RpcError, + BatchMessage, CertificateStore, Error, FrontToBack, Id, Notification, NotificationSer, ParamsSer, + RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, Subscription, + SubscriptionKind, SubscriptionMessage, SubscriptionResponse, TEN_MB_SIZE_BYTES, }; use crate::{ helpers::{ diff --git a/ws-client/src/helpers.rs b/ws-client/src/helpers.rs index 7be177ff7c..57fa05d2ff 100644 --- a/ws-client/src/helpers.rs +++ b/ws-client/src/helpers.rs @@ -26,10 +26,9 @@ use crate::manager::{RequestManager, RequestStatus}; use crate::transport::Sender as WsSender; -use crate::types::v2::{ - Id, Notification, ParamsSer, RequestSer, Response, RpcError, SubscriptionId, SubscriptionResponse, -}; -use crate::types::{Error, RequestMessage}; +use crate::types::{Error, RequestMessage, RpcError}; +use crate::types::{Id, ParamsSer, SubscriptionId}; +use crate::types::{Notification, RequestSer, Response, SubscriptionResponse}; use futures::channel::{mpsc, oneshot}; use serde_json::Value as JsonValue; use std::time::Duration; diff --git a/ws-client/src/manager.rs b/ws-client/src/manager.rs index 3e67e3ca86..ca43d5d797 100644 --- a/ws-client/src/manager.rs +++ b/ws-client/src/manager.rs @@ -32,7 +32,7 @@ //! > **Note**: The spec allow number, string or null but this crate only supports numbers. //! - SubscriptionId: unique ID generated by server -use crate::types::{v2::SubscriptionId, Error, JsonValue}; +use crate::types::{Error, JsonValue, SubscriptionId}; use fnv::FnvHashMap; use futures::channel::{mpsc, oneshot}; use std::collections::hash_map::{Entry, HashMap}; @@ -308,7 +308,7 @@ impl RequestManager { mod tests { use super::{Error, RequestManager}; use futures::channel::{mpsc, oneshot}; - use jsonrpsee_types::v2::SubscriptionId; + use jsonrpsee_types::SubscriptionId; use serde_json::Value as JsonValue; #[test] diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index a905501e07..69419e297a 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -27,8 +27,8 @@ #![cfg(test)] use crate::types::{ traits::{Client, SubscriptionClient}, - v2::{ErrorCode, ErrorObject, ParamsSer, RpcError}, - Error, Subscription, + error::{Error, ErrorCode, ErrorObject, RpcError}, + ParamsSer, Subscription, }; use crate::WsClientBuilder; use jsonrpsee_test_utils::helpers::*; diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index f60df7e682..ab2da7bfd1 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -30,12 +30,8 @@ use std::pin::Pin; use std::task::{Context, Poll}; use crate::future::{FutureDriver, ServerHandle, StopMonitor}; -use crate::types::{ - error::Error, - middleware::Middleware, - v2::{ErrorCode, Id, Request}, - TEN_MB_SIZE_BYTES, -}; +use crate::types::error::{Error, ErrorCode}; +use crate::types::{middleware::Middleware, Id, Request, TEN_MB_SIZE_BYTES}; use futures_channel::mpsc; use futures_util::future::join_all; use futures_util::future::FutureExt; diff --git a/ws-server/src/tests.rs b/ws-server/src/tests.rs index 67e5f36f66..d047a5cae9 100644 --- a/ws-server/src/tests.rs +++ b/ws-server/src/tests.rs @@ -27,8 +27,8 @@ #![cfg(test)] use crate::types::error::{CallError, Error}; -use crate::types::v2::{self, Response, RpcError}; use crate::types::DeserializeOwned; +use crate::types::{self, Response, RpcError}; use crate::{future::ServerHandle, RpcModule, WsServerBuilder}; use anyhow::anyhow; use futures_util::future::join; @@ -36,7 +36,7 @@ use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, TestContext, WebSocketTestClient, WebSocketTestError}; use jsonrpsee_test_utils::TimeoutFutureExt; use jsonrpsee_types::to_json_raw_value; -use jsonrpsee_types::v2::error::invalid_subscription_err; +use jsonrpsee_types::error::rpc::invalid_subscription_err; use serde_json::Value as JsonValue; use std::{fmt, net::SocketAddr, time::Duration}; use tracing_subscriber::{EnvFilter, FmtSubscriber}; @@ -611,7 +611,7 @@ async fn unsubscribe_twice_should_indicate_error() { let sub_id = to_json_raw_value(&sub_id).unwrap(); let err = Some(to_json_raw_value(&format!("Invalid subscription ID={}", sub_id)).unwrap()); - assert_eq!(unsub_2_err, RpcError::new(invalid_subscription_err(err.as_deref()), v2::Id::Number(2))); + assert_eq!(unsub_2_err, RpcError::new(invalid_subscription_err(err.as_deref()), types::Id::Number(2))); } #[tokio::test] @@ -624,5 +624,5 @@ async fn unsubscribe_wrong_sub_id_type() { client.send_request_text(call("unsubscribe_hello", vec!["string_is_not_supported"], Id::Num(0))).await.unwrap(); let unsub_2_err: RpcError = serde_json::from_str(&unsub).unwrap(); let err = Some(to_json_raw_value(&"Invalid subscription ID type, must be integer").unwrap()); - assert_eq!(unsub_2_err, RpcError::new(invalid_subscription_err(err.as_deref()), v2::Id::Number(0))); + assert_eq!(unsub_2_err, RpcError::new(invalid_subscription_err(err.as_deref()), types::Id::Number(0))); } From 09ceb908335169eee960b91d3b5a69cdf4113876 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Sun, 5 Dec 2021 22:56:46 +0000 Subject: [PATCH 02/24] fmt --- http-client/src/client.rs | 5 ++--- http-client/src/tests.rs | 2 +- types/src/error/mod.rs | 2 +- utils/src/server/helpers.rs | 4 ++-- utils/src/server/rpc_module.rs | 4 ++-- ws-client/src/client.rs | 3 +-- ws-client/src/tests.rs | 2 +- ws-server/src/tests.rs | 2 +- 8 files changed, 11 insertions(+), 13 deletions(-) diff --git a/http-client/src/client.rs b/http-client/src/client.rs index 504e081c7a..ad063156ab 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -27,9 +27,8 @@ use crate::transport::HttpTransportClient; use crate::types::{ traits::{Client, SubscriptionClient}, - RpcError, - CertificateStore, Error, Id, NotificationSer, ParamsSer, RequestIdManager, RequestSer, Response, Subscription, - TEN_MB_SIZE_BYTES, + CertificateStore, Error, Id, NotificationSer, ParamsSer, RequestIdManager, RequestSer, Response, RpcError, + Subscription, TEN_MB_SIZE_BYTES, }; use async_trait::async_trait; use fnv::FnvHashMap; diff --git a/http-client/src/tests.rs b/http-client/src/tests.rs index 2933eddfd0..fdbcec8dc2 100644 --- a/http-client/src/tests.rs +++ b/http-client/src/tests.rs @@ -25,8 +25,8 @@ // DEALINGS IN THE SOFTWARE. use crate::types::{ - traits::Client, error::{Error, ErrorCode, ErrorObject, RpcError}, + traits::Client, JsonValue, ParamsSer, }; use crate::HttpClientBuilder; diff --git a/types/src/error/mod.rs b/types/src/error/mod.rs index abe3e79976..7d357d05e2 100644 --- a/types/src/error/mod.rs +++ b/types/src/error/mod.rs @@ -33,5 +33,5 @@ mod error; /// JSON-RPC error related types. pub mod rpc; +pub use error::{CallError, Error, GenericTransportError, SubscriptionClosedError}; pub use rpc::{ErrorCode, ErrorObject, RpcError}; -pub use error::{Error, CallError, SubscriptionClosedError, GenericTransportError}; diff --git a/utils/src/server/helpers.rs b/utils/src/server/helpers.rs index 06643a9e04..e59940b309 100644 --- a/utils/src/server/helpers.rs +++ b/utils/src/server/helpers.rs @@ -26,9 +26,9 @@ use futures_channel::mpsc; use futures_util::stream::StreamExt; -use jsonrpsee_types::error::{CallError, Error, ErrorCode, ErrorObject, RpcError}; -use jsonrpsee_types::error::rpc::{OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG}; use jsonrpsee_types::error::rpc::{CALL_EXECUTION_FAILED_CODE, UNKNOWN_ERROR_CODE}; +use jsonrpsee_types::error::rpc::{OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG}; +use jsonrpsee_types::error::{CallError, Error, ErrorCode, ErrorObject, RpcError}; use jsonrpsee_types::{to_json_raw_value, Id, TwoPointZero}; use jsonrpsee_types::{InvalidRequest, Response}; use serde::Serialize; diff --git a/utils/src/server/rpc_module.rs b/utils/src/server/rpc_module.rs index 2c4ca8dc7c..ce624e4ff0 100644 --- a/utils/src/server/rpc_module.rs +++ b/utils/src/server/rpc_module.rs @@ -29,10 +29,10 @@ use crate::server::resource_limiting::{ResourceGuard, ResourceTable, ResourceVec use beef::Cow; use futures_channel::{mpsc, oneshot}; use futures_util::{future::BoxFuture, FutureExt, StreamExt}; -use jsonrpsee_types::to_json_raw_value; use jsonrpsee_types::error::rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}; +use jsonrpsee_types::to_json_raw_value; use jsonrpsee_types::{ - error::{Error, SubscriptionClosedError, ErrorCode}, + error::{Error, ErrorCode, SubscriptionClosedError}, traits::ToRpcParams, DeserializeOwned, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, SubscriptionResponse, TwoPointZero, diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index b190ed7679..8544c65821 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -27,9 +27,8 @@ use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; use crate::types::{ traits::{Client, SubscriptionClient}, - RpcError, BatchMessage, CertificateStore, Error, FrontToBack, Id, Notification, NotificationSer, ParamsSer, - RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, Subscription, + RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, RpcError, Subscription, SubscriptionKind, SubscriptionMessage, SubscriptionResponse, TEN_MB_SIZE_BYTES, }; use crate::{ diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index 69419e297a..58b9fb2069 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -26,8 +26,8 @@ #![cfg(test)] use crate::types::{ - traits::{Client, SubscriptionClient}, error::{Error, ErrorCode, ErrorObject, RpcError}, + traits::{Client, SubscriptionClient}, ParamsSer, Subscription, }; use crate::WsClientBuilder; diff --git a/ws-server/src/tests.rs b/ws-server/src/tests.rs index d047a5cae9..c558e24e46 100644 --- a/ws-server/src/tests.rs +++ b/ws-server/src/tests.rs @@ -35,8 +35,8 @@ use futures_util::future::join; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, TestContext, WebSocketTestClient, WebSocketTestError}; use jsonrpsee_test_utils::TimeoutFutureExt; -use jsonrpsee_types::to_json_raw_value; use jsonrpsee_types::error::rpc::invalid_subscription_err; +use jsonrpsee_types::to_json_raw_value; use serde_json::Value as JsonValue; use std::{fmt, net::SocketAddr, time::Duration}; use tracing_subscriber::{EnvFilter, FmtSubscriber}; From 714ce5dd3a728331bea8149f93c681568fe3f3a4 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 9 Dec 2021 12:42:45 +0000 Subject: [PATCH 03/24] Formatting and imports --- types/src/lib.rs | 2 +- utils/src/server/helpers.rs | 12 +++++++----- utils/src/server/rpc_module.rs | 8 +++++--- ws-client/src/helpers.rs | 7 ++++--- 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/types/src/lib.rs b/types/src/lib.rs index 71ef1bed1e..2b9ff4fd3f 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -46,7 +46,7 @@ pub mod traits; /// Middleware trait and implementation. pub mod middleware; -/// JSON_RPC params related types. +/// JSON-RPC params related types. pub mod params; /// JSON-RPC request object related types diff --git a/utils/src/server/helpers.rs b/utils/src/server/helpers.rs index e59940b309..2b02c2db8a 100644 --- a/utils/src/server/helpers.rs +++ b/utils/src/server/helpers.rs @@ -26,11 +26,13 @@ use futures_channel::mpsc; use futures_util::stream::StreamExt; -use jsonrpsee_types::error::rpc::{CALL_EXECUTION_FAILED_CODE, UNKNOWN_ERROR_CODE}; -use jsonrpsee_types::error::rpc::{OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG}; -use jsonrpsee_types::error::{CallError, Error, ErrorCode, ErrorObject, RpcError}; -use jsonrpsee_types::{to_json_raw_value, Id, TwoPointZero}; -use jsonrpsee_types::{InvalidRequest, Response}; +use jsonrpsee_types::{ + error::{ + rpc::{CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, UNKNOWN_ERROR_CODE}, + CallError, Error, ErrorCode, ErrorObject, RpcError, + }, + to_json_raw_value, Id, InvalidRequest, Response, TwoPointZero, +}; use serde::Serialize; use std::io; diff --git a/utils/src/server/rpc_module.rs b/utils/src/server/rpc_module.rs index ce624e4ff0..dfb2761ce4 100644 --- a/utils/src/server/rpc_module.rs +++ b/utils/src/server/rpc_module.rs @@ -29,10 +29,12 @@ use crate::server::resource_limiting::{ResourceGuard, ResourceTable, ResourceVec use beef::Cow; use futures_channel::{mpsc, oneshot}; use futures_util::{future::BoxFuture, FutureExt, StreamExt}; -use jsonrpsee_types::error::rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}; -use jsonrpsee_types::to_json_raw_value; use jsonrpsee_types::{ - error::{Error, ErrorCode, SubscriptionClosedError}, + error::{ + rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}, + Error, ErrorCode, SubscriptionClosedError, + }, + to_json_raw_value, traits::ToRpcParams, DeserializeOwned, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, SubscriptionResponse, TwoPointZero, diff --git a/ws-client/src/helpers.rs b/ws-client/src/helpers.rs index 57fa05d2ff..3b57eb2637 100644 --- a/ws-client/src/helpers.rs +++ b/ws-client/src/helpers.rs @@ -26,9 +26,10 @@ use crate::manager::{RequestManager, RequestStatus}; use crate::transport::Sender as WsSender; -use crate::types::{Error, RequestMessage, RpcError}; -use crate::types::{Id, ParamsSer, SubscriptionId}; -use crate::types::{Notification, RequestSer, Response, SubscriptionResponse}; +use crate::types::{ + Error, Id, Notification, ParamsSer, RequestMessage, RequestSer, Response, RpcError, SubscriptionId, + SubscriptionResponse, +}; use futures::channel::{mpsc, oneshot}; use serde_json::Value as JsonValue; use std::time::Duration; From 22dd3a7b6556c4059415c0f8fa1db2055ab760b2 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 9 Dec 2021 12:55:36 +0000 Subject: [PATCH 04/24] Updated benches --- benches/bench.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/benches/bench.rs b/benches/bench.rs index a24c40823f..8bdf31eef4 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -3,10 +3,9 @@ use futures_util::future::join_all; use helpers::{SUB_METHOD_NAME, UNSUB_METHOD_NAME}; use jsonrpsee::{ http_client::HttpClientBuilder, - types::traits::SubscriptionClient, types::{ - traits::Client, - v2::{Id, ParamsSer, RequestSer}, + traits::{Client, SubscriptionClient}, + Id, ParamsSer, RequestSer, }, ws_client::WsClientBuilder, }; From 6bb022412414777deed32a28f1a1144f7bf997c9 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 9 Dec 2021 12:58:46 +0000 Subject: [PATCH 05/24] Fix doc comment link --- utils/src/client.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/src/client.rs b/utils/src/client.rs index bcd8bf1a45..671cfae334 100644 --- a/utils/src/client.rs +++ b/utils/src/client.rs @@ -32,7 +32,7 @@ pub mod __reexports { } #[macro_export] -/// Convert the given values to a [`jsonrpsee_types::v2::ParamsSer`] as expected by a jsonrpsee Client (http or websocket). +/// Convert the given values to a [`jsonrpsee_types::ParamsSer`] as expected by a jsonrpsee Client (http or websocket). macro_rules! rpc_params { ($($param:expr),*) => { { From bc22ac222a0d83a59e71866e9719ad0be0c2abdb Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 9 Dec 2021 13:03:43 +0000 Subject: [PATCH 06/24] Brace imports in ws-server --- ws-server/src/server.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index ab2da7bfd1..57b7412dcb 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -30,13 +30,17 @@ use std::pin::Pin; use std::task::{Context, Poll}; use crate::future::{FutureDriver, ServerHandle, StopMonitor}; -use crate::types::error::{Error, ErrorCode}; -use crate::types::{middleware::Middleware, Id, Request, TEN_MB_SIZE_BYTES}; +use crate::types::{ + error::{Error, ErrorCode}, + middleware::Middleware, + Id, Request, TEN_MB_SIZE_BYTES, +}; use futures_channel::mpsc; -use futures_util::future::join_all; -use futures_util::future::FutureExt; -use futures_util::io::{BufReader, BufWriter}; -use futures_util::stream::StreamExt; +use futures_util::{ + future::{join_all, FutureExt}, + io::{BufReader, BufWriter}, + stream::StreamExt, +}; use soketto::connection::Error as SokettoError; use soketto::handshake::{server::Response, Server as SokettoServer}; use soketto::Sender; From 392daa78c58641ac27146e396d8344fb26deb369 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Fri, 10 Dec 2021 12:21:09 +0000 Subject: [PATCH 07/24] Reworking imports --- proc-macros/src/rpc_macro.rs | 8 +++----- proc-macros/src/visitor.rs | 6 ++---- proc-macros/tests/ui/correct/only_server.rs | 8 +++----- proc-macros/tests/ui/correct/param_kind.rs | 10 ++++------ .../tests/ui/incorrect/rpc/rpc_deprecated_method.rs | 10 ++++------ 5 files changed, 16 insertions(+), 26 deletions(-) diff --git a/proc-macros/src/rpc_macro.rs b/proc-macros/src/rpc_macro.rs index cd63753a1e..fcb3e7fc2f 100644 --- a/proc-macros/src/rpc_macro.rs +++ b/proc-macros/src/rpc_macro.rs @@ -26,12 +26,10 @@ //! Declaration of the JSON RPC generator procedural macros. -use crate::{ - attributes::{ - optional, parse_param_kind, Aliases, Argument, AttributeMeta, MissingArgument, NameMapping, ParamKind, Resource, - }, - helpers::extract_doc_comments, +use crate::attributes::{ + optional, parse_param_kind, Aliases, Argument, AttributeMeta, MissingArgument, NameMapping, ParamKind, Resource, }; +use crate::helpers::extract_doc_comments; use proc_macro2::TokenStream as TokenStream2; use quote::quote; diff --git a/proc-macros/src/visitor.rs b/proc-macros/src/visitor.rs index 4f796a035f..beb5fa01b9 100644 --- a/proc-macros/src/visitor.rs +++ b/proc-macros/src/visitor.rs @@ -25,10 +25,8 @@ // DEALINGS IN THE SOFTWARE. use std::collections::HashSet; -use syn::{ - visit::{self, Visit}, - Ident, -}; +use syn::visit::{self, Visit}; +use syn::Ident; /// Visitor that parses generic type parameters from `syn::Type` by traversing the AST. /// A `syn::Type` can any type such as `Vec, T, Foo>>, usize or similar`. diff --git a/proc-macros/tests/ui/correct/only_server.rs b/proc-macros/tests/ui/correct/only_server.rs index 819a326542..c3f487d110 100644 --- a/proc-macros/tests/ui/correct/only_server.rs +++ b/proc-macros/tests/ui/correct/only_server.rs @@ -1,8 +1,6 @@ -use jsonrpsee::{ - proc_macros::rpc, - types::{async_trait, RpcResult}, - ws_server::{SubscriptionSink, WsServerBuilder}, -}; +use jsonrpsee::proc_macros::rpc; +use jsonrpsee::types::{async_trait, RpcResult}; +use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; use std::net::SocketAddr; #[rpc(server)] diff --git a/proc-macros/tests/ui/correct/param_kind.rs b/proc-macros/tests/ui/correct/param_kind.rs index 52c76ea7ac..afba61e8d0 100644 --- a/proc-macros/tests/ui/correct/param_kind.rs +++ b/proc-macros/tests/ui/correct/param_kind.rs @@ -1,9 +1,7 @@ -use jsonrpsee::{ - proc_macros::rpc, - types::{async_trait, RpcResult}, - ws_client::*, - ws_server::WsServerBuilder, -}; +use jsonrpsee::proc_macros::rpc; +use jsonrpsee::types::{async_trait, RpcResult}; +use jsonrpsee::ws_client::*; +use jsonrpsee::ws_server::WsServerBuilder; use std::net::SocketAddr; diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs index 79fdd01972..fe8cfff341 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs @@ -3,12 +3,10 @@ // Treat warnings as errors to fail the build. #![deny(warnings)] -use jsonrpsee::{ - proc_macros::rpc, - types::{async_trait, RpcResult}, - ws_client::*, - ws_server::WsServerBuilder, -}; +use jsonrpsee::proc_macros::rpc; +use jsonrpsee::types::{async_trait, RpcResult}; +use jsonrpsee::ws_client::*; +use jsonrpsee::ws_server::WsServerBuilder; use std::net::SocketAddr; #[rpc(client, server)] From 57bdf5a677f66f6e2789bcbd382908372be16aff Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Fri, 10 Dec 2021 13:21:15 +0000 Subject: [PATCH 08/24] std first --- benches/bench.rs | 15 +++++-------- benches/helpers.rs | 3 ++- examples/http.rs | 11 +++++----- examples/middleware_http.rs | 10 ++++----- examples/middleware_ws.rs | 9 ++++---- examples/multi_middleware.rs | 8 +++---- examples/proc_macro.rs | 4 ++-- examples/ws.rs | 3 ++- examples/ws_sub_with_params.rs | 4 ++-- examples/ws_subscription.rs | 4 ++-- http-client/src/client.rs | 4 +++- http-server/src/access_control/cors.rs | 8 ++++--- http-server/src/access_control/matcher.rs | 3 ++- http-server/src/server.rs | 15 +++++++------ proc-macros/src/attributes.rs | 3 ++- proc-macros/src/helpers.rs | 3 ++- proc-macros/src/render_server.rs | 3 ++- proc-macros/src/rpc_macro.rs | 4 ++-- proc-macros/src/visitor.rs | 1 + proc-macros/tests/ui/correct/basic.rs | 3 ++- proc-macros/tests/ui/correct/only_server.rs | 3 ++- .../ui/incorrect/rpc/rpc_deprecated_method.rs | 3 ++- test-utils/src/helpers.rs | 5 +++-- test-utils/src/lib.rs | 4 +++- test-utils/src/mocks.rs | 17 +++++++------- tests/tests/helpers.rs | 6 ++--- tests/tests/integration_tests.rs | 6 ++--- tests/tests/middleware.rs | 10 ++++----- tests/tests/resource_limiting.rs | 6 ++--- types/src/client.rs | 5 +++-- types/src/error/error.rs | 3 ++- types/src/error/rpc.rs | 3 ++- types/src/params.rs | 4 +++- utils/src/server/helpers.rs | 17 ++++++-------- utils/src/server/rpc_module.rs | 22 +++++++++---------- ws-client/src/client.rs | 5 +++-- ws-client/src/helpers.rs | 6 ++--- ws-client/src/manager.rs | 3 ++- ws-server/src/server.rs | 3 ++- ws-server/src/tests.rs | 4 +++- 40 files changed, 137 insertions(+), 116 deletions(-) diff --git a/benches/bench.rs b/benches/bench.rs index 8bdf31eef4..111a3e2293 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -1,15 +1,12 @@ +use std::sync::Arc; + use criterion::*; use futures_util::future::join_all; use helpers::{SUB_METHOD_NAME, UNSUB_METHOD_NAME}; -use jsonrpsee::{ - http_client::HttpClientBuilder, - types::{ - traits::{Client, SubscriptionClient}, - Id, ParamsSer, RequestSer, - }, - ws_client::WsClientBuilder, -}; -use std::sync::Arc; +use jsonrpsee::http_client::HttpClientBuilder; +use jsonrpsee::types::traits::{Client, SubscriptionClient}; +use jsonrpsee::types::{Id, ParamsSer, RequestSer}; +use jsonrpsee::ws_client::WsClientBuilder; use tokio::runtime::Runtime as TokioRuntime; mod helpers; diff --git a/benches/helpers.rs b/benches/helpers.rs index dcd3de7394..da6b2ac0af 100644 --- a/benches/helpers.rs +++ b/benches/helpers.rs @@ -26,10 +26,11 @@ pub async fn http_server(handle: tokio::runtime::Handle) -> (String, jsonrpc_htt /// Run jsonrpc WebSocket server for benchmarks. #[cfg(feature = "jsonrpc-crate")] pub async fn ws_server(handle: tokio::runtime::Handle) -> (String, jsonrpc_ws_server::Server) { + use std::sync::atomic::{AtomicU64, Ordering}; + use jsonrpc_pubsub::{PubSubHandler, Session, Subscriber, SubscriptionId}; use jsonrpc_ws_server::jsonrpc_core::*; use jsonrpc_ws_server::*; - use std::sync::atomic::{AtomicU64, Ordering}; const ID: AtomicU64 = AtomicU64::new(0); diff --git a/examples/http.rs b/examples/http.rs index 8c4d2b485d..d1cb52c353 100644 --- a/examples/http.rs +++ b/examples/http.rs @@ -24,14 +24,13 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use jsonrpsee::{ - http_client::HttpClientBuilder, - http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}, - rpc_params, - types::traits::Client, -}; use std::net::SocketAddr; +use jsonrpsee::http_client::HttpClientBuilder; +use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; +use jsonrpsee::rpc_params; +use jsonrpsee::types::traits::Client; + #[tokio::main] async fn main() -> anyhow::Result<()> { tracing_subscriber::FmtSubscriber::builder() diff --git a/examples/middleware_http.rs b/examples/middleware_http.rs index c734ca5d47..88308bc311 100644 --- a/examples/middleware_http.rs +++ b/examples/middleware_http.rs @@ -24,14 +24,14 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use jsonrpsee::{ - http_client::HttpClientBuilder, - http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}, - types::{middleware, traits::Client}, -}; use std::net::SocketAddr; use std::time::Instant; +use jsonrpsee::http_client::HttpClientBuilder; +use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; +use jsonrpsee::types::{middleware, traits::Client}; + + #[derive(Clone)] struct Timings; diff --git a/examples/middleware_ws.rs b/examples/middleware_ws.rs index 19d262a2bd..7c54a540cb 100644 --- a/examples/middleware_ws.rs +++ b/examples/middleware_ws.rs @@ -24,14 +24,13 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use jsonrpsee::{ - types::{middleware, traits::Client}, - ws_client::WsClientBuilder, - ws_server::{RpcModule, WsServerBuilder}, -}; use std::net::SocketAddr; use std::time::Instant; +use jsonrpsee::types::{middleware, traits::Client}; +use jsonrpsee::ws_client::WsClientBuilder; +use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; + #[derive(Clone)] struct Timings; diff --git a/examples/multi_middleware.rs b/examples/multi_middleware.rs index f67cc9e666..9cf36e6fb9 100644 --- a/examples/multi_middleware.rs +++ b/examples/multi_middleware.rs @@ -26,15 +26,15 @@ //! Example showing how to add multiple middlewares to the same server. +use std::net::SocketAddr; +use std::process::Command; +use std::time::Instant; + use jsonrpsee::rpc_params; use jsonrpsee::types::{middleware, traits::Client}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; -use std::net::SocketAddr; -use std::process::Command; -use std::time::Instant; - /// Example middleware to measure call execution time. #[derive(Clone)] struct Timings; diff --git a/examples/proc_macro.rs b/examples/proc_macro.rs index 5e8ea6f1ef..0d2ae772a8 100644 --- a/examples/proc_macro.rs +++ b/examples/proc_macro.rs @@ -24,13 +24,13 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::net::SocketAddr; + use jsonrpsee::proc_macros::rpc; use jsonrpsee::types::{async_trait, error::Error, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder, WsServerHandle}; -use std::net::SocketAddr; - type ExampleHash = [u8; 32]; type ExampleStorageKey = Vec; diff --git a/examples/ws.rs b/examples/ws.rs index 8b4ddc2d50..ccd166441a 100644 --- a/examples/ws.rs +++ b/examples/ws.rs @@ -24,10 +24,11 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::net::SocketAddr; + use jsonrpsee::types::traits::Client; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; -use std::net::SocketAddr; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/examples/ws_sub_with_params.rs b/examples/ws_sub_with_params.rs index 8234035c14..509c8dcc10 100644 --- a/examples/ws_sub_with_params.rs +++ b/examples/ws_sub_with_params.rs @@ -24,13 +24,13 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::net::SocketAddr; + use jsonrpsee::rpc_params; use jsonrpsee::types::traits::SubscriptionClient; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; -use std::net::SocketAddr; - #[tokio::main] async fn main() -> anyhow::Result<()> { tracing_subscriber::FmtSubscriber::builder() diff --git a/examples/ws_subscription.rs b/examples/ws_subscription.rs index d20c42ea92..d8fd96e8ce 100644 --- a/examples/ws_subscription.rs +++ b/examples/ws_subscription.rs @@ -24,13 +24,13 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::net::SocketAddr; + use jsonrpsee::rpc_params; use jsonrpsee::types::{traits::SubscriptionClient, Error, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; -use std::net::SocketAddr; - const NUM_SUBSCRIPTION_RESPONSES: usize = 5; #[tokio::main] diff --git a/http-client/src/client.rs b/http-client/src/client.rs index c585022a37..653615701c 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -24,6 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::sync::Arc; +use std::time::Duration; + use crate::transport::HttpTransportClient; use crate::types::traits::{Client, SubscriptionClient}; use crate::types::{ @@ -34,7 +37,6 @@ use async_trait::async_trait; use rustc_hash::FxHashMap; use serde::de::DeserializeOwned; -use std::{sync::Arc, time::Duration}; /// Http Client Builder. #[derive(Debug)] diff --git a/http-server/src/access_control/cors.rs b/http-server/src/access_control/cors.rs index 4340a7016e..3739077d0b 100644 --- a/http-server/src/access_control/cors.rs +++ b/http-server/src/access_control/cors.rs @@ -26,11 +26,12 @@ //! CORS handling utility functions +use std::collections::HashSet; +use std::{fmt, ops}; + use crate::access_control::hosts::{Host, Port}; use crate::access_control::matcher::{Matcher, Pattern}; use lazy_static::lazy_static; -use std::collections::HashSet; -use std::{fmt, ops}; use unicase::Ascii; /// Origin Protocol @@ -322,9 +323,10 @@ lazy_static! { #[cfg(test)] mod tests { + use std::iter; + use super::*; use crate::access_control::hosts::Host; - use std::iter; #[test] fn should_parse_origin() { diff --git a/http-server/src/access_control/matcher.rs b/http-server/src/access_control/matcher.rs index c20ed1d654..9479070ef1 100644 --- a/http-server/src/access_control/matcher.rs +++ b/http-server/src/access_control/matcher.rs @@ -24,8 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use globset::{GlobBuilder, GlobMatcher}; use std::{fmt, hash}; + +use globset::{GlobBuilder, GlobMatcher}; use tracing::warn; /// Pattern that can be matched to string. diff --git a/http-server/src/server.rs b/http-server/src/server.rs index 6eaf6bd36b..5ef180af5c 100644 --- a/http-server/src/server.rs +++ b/http-server/src/server.rs @@ -24,6 +24,12 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::cmp; +use std::future::Future; +use std::net::{SocketAddr, TcpListener, ToSocketAddrs}; +use std::pin::Pin; +use std::task::{Context, Poll}; + use crate::{response, AccessControl}; use futures_channel::mpsc; use futures_util::{future::join_all, stream::StreamExt, FutureExt}; @@ -40,12 +46,6 @@ use jsonrpsee_utils::server::rpc_module::{MethodResult, Methods}; use serde_json::value::RawValue; use socket2::{Domain, Socket, Type}; -use std::cmp; -use std::future::Future; -use std::net::{SocketAddr, TcpListener, ToSocketAddrs}; -use std::pin::Pin; -use std::task::{Context, Poll}; - /// Builder to create JSON-RPC HTTP server. #[derive(Debug)] pub struct Builder { @@ -82,9 +82,10 @@ impl Builder { /// Add a middleware to the builder [`Middleware`](../jsonrpsee_types/middleware/trait.Middleware.html). /// /// ``` + /// use std::time::Instant; + /// /// use jsonrpsee_types::middleware::Middleware; /// use jsonrpsee_http_server::HttpServerBuilder; - /// use std::time::Instant; /// /// #[derive(Clone)] /// struct MyMiddleware; diff --git a/proc-macros/src/attributes.rs b/proc-macros/src/attributes.rs index a143a7a873..7a4b49e4ac 100644 --- a/proc-macros/src/attributes.rs +++ b/proc-macros/src/attributes.rs @@ -24,8 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use proc_macro2::{Span, TokenStream as TokenStream2, TokenTree}; use std::{fmt, iter}; + +use proc_macro2::{Span, TokenStream as TokenStream2, TokenTree}; use syn::parse::{Parse, ParseStream, Parser}; use syn::punctuated::Punctuated; use syn::{spanned::Spanned, Attribute, Error, LitInt, LitStr, Token}; diff --git a/proc-macros/src/helpers.rs b/proc-macros/src/helpers.rs index a1fd1a03eb..471f069f0f 100644 --- a/proc-macros/src/helpers.rs +++ b/proc-macros/src/helpers.rs @@ -24,11 +24,12 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::collections::HashSet; + use crate::visitor::{FindAllParams, FindSubscriptionParams}; use proc_macro2::{Span, TokenStream as TokenStream2}; use proc_macro_crate::{crate_name, FoundCrate}; use quote::quote; -use std::collections::HashSet; use syn::{parse_quote, punctuated::Punctuated, visit::Visit, Token}; /// Search for client-side `jsonrpsee` in `Cargo.toml`. diff --git a/proc-macros/src/render_server.rs b/proc-macros/src/render_server.rs index 68d4b7e816..38850e8add 100644 --- a/proc-macros/src/render_server.rs +++ b/proc-macros/src/render_server.rs @@ -24,12 +24,13 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::collections::HashSet; + use super::RpcDescription; use crate::attributes::Resource; use crate::helpers::{generate_where_clause, is_option}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, quote_spanned}; -use std::collections::HashSet; impl RpcDescription { pub(super) fn render_server(&self) -> Result { diff --git a/proc-macros/src/rpc_macro.rs b/proc-macros/src/rpc_macro.rs index fcb3e7fc2f..5c6c0fa5d1 100644 --- a/proc-macros/src/rpc_macro.rs +++ b/proc-macros/src/rpc_macro.rs @@ -26,14 +26,14 @@ //! Declaration of the JSON RPC generator procedural macros. +use std::borrow::Cow; + use crate::attributes::{ optional, parse_param_kind, Aliases, Argument, AttributeMeta, MissingArgument, NameMapping, ParamKind, Resource, }; use crate::helpers::extract_doc_comments; - use proc_macro2::TokenStream as TokenStream2; use quote::quote; -use std::borrow::Cow; use syn::spanned::Spanned; use syn::{punctuated::Punctuated, Attribute, Token}; diff --git a/proc-macros/src/visitor.rs b/proc-macros/src/visitor.rs index beb5fa01b9..c77ef9f993 100644 --- a/proc-macros/src/visitor.rs +++ b/proc-macros/src/visitor.rs @@ -25,6 +25,7 @@ // DEALINGS IN THE SOFTWARE. use std::collections::HashSet; + use syn::visit::{self, Visit}; use syn::Ident; diff --git a/proc-macros/tests/ui/correct/basic.rs b/proc-macros/tests/ui/correct/basic.rs index 2f64adae36..62a457634d 100644 --- a/proc-macros/tests/ui/correct/basic.rs +++ b/proc-macros/tests/ui/correct/basic.rs @@ -1,11 +1,12 @@ //! Example of using proc macro to generate working client and server. +use std::net::SocketAddr; + use jsonrpsee::proc_macros::rpc; use jsonrpsee::rpc_params; use jsonrpsee::types::{async_trait, traits::Client, RpcResult}; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; -use std::net::SocketAddr; #[rpc(client, server, namespace = "foo")] pub trait Rpc { diff --git a/proc-macros/tests/ui/correct/only_server.rs b/proc-macros/tests/ui/correct/only_server.rs index c3f487d110..1a025bfd9f 100644 --- a/proc-macros/tests/ui/correct/only_server.rs +++ b/proc-macros/tests/ui/correct/only_server.rs @@ -1,7 +1,8 @@ +use std::net::SocketAddr; + use jsonrpsee::proc_macros::rpc; use jsonrpsee::types::{async_trait, RpcResult}; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; -use std::net::SocketAddr; #[rpc(server)] pub trait Rpc { diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs index fe8cfff341..13998b08b1 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs @@ -3,11 +3,12 @@ // Treat warnings as errors to fail the build. #![deny(warnings)] +use std::net::SocketAddr; + use jsonrpsee::proc_macros::rpc; use jsonrpsee::types::{async_trait, RpcResult}; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::WsServerBuilder; -use std::net::SocketAddr; #[rpc(client, server)] pub trait Deprecated { diff --git a/test-utils/src/helpers.rs b/test-utils/src/helpers.rs index 3db1050a07..3a7e58fae2 100644 --- a/test-utils/src/helpers.rs +++ b/test-utils/src/helpers.rs @@ -24,13 +24,14 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::convert::Infallible; +use std::net::SocketAddr; + use crate::mocks::{Body, HttpResponse, Id, Uri}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Request, Response, Server}; use serde::Serialize; use serde_json::Value; -use std::convert::Infallible; -use std::net::SocketAddr; pub const PARSE_ERROR: &str = "Parse error"; pub const INTERNAL_ERROR: &str = "Internal error"; diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs index c47211bc62..9158317b82 100644 --- a/test-utils/src/lib.rs +++ b/test-utils/src/lib.rs @@ -28,7 +28,9 @@ #![recursion_limit = "256"] -use std::{future::Future, time::Duration}; +use std::future::Future; +use std::time::Duration; + use tokio::time::{timeout, Timeout}; pub mod helpers; diff --git a/test-utils/src/mocks.rs b/test-utils/src/mocks.rs index faa89f0ffe..974395b90b 100644 --- a/test-utils/src/mocks.rs +++ b/test-utils/src/mocks.rs @@ -24,18 +24,19 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::io; +use std::net::SocketAddr; +use std::time::Duration; + use futures_channel::mpsc::{self, Receiver, Sender}; use futures_channel::oneshot; -use futures_util::{ - future::FutureExt, - io::{BufReader, BufWriter}, - pin_mut, select, - sink::SinkExt, - stream::{self, StreamExt}, -}; +use futures_util::future::FutureExt; +use futures_util::io::{BufReader, BufWriter}; +use futures_util::{pin_mut, select}; +use futures_util::sink::SinkExt; +use futures_util::stream::{self, StreamExt}; use serde::{Deserialize, Serialize}; use soketto::handshake::{self, http::is_upgrade_request, server::Response, Error as SokettoError, Server}; -use std::{io, net::SocketAddr, time::Duration}; use tokio::net::TcpStream; use tokio_util::compat::{Compat, TokioAsyncReadCompatExt}; diff --git a/tests/tests/helpers.rs b/tests/tests/helpers.rs index 24237a7f8c..04f0c019ea 100644 --- a/tests/tests/helpers.rs +++ b/tests/tests/helpers.rs @@ -24,14 +24,14 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::net::SocketAddr; +use std::time::Duration; + use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::types::Error; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; -use std::net::SocketAddr; -use std::time::Duration; - pub async fn websocket_server_with_subscription() -> (SocketAddr, WsServerHandle) { let server = WsServerBuilder::default().build("127.0.0.1:0").await.unwrap(); diff --git a/tests/tests/integration_tests.rs b/tests/tests/integration_tests.rs index 2ec3068553..17b37b08f8 100644 --- a/tests/tests/integration_tests.rs +++ b/tests/tests/integration_tests.rs @@ -27,7 +27,8 @@ #![cfg(test)] #![allow(clippy::blacklisted_name)] -mod helpers; +use std::sync::Arc; +use std::time::Duration; use helpers::{http_server, websocket_server, websocket_server_with_subscription}; use jsonrpsee::http_client::HttpClientBuilder; @@ -37,8 +38,7 @@ use jsonrpsee::types::traits::{Client, SubscriptionClient}; use jsonrpsee::types::{Error, JsonValue, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; -use std::sync::Arc; -use std::time::Duration; +mod helpers; #[tokio::test] async fn ws_subscription_works() { diff --git a/tests/tests/middleware.rs b/tests/tests/middleware.rs index 4c4bb36eb8..ac88fd73ce 100644 --- a/tests/tests/middleware.rs +++ b/tests/tests/middleware.rs @@ -24,6 +24,11 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; @@ -33,11 +38,6 @@ use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; use tokio::time::sleep; -use std::collections::HashMap; -use std::net::SocketAddr; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - #[derive(Clone, Default)] struct Counter { inner: Arc>, diff --git a/tests/tests/resource_limiting.rs b/tests/tests/resource_limiting.rs index 26f743dbb4..0db264c8a2 100644 --- a/tests/tests/resource_limiting.rs +++ b/tests/tests/resource_limiting.rs @@ -24,6 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::net::SocketAddr; +use std::time::Duration; + use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; @@ -33,9 +36,6 @@ use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; use tokio::time::sleep; -use std::net::SocketAddr; -use std::time::Duration; - fn module_manual() -> Result, Error> { let mut module = RpcModule::new(()); diff --git a/types/src/client.rs b/types/src/client.rs index 76a3db756a..78a45db3f3 100644 --- a/types/src/client.rs +++ b/types/src/client.rs @@ -24,14 +24,15 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + use crate::{error::SubscriptionClosedError, Error, SubscriptionId}; use core::marker::PhantomData; use futures_channel::{mpsc, oneshot}; use futures_util::{future::FutureExt, sink::SinkExt, stream::StreamExt}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value as JsonValue; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; /// Subscription kind #[derive(Debug)] diff --git a/types/src/error/error.rs b/types/src/error/error.rs index 16ea73b452..04264824db 100644 --- a/types/src/error/error.rs +++ b/types/src/error/error.rs @@ -24,9 +24,10 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::fmt; + use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; -use std::fmt; /// Convenience type for displaying errors. #[derive(Clone, Debug, PartialEq)] diff --git a/types/src/error/rpc.rs b/types/src/error/rpc.rs index dc702d12ed..8b1c1a190e 100644 --- a/types/src/error/rpc.rs +++ b/types/src/error/rpc.rs @@ -24,13 +24,14 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::fmt; + use crate::params::{Id, TwoPointZero}; use beef::Cow; use serde::de::Deserializer; use serde::ser::Serializer; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; -use std::fmt; use thiserror::Error; /// [Failed JSON-RPC response object](https://www.jsonrpc.org/specification#response_object). diff --git a/types/src/params.rs b/types/src/params.rs index 0f28cd2814..d6705f378f 100644 --- a/types/src/params.rs +++ b/types/src/params.rs @@ -27,6 +27,9 @@ //! Types to handle JSON-RPC request parameters according to the [spec](https://www.jsonrpc.org/specification#parameter_structures). //! Some types come with a "*Ser" variant that implements [`serde::Serialize`]; these are used in the client. +use std::convert::TryFrom; +use std::fmt; + use crate::error::CallError; use alloc::collections::BTreeMap; use anyhow::anyhow; @@ -35,7 +38,6 @@ use serde::de::{self, Deserializer, Unexpected, Visitor}; use serde::ser::Serializer; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; -use std::{convert::TryFrom, fmt}; /// JSON-RPC v2 marker type. #[derive(Clone, Copy, Debug, Default, PartialEq)] diff --git a/utils/src/server/helpers.rs b/utils/src/server/helpers.rs index ac0f3e6cdf..eb31c558ee 100644 --- a/utils/src/server/helpers.rs +++ b/utils/src/server/helpers.rs @@ -24,25 +24,22 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::io; + use futures_channel::mpsc; use futures_util::stream::StreamExt; -use jsonrpsee_types::{ - error::{ - rpc::{CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, UNKNOWN_ERROR_CODE}, - CallError, Error, ErrorCode, ErrorObject, RpcError, - }, - to_json_raw_value, Id, InvalidRequest, Response, -}; +use jsonrpsee_types::error::rpc::{CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, UNKNOWN_ERROR_CODE}; +use jsonrpsee_types::error::{CallError, Error, ErrorCode, ErrorObject, RpcError}; +use jsonrpsee_types::{to_json_raw_value, Id, InvalidRequest, Response}; use serde::Serialize; -use std::io; - /// Bounded writer that allows writing at most `max_len` bytes. /// /// ``` -/// use jsonrpsee_utils::server::helpers::BoundedWriter; /// use std::io::Write; /// +/// use jsonrpsee_utils::server::helpers::BoundedWriter; +/// /// let mut writer = BoundedWriter::new(10); /// (&mut writer).write("hello".as_bytes()).unwrap(); /// assert_eq!(std::str::from_utf8(&writer.into_bytes()).unwrap(), "hello"); diff --git a/utils/src/server/rpc_module.rs b/utils/src/server/rpc_module.rs index 93a4c3ac75..2235cabe90 100644 --- a/utils/src/server/rpc_module.rs +++ b/utils/src/server/rpc_module.rs @@ -24,31 +24,30 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::collections::hash_map::Entry; +use std::fmt::{self, Debug}; +use std::future::Future; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + use crate::server::helpers::MethodSink; use crate::server::resource_limiting::{ResourceGuard, ResourceTable, ResourceVec, Resources}; use beef::Cow; use futures_channel::{mpsc, oneshot}; use futures_util::{future::BoxFuture, FutureExt, StreamExt}; -use jsonrpsee_types::error::{ - rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}, - Error, ErrorCode, SubscriptionClosedError, -}; +use jsonrpsee_types::error::rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}; +use jsonrpsee_types::error::{Error, ErrorCode, SubscriptionClosedError}; use jsonrpsee_types::to_json_raw_value; use jsonrpsee_types::traits::ToRpcParams; use jsonrpsee_types::{ DeserializeOwned, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, SubscriptionResponse, }; - use parking_lot::Mutex; use rustc_hash::FxHashMap; use serde::Serialize; use serde_json::value::RawValue; -use std::collections::hash_map::Entry; -use std::fmt::{self, Debug}; -use std::future::Future; -use std::ops::{Deref, DerefMut}; -use std::sync::Arc; + /// A `MethodCallback` is an RPC endpoint, callable with a standard JSON-RPC request, /// implemented as a function pointer to a `Fn` function taking four arguments: @@ -839,9 +838,10 @@ impl Drop for TestSubscription { #[cfg(test)] mod tests { + use std::collections::HashMap; + use super::*; use serde::Deserialize; - use std::collections::HashMap; #[test] fn rpc_modules_with_different_contexts_can_be_merged() { diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index a58699c3c5..1e68fd12b0 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -24,6 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::convert::TryInto; +use std::time::Duration; + use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; use crate::types::traits::{Client, SubscriptionClient}; use crate::types::{ @@ -45,8 +48,6 @@ use http::uri::{InvalidUri, Uri}; use tokio::sync::Mutex; use serde::de::DeserializeOwned; -use std::{convert::TryInto, time::Duration}; - pub use soketto::handshake::client::Header; /// Wrapper over a [`oneshot::Receiver`](futures::channel::oneshot::Receiver) that reads diff --git a/ws-client/src/helpers.rs b/ws-client/src/helpers.rs index 09fd3e1ad2..f7a31e0e46 100644 --- a/ws-client/src/helpers.rs +++ b/ws-client/src/helpers.rs @@ -24,6 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use std::convert::TryInto; +use std::time::Duration; + use crate::manager::{RequestManager, RequestStatus}; use crate::transport::Sender as WsSender; use crate::types::{ @@ -33,9 +36,6 @@ use crate::types::{ use futures::channel::{mpsc, oneshot}; use serde_json::Value as JsonValue; -use std::convert::TryInto; -use std::time::Duration; - /// Attempts to process a batch response. /// /// On success the result is sent to the frontend. diff --git a/ws-client/src/manager.rs b/ws-client/src/manager.rs index a8b632b753..48d2b146c0 100644 --- a/ws-client/src/manager.rs +++ b/ws-client/src/manager.rs @@ -32,10 +32,11 @@ //! > **Note**: The spec allow number, string or null but this crate only supports numbers. //! - SubscriptionId: unique ID generated by server +use std::collections::hash_map::{Entry, HashMap}; + use crate::types::{Error, JsonValue, SubscriptionId}; use futures::channel::{mpsc, oneshot}; use rustc_hash::FxHashMap; -use std::collections::hash_map::{Entry, HashMap}; #[derive(Debug)] enum Kind { diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index 863670c799..0582975ec4 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -573,9 +573,10 @@ impl Builder { /// Add a middleware to the builder [`Middleware`](../jsonrpsee_types/middleware/trait.Middleware.html). /// /// ``` + /// use std::time::Instant; + /// /// use jsonrpsee_types::middleware::Middleware; /// use jsonrpsee_ws_server::WsServerBuilder; - /// use std::time::Instant; /// /// #[derive(Clone)] /// struct MyMiddleware; diff --git a/ws-server/src/tests.rs b/ws-server/src/tests.rs index c558e24e46..38dbcec573 100644 --- a/ws-server/src/tests.rs +++ b/ws-server/src/tests.rs @@ -25,6 +25,9 @@ // DEALINGS IN THE SOFTWARE. #![cfg(test)] +use std::fmt; +use std::net::SocketAddr; +use std::time::Duration; use crate::types::error::{CallError, Error}; use crate::types::DeserializeOwned; @@ -38,7 +41,6 @@ use jsonrpsee_test_utils::TimeoutFutureExt; use jsonrpsee_types::error::rpc::invalid_subscription_err; use jsonrpsee_types::to_json_raw_value; use serde_json::Value as JsonValue; -use std::{fmt, net::SocketAddr, time::Duration}; use tracing_subscriber::{EnvFilter, FmtSubscriber}; fn init_logger() { From e24f12d88e0b33dabeb9ca53290b29080ec4d605 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Fri, 10 Dec 2021 13:21:49 +0000 Subject: [PATCH 09/24] fmt --- examples/middleware_http.rs | 1 - http-client/src/client.rs | 1 - test-utils/src/mocks.rs | 2 +- utils/src/server/helpers.rs | 4 +++- utils/src/server/rpc_module.rs | 1 - ws-client/src/client.rs | 12 ++++++------ ws-client/src/transport.rs | 2 +- ws-server/src/server.rs | 6 +++--- 8 files changed, 14 insertions(+), 15 deletions(-) diff --git a/examples/middleware_http.rs b/examples/middleware_http.rs index 88308bc311..b729fb6a47 100644 --- a/examples/middleware_http.rs +++ b/examples/middleware_http.rs @@ -31,7 +31,6 @@ use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; use jsonrpsee::types::{middleware, traits::Client}; - #[derive(Clone)] struct Timings; diff --git a/http-client/src/client.rs b/http-client/src/client.rs index 653615701c..7030715f85 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -37,7 +37,6 @@ use async_trait::async_trait; use rustc_hash::FxHashMap; use serde::de::DeserializeOwned; - /// Http Client Builder. #[derive(Debug)] pub struct HttpClientBuilder { diff --git a/test-utils/src/mocks.rs b/test-utils/src/mocks.rs index 974395b90b..4110ca6a2f 100644 --- a/test-utils/src/mocks.rs +++ b/test-utils/src/mocks.rs @@ -32,9 +32,9 @@ use futures_channel::mpsc::{self, Receiver, Sender}; use futures_channel::oneshot; use futures_util::future::FutureExt; use futures_util::io::{BufReader, BufWriter}; -use futures_util::{pin_mut, select}; use futures_util::sink::SinkExt; use futures_util::stream::{self, StreamExt}; +use futures_util::{pin_mut, select}; use serde::{Deserialize, Serialize}; use soketto::handshake::{self, http::is_upgrade_request, server::Response, Error as SokettoError, Server}; use tokio::net::TcpStream; diff --git a/utils/src/server/helpers.rs b/utils/src/server/helpers.rs index eb31c558ee..903403ed86 100644 --- a/utils/src/server/helpers.rs +++ b/utils/src/server/helpers.rs @@ -28,7 +28,9 @@ use std::io; use futures_channel::mpsc; use futures_util::stream::StreamExt; -use jsonrpsee_types::error::rpc::{CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, UNKNOWN_ERROR_CODE}; +use jsonrpsee_types::error::rpc::{ + CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, UNKNOWN_ERROR_CODE, +}; use jsonrpsee_types::error::{CallError, Error, ErrorCode, ErrorObject, RpcError}; use jsonrpsee_types::{to_json_raw_value, Id, InvalidRequest, Response}; use serde::Serialize; diff --git a/utils/src/server/rpc_module.rs b/utils/src/server/rpc_module.rs index 2235cabe90..5140f83c2a 100644 --- a/utils/src/server/rpc_module.rs +++ b/utils/src/server/rpc_module.rs @@ -48,7 +48,6 @@ use rustc_hash::FxHashMap; use serde::Serialize; use serde_json::value::RawValue; - /// A `MethodCallback` is an RPC endpoint, callable with a standard JSON-RPC request, /// implemented as a function pointer to a `Fn` function taking four arguments: /// the `id`, `params`, a channel the function uses to communicate the result (or error) diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index 1e68fd12b0..8d5b049c61 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -27,6 +27,11 @@ use std::convert::TryInto; use std::time::Duration; +use crate::helpers::{ + build_unsubscribe_message, call_with_timeout, process_batch_response, process_error_response, process_notification, + process_single_response, process_subscription_response, stop_subscription, +}; +use crate::manager::RequestManager; use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; use crate::types::traits::{Client, SubscriptionClient}; use crate::types::{ @@ -34,19 +39,14 @@ use crate::types::{ RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, RpcError, Subscription, SubscriptionKind, SubscriptionMessage, SubscriptionResponse, TEN_MB_SIZE_BYTES, }; -use crate::helpers::{ - build_unsubscribe_message, call_with_timeout, process_batch_response, process_error_response, - process_notification, process_single_response, process_subscription_response, stop_subscription, -}; -use crate::manager::RequestManager; use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; use futures::future::Either; use futures::prelude::*; use futures::sink::SinkExt; use http::uri::{InvalidUri, Uri}; -use tokio::sync::Mutex; use serde::de::DeserializeOwned; +use tokio::sync::Mutex; pub use soketto::handshake::client::Header; diff --git a/ws-client/src/transport.rs b/ws-client/src/transport.rs index 1704222fba..026ec58eb8 100644 --- a/ws-client/src/transport.rs +++ b/ws-client/src/transport.rs @@ -24,7 +24,7 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use std::convert::{TryInto, TryFrom}; +use std::convert::{TryFrom, TryInto}; use std::io; use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index 0582975ec4..2b499caa01 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -37,14 +37,14 @@ use futures_channel::mpsc; use futures_util::future::{join_all, FutureExt}; use futures_util::io::{BufReader, BufWriter}; use futures_util::stream::StreamExt; +use jsonrpsee_utils::server::helpers::{collect_batch_response, prepare_error, MethodSink}; +use jsonrpsee_utils::server::resource_limiting::Resources; +use jsonrpsee_utils::server::rpc_module::{ConnectionId, MethodResult, Methods}; use soketto::connection::Error as SokettoError; use soketto::handshake::{server::Response, Server as SokettoServer}; use soketto::Sender; use tokio::net::{TcpListener, TcpStream, ToSocketAddrs}; use tokio_util::compat::{Compat, TokioAsyncReadCompatExt}; -use jsonrpsee_utils::server::helpers::{collect_batch_response, prepare_error, MethodSink}; -use jsonrpsee_utils::server::resource_limiting::Resources; -use jsonrpsee_utils::server::rpc_module::{ConnectionId, MethodResult, Methods}; /// Default maximum connections allowed. const MAX_CONNECTIONS: u64 = 100; From e59732fbb0cb2f9b96d33090d315575e81f1a6b9 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Fri, 10 Dec 2021 13:38:02 +0000 Subject: [PATCH 10/24] std on top --- proc-macros/tests/ui/correct/param_kind.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/proc-macros/tests/ui/correct/param_kind.rs b/proc-macros/tests/ui/correct/param_kind.rs index afba61e8d0..a1d3734500 100644 --- a/proc-macros/tests/ui/correct/param_kind.rs +++ b/proc-macros/tests/ui/correct/param_kind.rs @@ -1,10 +1,10 @@ +use std::net::SocketAddr; + use jsonrpsee::proc_macros::rpc; use jsonrpsee::types::{async_trait, RpcResult}; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::WsServerBuilder; -use std::net::SocketAddr; - #[rpc(client, server, namespace = "foo")] pub trait Rpc { #[method(name = "method_with_array_param", param_kind = array)] From 4f32c883c6f35cfdebb774aa61131546aeadb4e6 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Fri, 10 Dec 2021 13:45:54 +0000 Subject: [PATCH 11/24] Update to match changed line numbers --- .../tests/ui/incorrect/rpc/rpc_deprecated_method.stderr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr index 0f80a6749a..7a3018a819 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr @@ -1,7 +1,7 @@ error: use of deprecated associated function `DeprecatedClient::async_method`: please use `new_method` instead - --> $DIR/rpc_deprecated_method.rs:64:20 + --> $DIR/rpc_deprecated_method.rs:63:20 | -64 | assert_eq!(client.async_method().await.unwrap(), 16); +63 | assert_eq!(client.async_method().await.unwrap(), 16); | ^^^^^^^^^^^^ | note: the lint level is defined here From f2f53151814062c520580e1926f667f0048c48ad Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Tue, 14 Dec 2021 11:25:14 +0000 Subject: [PATCH 12/24] Rename jsonrpsee_utils -> jsonrpsee_core --- Cargo.toml | 2 +- {utils => core}/Cargo.toml | 2 +- {utils => core}/src/client.rs | 0 {utils => core}/src/http_helpers.rs | 0 {utils => core}/src/lib.rs | 0 {utils => core}/src/server/helpers.rs | 2 +- {utils => core}/src/server/mod.rs | 0 {utils => core}/src/server/resource_limiting.rs | 0 {utils => core}/src/server/rpc_module.rs | 2 +- http-client/Cargo.toml | 2 +- http-client/src/tests.rs | 2 +- http-client/src/transport.rs | 2 +- http-server/Cargo.toml | 2 +- http-server/src/access_control/mod.rs | 2 +- http-server/src/lib.rs | 2 +- http-server/src/server.rs | 8 ++++---- jsonrpsee/Cargo.toml | 10 +++++----- jsonrpsee/src/lib.rs | 6 +++--- ws-client/Cargo.toml | 2 +- ws-client/src/tests.rs | 2 +- ws-server/Cargo.toml | 2 +- ws-server/src/lib.rs | 2 +- ws-server/src/server.rs | 6 +++--- 23 files changed, 29 insertions(+), 29 deletions(-) rename {utils => core}/Cargo.toml (98%) rename {utils => core}/src/client.rs (100%) rename {utils => core}/src/http_helpers.rs (100%) rename {utils => core}/src/lib.rs (100%) rename {utils => core}/src/server/helpers.rs (99%) rename {utils => core}/src/server/mod.rs (100%) rename {utils => core}/src/server/resource_limiting.rs (100%) rename {utils => core}/src/server/rpc_module.rs (99%) diff --git a/Cargo.toml b/Cargo.toml index 371543da63..5c87c28fc8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ members = [ "jsonrpsee", "tests", "types", - "utils", + "core", "ws-client", "ws-server", "proc-macros", diff --git a/utils/Cargo.toml b/core/Cargo.toml similarity index 98% rename from utils/Cargo.toml rename to core/Cargo.toml index bc6d7b2779..de0bf5a75d 100644 --- a/utils/Cargo.toml +++ b/core/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "jsonrpsee-utils" +name = "jsonrpsee-core" version = "0.6.0" authors = ["Parity Technologies "] description = "Utilities for jsonrpsee" diff --git a/utils/src/client.rs b/core/src/client.rs similarity index 100% rename from utils/src/client.rs rename to core/src/client.rs diff --git a/utils/src/http_helpers.rs b/core/src/http_helpers.rs similarity index 100% rename from utils/src/http_helpers.rs rename to core/src/http_helpers.rs diff --git a/utils/src/lib.rs b/core/src/lib.rs similarity index 100% rename from utils/src/lib.rs rename to core/src/lib.rs diff --git a/utils/src/server/helpers.rs b/core/src/server/helpers.rs similarity index 99% rename from utils/src/server/helpers.rs rename to core/src/server/helpers.rs index 903403ed86..ba5f68afad 100644 --- a/utils/src/server/helpers.rs +++ b/core/src/server/helpers.rs @@ -40,7 +40,7 @@ use serde::Serialize; /// ``` /// use std::io::Write; /// -/// use jsonrpsee_utils::server::helpers::BoundedWriter; +/// use jsonrpsee_core::server::helpers::BoundedWriter; /// /// let mut writer = BoundedWriter::new(10); /// (&mut writer).write("hello".as_bytes()).unwrap(); diff --git a/utils/src/server/mod.rs b/core/src/server/mod.rs similarity index 100% rename from utils/src/server/mod.rs rename to core/src/server/mod.rs diff --git a/utils/src/server/resource_limiting.rs b/core/src/server/resource_limiting.rs similarity index 100% rename from utils/src/server/resource_limiting.rs rename to core/src/server/resource_limiting.rs diff --git a/utils/src/server/rpc_module.rs b/core/src/server/rpc_module.rs similarity index 99% rename from utils/src/server/rpc_module.rs rename to core/src/server/rpc_module.rs index 7cbfadf954..51efb7d75c 100644 --- a/utils/src/server/rpc_module.rs +++ b/core/src/server/rpc_module.rs @@ -627,7 +627,7 @@ impl RpcModule { /// /// ```no_run /// - /// use jsonrpsee_utils::server::rpc_module::RpcModule; + /// use jsonrpsee_core::server::rpc_module::RpcModule; /// /// let mut ctx = RpcModule::new(99_usize); /// ctx.register_subscription("sub", "notif_name", "unsub", |params, mut sink, ctx| { diff --git a/http-client/Cargo.toml b/http-client/Cargo.toml index 9526eb17e2..a615b4c5f3 100644 --- a/http-client/Cargo.toml +++ b/http-client/Cargo.toml @@ -15,7 +15,7 @@ rustc-hash = "1" hyper = { version = "0.14.10", features = ["client", "http1", "http2", "tcp"] } hyper-rustls = { version = "0.23", optional = true } jsonrpsee-types = { path = "../types", version = "0.6.0" } -jsonrpsee-utils = { path = "../utils", version = "0.6.0", features = ["client", "http-helpers"] } +jsonrpsee-core = { path = "../core", version = "0.6.0", features = ["client", "http-helpers"] } serde = { version = "1.0", default-features = false, features = ["derive"] } serde_json = "1.0" thiserror = "1.0" diff --git a/http-client/src/tests.rs b/http-client/src/tests.rs index 652125d829..dc187f42a6 100644 --- a/http-client/src/tests.rs +++ b/http-client/src/tests.rs @@ -31,7 +31,7 @@ use crate::HttpClientBuilder; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::Id; use jsonrpsee_test_utils::TimeoutFutureExt; -use jsonrpsee_utils::rpc_params; +use jsonrpsee_core::rpc_params; #[tokio::test] async fn method_call_works() { diff --git a/http-client/src/transport.rs b/http-client/src/transport.rs index 73daa3a703..43127cabb7 100644 --- a/http-client/src/transport.rs +++ b/http-client/src/transport.rs @@ -10,7 +10,7 @@ use crate::types::error::GenericTransportError; use hyper::client::{Client, HttpConnector}; use hyper::Uri; use jsonrpsee_types::CertificateStore; -use jsonrpsee_utils::http_helpers; +use jsonrpsee_core::http_helpers; use thiserror::Error; const CONTENT_TYPE_JSON: &str = "application/json"; diff --git a/http-server/Cargo.toml b/http-server/Cargo.toml index 652ef6d0bc..80d1d51493 100644 --- a/http-server/Cargo.toml +++ b/http-server/Cargo.toml @@ -14,7 +14,7 @@ hyper = { version = "0.14.10", features = ["server", "http1", "http2", "tcp"] } futures-channel = "0.3.14" futures-util = { version = "0.3.14", default-features = false } jsonrpsee-types = { path = "../types", version = "0.6.0" } -jsonrpsee-utils = { path = "../utils", version = "0.6.0", features = ["server", "http-helpers"] } +jsonrpsee-core = { path = "../core", version = "0.6.0", features = ["server", "http-helpers"] } globset = "0.4" lazy_static = "1.4" tracing = "0.1" diff --git a/http-server/src/access_control/mod.rs b/http-server/src/access_control/mod.rs index b749bfff4e..ae1101e90e 100644 --- a/http-server/src/access_control/mod.rs +++ b/http-server/src/access_control/mod.rs @@ -35,7 +35,7 @@ use crate::types::Error; use cors::{AccessControlAllowHeaders, AccessControlAllowOrigin}; use hosts::{AllowHosts, Host}; use hyper::header; -use jsonrpsee_utils::http_helpers; +use jsonrpsee_core::http_helpers; /// Define access on control on HTTP layer. #[derive(Clone, Debug)] diff --git a/http-server/src/lib.rs b/http-server/src/lib.rs index 81530cd814..cf63e178c2 100644 --- a/http-server/src/lib.rs +++ b/http-server/src/lib.rs @@ -42,7 +42,7 @@ pub use access_control::{ AccessControl, AccessControlBuilder, }; pub use jsonrpsee_types as types; -pub use jsonrpsee_utils::server::rpc_module::RpcModule; +pub use jsonrpsee_core::server::rpc_module::RpcModule; pub use server::{Builder as HttpServerBuilder, Server as HttpServer, ServerHandle as HttpServerHandle}; pub use tracing; diff --git a/http-server/src/server.rs b/http-server/src/server.rs index 5ef180af5c..ddf65d3ddd 100644 --- a/http-server/src/server.rs +++ b/http-server/src/server.rs @@ -39,10 +39,10 @@ use hyper::Error as HyperError; use jsonrpsee_types::error::{Error, ErrorCode, GenericTransportError}; use jsonrpsee_types::middleware::Middleware; use jsonrpsee_types::{Id, Notification, Request, TEN_MB_SIZE_BYTES}; -use jsonrpsee_utils::http_helpers::read_body; -use jsonrpsee_utils::server::helpers::{collect_batch_response, prepare_error, MethodSink}; -use jsonrpsee_utils::server::resource_limiting::Resources; -use jsonrpsee_utils::server::rpc_module::{MethodResult, Methods}; +use jsonrpsee_core::http_helpers::read_body; +use jsonrpsee_core::server::helpers::{collect_batch_response, prepare_error, MethodSink}; +use jsonrpsee_core::server::resource_limiting::Resources; +use jsonrpsee_core::server::rpc_module::{MethodResult, Methods}; use serde_json::value::RawValue; use socket2::{Domain, Socket, Type}; diff --git a/jsonrpsee/Cargo.toml b/jsonrpsee/Cargo.toml index 87bc2c0247..ee6d143c02 100644 --- a/jsonrpsee/Cargo.toml +++ b/jsonrpsee/Cargo.toml @@ -17,14 +17,14 @@ jsonrpsee-http-server = { path = "../http-server", version = "0.6.0", package = jsonrpsee-ws-client = { path = "../ws-client", version = "0.6.0", package = "jsonrpsee-ws-client", optional = true } jsonrpsee-ws-server = { path = "../ws-server", version = "0.6.0", package = "jsonrpsee-ws-server", optional = true } jsonrpsee-proc-macros = { path = "../proc-macros", version = "0.6.0", package = "jsonrpsee-proc-macros", optional = true } -jsonrpsee-utils = { path = "../utils", version = "0.6.0", package = "jsonrpsee-utils", optional = true } +jsonrpsee-core = { path = "../core", version = "0.6.0", package = "jsonrpsee-core", optional = true } jsonrpsee-types = { path = "../types", version = "0.6.0", package = "jsonrpsee-types", optional = true } [features] -http-client = ["jsonrpsee-http-client", "jsonrpsee-types", "jsonrpsee-utils/client"] -http-server = ["jsonrpsee-http-server", "jsonrpsee-types", "jsonrpsee-utils"] -ws-client = ["jsonrpsee-ws-client", "jsonrpsee-types", "jsonrpsee-utils/client"] -ws-server = ["jsonrpsee-ws-server", "jsonrpsee-types", "jsonrpsee-utils"] +http-client = ["jsonrpsee-http-client", "jsonrpsee-types", "jsonrpsee-core/client"] +http-server = ["jsonrpsee-http-server", "jsonrpsee-types", "jsonrpsee-core"] +ws-client = ["jsonrpsee-ws-client", "jsonrpsee-types", "jsonrpsee-core/client"] +ws-server = ["jsonrpsee-ws-server", "jsonrpsee-types", "jsonrpsee-core"] macros = ["jsonrpsee-proc-macros", "jsonrpsee-types"] client = ["http-client", "ws-client"] diff --git a/jsonrpsee/src/lib.rs b/jsonrpsee/src/lib.rs index 5d2e97ca5f..098ecff7bd 100644 --- a/jsonrpsee/src/lib.rs +++ b/jsonrpsee/src/lib.rs @@ -54,7 +54,7 @@ pub use jsonrpsee_ws_client as ws_client; /// JSON-RPC client convenience macro to build params. #[cfg(any(feature = "http-client", feature = "ws-client"))] -pub use jsonrpsee_utils::rpc_params; +pub use jsonrpsee_core::rpc_params; /// JSON-RPC HTTP server. #[cfg(feature = "jsonrpsee-http-server")] @@ -74,10 +74,10 @@ pub use jsonrpsee_types as types; /// Set of RPC methods that can be mounted to the server. #[cfg(any(feature = "http-server", feature = "ws-server"))] -pub use jsonrpsee_utils::server::rpc_module::{RpcModule, SubscriptionSink}; +pub use jsonrpsee_core::server::rpc_module::{RpcModule, SubscriptionSink}; #[cfg(any(feature = "http-server", feature = "ws-server"))] -pub use jsonrpsee_utils as utils; +pub use jsonrpsee_core as core; #[cfg(feature = "http-server")] pub use http_server::tracing; diff --git a/ws-client/Cargo.toml b/ws-client/Cargo.toml index e7d94de34d..149b1cea08 100644 --- a/ws-client/Cargo.toml +++ b/ws-client/Cargo.toml @@ -31,7 +31,7 @@ webpki-roots = "0.22.0" [dev-dependencies] env_logger = "0.9.0" jsonrpsee-test-utils = { path = "../test-utils" } -jsonrpsee-utils = { path = "../utils", features = ["client"] } +jsonrpsee-core = { path = "../core", features = ["client"] } tokio = { version = "1.8", features = ["macros"] } [features] diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index c9b3068981..59e4efdc2e 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -32,7 +32,7 @@ use crate::WsClientBuilder; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, WebSocketTestServer}; use jsonrpsee_test_utils::TimeoutFutureExt; -use jsonrpsee_utils::rpc_params; +use jsonrpsee_core::rpc_params; use serde_json::Value as JsonValue; #[tokio::test] diff --git a/ws-server/Cargo.toml b/ws-server/Cargo.toml index f7f327f1a5..d3b4e04e3e 100644 --- a/ws-server/Cargo.toml +++ b/ws-server/Cargo.toml @@ -13,7 +13,7 @@ documentation = "https://docs.rs/jsonrpsee-ws-server" futures-channel = "0.3.14" futures-util = { version = "0.3.14", default-features = false, features = ["io", "async-await-macro"] } jsonrpsee-types = { path = "../types", version = "0.6.0" } -jsonrpsee-utils = { path = "../utils", version = "0.6.0", features = ["server"] } +jsonrpsee-core = { path = "../core", version = "0.6.0", features = ["server"] } tracing = "0.1" serde_json = { version = "1", features = ["raw_value"] } soketto = "0.7.1" diff --git a/ws-server/src/lib.rs b/ws-server/src/lib.rs index d2c02a9870..224bd45bb9 100644 --- a/ws-server/src/lib.rs +++ b/ws-server/src/lib.rs @@ -40,6 +40,6 @@ mod tests; pub use future::{ServerHandle as WsServerHandle, ShutdownWaiter as WsShutdownWaiter}; pub use jsonrpsee_types as types; -pub use jsonrpsee_utils::server::rpc_module::{RpcModule, SubscriptionSink}; +pub use jsonrpsee_core::server::rpc_module::{RpcModule, SubscriptionSink}; pub use server::{Builder as WsServerBuilder, Server as WsServer}; pub use tracing; diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index 2b499caa01..84e484b6a1 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -37,9 +37,9 @@ use futures_channel::mpsc; use futures_util::future::{join_all, FutureExt}; use futures_util::io::{BufReader, BufWriter}; use futures_util::stream::StreamExt; -use jsonrpsee_utils::server::helpers::{collect_batch_response, prepare_error, MethodSink}; -use jsonrpsee_utils::server::resource_limiting::Resources; -use jsonrpsee_utils::server::rpc_module::{ConnectionId, MethodResult, Methods}; +use jsonrpsee_core::server::helpers::{collect_batch_response, prepare_error, MethodSink}; +use jsonrpsee_core::server::resource_limiting::Resources; +use jsonrpsee_core::server::rpc_module::{ConnectionId, MethodResult, Methods}; use soketto::connection::Error as SokettoError; use soketto::handshake::{server::Response, Server as SokettoServer}; use soketto::Sender; From e29bdec7db09d69314041b1d52974c0fedce0b39 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Tue, 14 Dec 2021 12:26:47 +0000 Subject: [PATCH 13/24] Migrating things types -> core --- benches/bench.rs | 2 +- core/Cargo.toml | 1 + core/src/lib.rs | 17 +++++++++++++++++ {types => core}/src/middleware.rs | 0 core/src/server/rpc_module.rs | 4 ++-- {types => core}/src/traits.rs | 4 ++-- examples/http.rs | 2 +- examples/middleware_http.rs | 2 +- examples/middleware_ws.rs | 2 +- examples/multi_middleware.rs | 2 +- examples/proc_macro.rs | 3 ++- examples/ws.rs | 2 +- examples/ws_sub_with_params.rs | 2 +- examples/ws_subscription.rs | 3 ++- http-client/src/client.rs | 2 +- http-client/src/tests.rs | 2 +- http-server/src/server.rs | 4 ++-- proc-macros/src/lib.rs | 2 +- proc-macros/src/render_client.rs | 8 ++++---- proc-macros/src/render_server.rs | 4 ++-- proc-macros/tests/ui/correct/basic.rs | 3 ++- proc-macros/tests/ui/correct/only_server.rs | 3 ++- proc-macros/tests/ui/correct/param_kind.rs | 3 ++- .../ui/incorrect/rpc/rpc_deprecated_method.rs | 3 ++- .../incorrect/rpc/rpc_deprecated_method.stderr | 4 ++-- tests/tests/integration_tests.rs | 2 +- tests/tests/middleware.rs | 3 ++- tests/tests/proc_macros.rs | 3 ++- tests/tests/resource_limiting.rs | 3 ++- types/Cargo.toml | 1 - types/src/lib.rs | 17 +---------------- ws-client/Cargo.toml | 2 +- ws-client/src/client.rs | 2 +- ws-client/src/tests.rs | 2 +- ws-server/src/server.rs | 4 ++-- 35 files changed, 67 insertions(+), 56 deletions(-) rename {types => core}/src/middleware.rs (100%) rename {types => core}/src/traits.rs (98%) diff --git a/benches/bench.rs b/benches/bench.rs index 4daef73b35..b1ef87e507 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -4,7 +4,7 @@ use criterion::*; use futures_util::future::join_all; use helpers::{SUB_METHOD_NAME, UNSUB_METHOD_NAME}; use jsonrpsee::http_client::HttpClientBuilder; -use jsonrpsee::types::traits::{Client, SubscriptionClient}; +use jsonrpsee::core::traits::{Client, SubscriptionClient}; use jsonrpsee::types::{Id, ParamsSer, RequestSer}; use jsonrpsee::ws_client::WsClientBuilder; use tokio::runtime::Runtime as TokioRuntime; diff --git a/core/Cargo.toml b/core/Cargo.toml index de0bf5a75d..5ddf804ef4 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -8,6 +8,7 @@ license = "MIT" [dependencies] arrayvec = "0.7.1" +async-trait = "0.1" beef = { version = "0.5.1", features = ["impl_serde"] } thiserror = { version = "1", optional = true } futures-channel = { version = "0.3.14", default-features = false, optional = true } diff --git a/core/src/lib.rs b/core/src/lib.rs index b6cde330e4..05d10d32ce 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -28,6 +28,12 @@ #![warn(missing_docs, missing_debug_implementations, unreachable_pub)] +/// Middleware trait and implementation. +pub mod middleware; + +/// Traits +pub mod traits; + /// Shared hyper helpers. #[cfg(feature = "http-helpers")] pub mod http_helpers; @@ -39,3 +45,14 @@ pub mod server; /// Shared code for JSON-RPC clients. #[cfg(feature = "client")] pub mod client; + +pub use async_trait::async_trait; + +/// Re-exports for proc-macro library to not require any additional +/// dependencies to be explicitly added on the client side. +#[doc(hidden)] +pub mod __reexports { + pub use async_trait::async_trait; + pub use serde; + pub use serde_json; +} diff --git a/types/src/middleware.rs b/core/src/middleware.rs similarity index 100% rename from types/src/middleware.rs rename to core/src/middleware.rs diff --git a/core/src/server/rpc_module.rs b/core/src/server/rpc_module.rs index 51efb7d75c..c41a8fa37a 100644 --- a/core/src/server/rpc_module.rs +++ b/core/src/server/rpc_module.rs @@ -38,7 +38,7 @@ use futures_util::{future::BoxFuture, FutureExt, StreamExt}; use jsonrpsee_types::error::rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}; use jsonrpsee_types::error::{Error, ErrorCode, SubscriptionClosedError}; use jsonrpsee_types::to_json_raw_value; -use jsonrpsee_types::traits::ToRpcParams; +use crate::traits::ToRpcParams; use jsonrpsee_types::{ DeserializeOwned, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, SubscriptionResponse, @@ -952,7 +952,7 @@ mod tests { #[tokio::test] async fn calling_method_without_server_using_proc_macro() { - use jsonrpsee::{proc_macros::rpc, types::async_trait}; + use jsonrpsee::{proc_macros::rpc, core::async_trait}; // Setup #[derive(Debug, Deserialize, Serialize)] #[allow(unreachable_pub)] diff --git a/types/src/traits.rs b/core/src/traits.rs similarity index 98% rename from types/src/traits.rs rename to core/src/traits.rs index 7392f7b326..f990baccfe 100644 --- a/types/src/traits.rs +++ b/core/src/traits.rs @@ -24,8 +24,8 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::ParamsSer; -use crate::{Error, Subscription}; +use jsonrpsee_types::ParamsSer; +use jsonrpsee_types::{Error, Subscription}; use async_trait::async_trait; use serde::de::DeserializeOwned; use serde::Serialize; diff --git a/examples/http.rs b/examples/http.rs index d1cb52c353..3a5cfecf01 100644 --- a/examples/http.rs +++ b/examples/http.rs @@ -29,7 +29,7 @@ use std::net::SocketAddr; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; use jsonrpsee::rpc_params; -use jsonrpsee::types::traits::Client; +use jsonrpsee::core::traits::Client; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/examples/middleware_http.rs b/examples/middleware_http.rs index b729fb6a47..0bb3f629f7 100644 --- a/examples/middleware_http.rs +++ b/examples/middleware_http.rs @@ -29,7 +29,7 @@ use std::time::Instant; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; -use jsonrpsee::types::{middleware, traits::Client}; +use jsonrpsee::core::{middleware, traits::Client}; #[derive(Clone)] struct Timings; diff --git a/examples/middleware_ws.rs b/examples/middleware_ws.rs index 7c54a540cb..5b12da410d 100644 --- a/examples/middleware_ws.rs +++ b/examples/middleware_ws.rs @@ -27,7 +27,7 @@ use std::net::SocketAddr; use std::time::Instant; -use jsonrpsee::types::{middleware, traits::Client}; +use jsonrpsee::core::{middleware, traits::Client}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/multi_middleware.rs b/examples/multi_middleware.rs index 9cf36e6fb9..9653bd227e 100644 --- a/examples/multi_middleware.rs +++ b/examples/multi_middleware.rs @@ -31,7 +31,7 @@ use std::process::Command; use std::time::Instant; use jsonrpsee::rpc_params; -use jsonrpsee::types::{middleware, traits::Client}; +use jsonrpsee::core::{middleware, traits::Client}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/proc_macro.rs b/examples/proc_macro.rs index 3ed0116805..172d21405d 100644 --- a/examples/proc_macro.rs +++ b/examples/proc_macro.rs @@ -27,7 +27,8 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::{async_trait, error::Error, Subscription}; +use jsonrpsee::core::async_trait; +use jsonrpsee::types::{error::Error, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder, WsServerHandle}; diff --git a/examples/ws.rs b/examples/ws.rs index ccd166441a..2f0ef69859 100644 --- a/examples/ws.rs +++ b/examples/ws.rs @@ -26,7 +26,7 @@ use std::net::SocketAddr; -use jsonrpsee::types::traits::Client; +use jsonrpsee::core::traits::Client; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/ws_sub_with_params.rs b/examples/ws_sub_with_params.rs index 509c8dcc10..694ddb401c 100644 --- a/examples/ws_sub_with_params.rs +++ b/examples/ws_sub_with_params.rs @@ -27,7 +27,7 @@ use std::net::SocketAddr; use jsonrpsee::rpc_params; -use jsonrpsee::types::traits::SubscriptionClient; +use jsonrpsee::core::traits::SubscriptionClient; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/ws_subscription.rs b/examples/ws_subscription.rs index d8fd96e8ce..44c187552a 100644 --- a/examples/ws_subscription.rs +++ b/examples/ws_subscription.rs @@ -27,7 +27,8 @@ use std::net::SocketAddr; use jsonrpsee::rpc_params; -use jsonrpsee::types::{traits::SubscriptionClient, Error, Subscription}; +use jsonrpsee::core::traits::SubscriptionClient; +use jsonrpsee::types::{Error, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/http-client/src/client.rs b/http-client/src/client.rs index 7030715f85..b9d2c0fc59 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -28,7 +28,7 @@ use std::sync::Arc; use std::time::Duration; use crate::transport::HttpTransportClient; -use crate::types::traits::{Client, SubscriptionClient}; +use jsonrpsee_core::traits::{Client, SubscriptionClient}; use crate::types::{ CertificateStore, Error, Id, NotificationSer, ParamsSer, RequestIdManager, RequestSer, Response, RpcError, Subscription, TEN_MB_SIZE_BYTES, diff --git a/http-client/src/tests.rs b/http-client/src/tests.rs index dc187f42a6..3bf4b90157 100644 --- a/http-client/src/tests.rs +++ b/http-client/src/tests.rs @@ -25,7 +25,7 @@ // DEALINGS IN THE SOFTWARE. use crate::types::error::{Error, ErrorCode, ErrorObject, RpcError}; -use crate::types::traits::Client; +use jsonrpsee_core::traits::Client; use crate::types::{JsonValue, ParamsSer}; use crate::HttpClientBuilder; use jsonrpsee_test_utils::helpers::*; diff --git a/http-server/src/server.rs b/http-server/src/server.rs index ddf65d3ddd..8b8f02f155 100644 --- a/http-server/src/server.rs +++ b/http-server/src/server.rs @@ -37,9 +37,9 @@ use hyper::server::{conn::AddrIncoming, Builder as HyperBuilder}; use hyper::service::{make_service_fn, service_fn}; use hyper::Error as HyperError; use jsonrpsee_types::error::{Error, ErrorCode, GenericTransportError}; -use jsonrpsee_types::middleware::Middleware; use jsonrpsee_types::{Id, Notification, Request, TEN_MB_SIZE_BYTES}; use jsonrpsee_core::http_helpers::read_body; +use jsonrpsee_core::middleware::Middleware; use jsonrpsee_core::server::helpers::{collect_batch_response, prepare_error, MethodSink}; use jsonrpsee_core::server::resource_limiting::Resources; use jsonrpsee_core::server::rpc_module::{MethodResult, Methods}; @@ -84,7 +84,7 @@ impl Builder { /// ``` /// use std::time::Instant; /// - /// use jsonrpsee_types::middleware::Middleware; + /// use jsonrpsee_core::middleware::Middleware; /// use jsonrpsee_http_server::HttpServerBuilder; /// /// #[derive(Clone)] diff --git a/proc-macros/src/lib.rs b/proc-macros/src/lib.rs index 62d139353b..842da11429 100644 --- a/proc-macros/src/lib.rs +++ b/proc-macros/src/lib.rs @@ -206,7 +206,7 @@ pub(crate) mod visitor; /// /// // RPC is put into a separate module to clearly show names of generated entities. /// mod rpc_impl { -/// use jsonrpsee::{proc_macros::rpc, types::{async_trait, RpcResult}, ws_server::SubscriptionSink}; +/// use jsonrpsee::{proc_macros::rpc, core::async_trait, types::RpcResult, ws_server::SubscriptionSink}; /// /// // Generate both server and client implementations, prepend all the methods with `foo_` prefix. /// #[rpc(client, server, namespace = "foo")] diff --git a/proc-macros/src/render_client.rs b/proc-macros/src/render_client.rs index fdc6f26e44..591a97ce08 100644 --- a/proc-macros/src/render_client.rs +++ b/proc-macros/src/render_client.rs @@ -41,16 +41,16 @@ impl RpcDescription { let (impl_generics, type_generics, _) = self.trait_def.generics.split_for_impl(); let super_trait = if self.subscriptions.is_empty() { - quote! { #jsonrpsee::types::traits::Client } + quote! { #jsonrpsee::core::traits::Client } } else { - quote! { #jsonrpsee::types::traits::SubscriptionClient } + quote! { #jsonrpsee::core::traits::SubscriptionClient } }; let method_impls = self.methods.iter().map(|method| self.render_method(method)).collect::, _>>()?; let sub_impls = self.subscriptions.iter().map(|sub| self.render_sub(sub)).collect::, _>>()?; - let async_trait = self.jrps_client_item(quote! { types::__reexports::async_trait }); + let async_trait = self.jrps_client_item(quote! { core::__reexports::async_trait }); // Doc-comment to be associated with the client. let doc_comment = format!("Client implementation for the `{}` RPC API.", &self.trait_def.ident); @@ -150,7 +150,7 @@ impl RpcDescription { signature: &syn::TraitItemMethod, ) -> TokenStream2 { if !params.is_empty() { - let serde_json = self.jrps_client_item(quote! { types::__reexports::serde_json }); + let serde_json = self.jrps_client_item(quote! { core::__reexports::serde_json }); let params = params.iter().map(|(param, _param_type)| { quote! { #serde_json::to_value(&#param)? } }); diff --git a/proc-macros/src/render_server.rs b/proc-macros/src/render_server.rs index 38850e8add..866e71210a 100644 --- a/proc-macros/src/render_server.rs +++ b/proc-macros/src/render_server.rs @@ -40,7 +40,7 @@ impl RpcDescription { let method_impls = self.render_methods()?; let into_rpc_impl = self.render_into_rpc()?; - let async_trait = self.jrps_server_item(quote! { types::__reexports::async_trait }); + let async_trait = self.jrps_server_item(quote! { core::__reexports::async_trait }); // Doc-comment to be associated with the server. let doc_comment = format!("Server trait implementation for the `{}` RPC API.", &self.trait_def.ident); @@ -332,7 +332,7 @@ impl RpcDescription { let decode_map = { let generics = (0..params.len()).map(|n| quote::format_ident!("G{}", n)); - let serde = self.jrps_server_item(quote! { types::__reexports::serde }); + let serde = self.jrps_server_item(quote! { core::__reexports::serde }); let serde_crate = serde.to_string(); let fields = params.iter().zip(generics.clone()).map(|((name, _), ty)| { quote! { #name: #ty, } diff --git a/proc-macros/tests/ui/correct/basic.rs b/proc-macros/tests/ui/correct/basic.rs index 7e313c6302..6dbd649fdf 100644 --- a/proc-macros/tests/ui/correct/basic.rs +++ b/proc-macros/tests/ui/correct/basic.rs @@ -4,7 +4,8 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; use jsonrpsee::rpc_params; -use jsonrpsee::types::{async_trait, traits::Client, RpcResult}; +use jsonrpsee::core::{async_trait, traits::Client}; +use jsonrpsee::types::RpcResult; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; diff --git a/proc-macros/tests/ui/correct/only_server.rs b/proc-macros/tests/ui/correct/only_server.rs index 1a025bfd9f..ba3d3c27b7 100644 --- a/proc-macros/tests/ui/correct/only_server.rs +++ b/proc-macros/tests/ui/correct/only_server.rs @@ -1,7 +1,8 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::{async_trait, RpcResult}; +use jsonrpsee::core::async_trait; +use jsonrpsee::types::RpcResult; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; #[rpc(server)] diff --git a/proc-macros/tests/ui/correct/param_kind.rs b/proc-macros/tests/ui/correct/param_kind.rs index a1d3734500..018e45b594 100644 --- a/proc-macros/tests/ui/correct/param_kind.rs +++ b/proc-macros/tests/ui/correct/param_kind.rs @@ -1,7 +1,8 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::{async_trait, RpcResult}; +use jsonrpsee::core::async_trait; +use jsonrpsee::types::RpcResult; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::WsServerBuilder; diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs index 13998b08b1..8f006944b2 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs @@ -6,7 +6,8 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::{async_trait, RpcResult}; +use jsonrpsee::core::async_trait; +use jsonrpsee::types::RpcResult; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::WsServerBuilder; diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr index 7a3018a819..0f80a6749a 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr @@ -1,7 +1,7 @@ error: use of deprecated associated function `DeprecatedClient::async_method`: please use `new_method` instead - --> $DIR/rpc_deprecated_method.rs:63:20 + --> $DIR/rpc_deprecated_method.rs:64:20 | -63 | assert_eq!(client.async_method().await.unwrap(), 16); +64 | assert_eq!(client.async_method().await.unwrap(), 16); | ^^^^^^^^^^^^ | note: the lint level is defined here diff --git a/tests/tests/integration_tests.rs b/tests/tests/integration_tests.rs index 4cc07d3639..56248c62ed 100644 --- a/tests/tests/integration_tests.rs +++ b/tests/tests/integration_tests.rs @@ -34,7 +34,7 @@ use helpers::{http_server, websocket_server, websocket_server_with_subscription} use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::rpc_params; use jsonrpsee::types::error::SubscriptionClosedError; -use jsonrpsee::types::traits::{Client, SubscriptionClient}; +use jsonrpsee::core::traits::{Client, SubscriptionClient}; use jsonrpsee::types::{Error, JsonValue, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; diff --git a/tests/tests/middleware.rs b/tests/tests/middleware.rs index ac88fd73ce..322c5633d6 100644 --- a/tests/tests/middleware.rs +++ b/tests/tests/middleware.rs @@ -32,7 +32,8 @@ use std::time::Duration; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::{middleware::Middleware, traits::Client, Error}; +use jsonrpsee::core::{middleware::Middleware, traits::Client}; +use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; diff --git a/tests/tests/proc_macros.rs b/tests/tests/proc_macros.rs index 2d5535a98a..802cf92c04 100644 --- a/tests/tests/proc_macros.rs +++ b/tests/tests/proc_macros.rs @@ -37,7 +37,8 @@ use serde_json::json; mod rpc_impl { use jsonrpsee::proc_macros::rpc; - use jsonrpsee::types::{async_trait, RpcResult}; + use jsonrpsee::types::RpcResult; + use jsonrpsee::core::async_trait; use jsonrpsee::ws_server::SubscriptionSink; #[rpc(client, server, namespace = "foo")] diff --git a/tests/tests/resource_limiting.rs b/tests/tests/resource_limiting.rs index 0db264c8a2..20091c9925 100644 --- a/tests/tests/resource_limiting.rs +++ b/tests/tests/resource_limiting.rs @@ -30,7 +30,8 @@ use std::time::Duration; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::{traits::Client, Error}; +use jsonrpsee::core::traits::Client; +use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; diff --git a/types/Cargo.toml b/types/Cargo.toml index b4488810ed..423f57d0c3 100644 --- a/types/Cargo.toml +++ b/types/Cargo.toml @@ -10,7 +10,6 @@ homepage = "https://github.com/paritytech/jsonrpsee" documentation = "https://docs.rs/jsonrpsee-types" [dependencies] -async-trait = "0.1" anyhow = "1" beef = { version = "0.5.1", features = ["impl_serde"] } futures-channel = { version = "0.3.14", features = ["sink"] } diff --git a/types/src/lib.rs b/types/src/lib.rs index 841223542b..f31002c8d0 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -40,12 +40,6 @@ pub mod error; /// Client types. mod client; -/// Traits -pub mod traits; - -/// Middleware trait and implementation. -pub mod middleware; - /// JSON-RPC params related types. pub mod params; @@ -55,7 +49,7 @@ pub mod request; /// JSON-RPC response object related types. pub mod response; -pub use async_trait::async_trait; +// pub use async_trait::async_trait; pub use beef::Cow; pub use client::*; pub use error::{CallError, Error, RpcError}; @@ -66,15 +60,6 @@ pub use serde_json::{ Value as JsonValue, }; -/// Re-exports for proc-macro library to not require any additional -/// dependencies to be explicitly added on the client side. -#[doc(hidden)] -pub mod __reexports { - pub use async_trait::async_trait; - pub use serde; - pub use serde_json; -} - /// JSON-RPC result. pub type RpcResult = std::result::Result; diff --git a/ws-client/Cargo.toml b/ws-client/Cargo.toml index 149b1cea08..2282667053 100644 --- a/ws-client/Cargo.toml +++ b/ws-client/Cargo.toml @@ -16,6 +16,7 @@ rustc-hash = "1" futures = { version = "0.3.14", default-features = false, features = ["std"] } http = "0.2" jsonrpsee-types = { path = "../types", version = "0.6.0" } +jsonrpsee-core = { path = "../core", features = ["client"] } pin-project = "1" rustls-native-certs = "0.6.0" serde = "1" @@ -31,7 +32,6 @@ webpki-roots = "0.22.0" [dev-dependencies] env_logger = "0.9.0" jsonrpsee-test-utils = { path = "../test-utils" } -jsonrpsee-core = { path = "../core", features = ["client"] } tokio = { version = "1.8", features = ["macros"] } [features] diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index 8d5b049c61..8cd0942cbd 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -33,7 +33,7 @@ use crate::helpers::{ }; use crate::manager::RequestManager; use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; -use crate::types::traits::{Client, SubscriptionClient}; +use jsonrpsee_core::traits::{Client, SubscriptionClient}; use crate::types::{ BatchMessage, CertificateStore, Error, FrontToBack, Id, Notification, NotificationSer, ParamsSer, RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, RpcError, Subscription, diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index 59e4efdc2e..43acc9d4ad 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -26,7 +26,7 @@ #![cfg(test)] use crate::types::error::{Error, ErrorCode, ErrorObject, RpcError}; -use crate::types::traits::{Client, SubscriptionClient}; +use jsonrpsee_core::traits::{Client, SubscriptionClient}; use crate::types::{ParamsSer, Subscription}; use crate::WsClientBuilder; use jsonrpsee_test_utils::helpers::*; diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index 84e484b6a1..6280a38822 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -31,12 +31,12 @@ use std::task::{Context, Poll}; use crate::future::{FutureDriver, ServerHandle, StopMonitor}; use crate::types::error::{Error, ErrorCode}; -use crate::types::middleware::Middleware; use crate::types::{Id, Request, TEN_MB_SIZE_BYTES}; use futures_channel::mpsc; use futures_util::future::{join_all, FutureExt}; use futures_util::io::{BufReader, BufWriter}; use futures_util::stream::StreamExt; +use jsonrpsee_core::middleware::Middleware; use jsonrpsee_core::server::helpers::{collect_batch_response, prepare_error, MethodSink}; use jsonrpsee_core::server::resource_limiting::Resources; use jsonrpsee_core::server::rpc_module::{ConnectionId, MethodResult, Methods}; @@ -575,7 +575,7 @@ impl Builder { /// ``` /// use std::time::Instant; /// - /// use jsonrpsee_types::middleware::Middleware; + /// use jsonrpsee_core::middleware::Middleware; /// use jsonrpsee_ws_server::WsServerBuilder; /// /// #[derive(Clone)] From faa0da15f8f33c7c71021659b2fbec400c95a248 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Tue, 14 Dec 2021 13:17:05 +0000 Subject: [PATCH 14/24] RpcError -> ErrorResponse --- benches/bench.rs | 2 +- core/src/server/helpers.rs | 9 +++-- core/src/server/rpc_module.rs | 8 ++-- core/src/traits.rs | 2 +- examples/http.rs | 2 +- examples/middleware_http.rs | 2 +- examples/multi_middleware.rs | 2 +- examples/proc_macro.rs | 2 +- examples/ws_sub_with_params.rs | 2 +- examples/ws_subscription.rs | 2 +- http-client/src/client.rs | 8 ++-- http-client/src/tests.rs | 9 +++-- http-client/src/transport.rs | 2 +- http-server/src/lib.rs | 2 +- http-server/src/response.rs | 8 ++-- http-server/src/server.rs | 5 ++- tests/tests/integration_tests.rs | 2 +- tests/tests/middleware.rs | 2 +- tests/tests/proc_macros.rs | 2 +- tests/tests/resource_limiting.rs | 2 +- types/src/{error => }/error.rs | 0 types/src/error/mod.rs | 37 ------------------- types/src/{error/rpc.rs => error_response.rs} | 24 ++++++------ types/src/lib.rs | 6 ++- ws-client/src/client.rs | 8 ++-- ws-client/src/helpers.rs | 4 +- ws-client/src/tests.rs | 9 +++-- ws-server/src/lib.rs | 2 +- ws-server/src/server.rs | 3 +- ws-server/src/tests.rs | 12 +++--- 30 files changed, 76 insertions(+), 104 deletions(-) rename types/src/{error => }/error.rs (100%) delete mode 100644 types/src/error/mod.rs rename types/src/{error/rpc.rs => error_response.rs} (94%) diff --git a/benches/bench.rs b/benches/bench.rs index b1ef87e507..2588a682ff 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use criterion::*; use futures_util::future::join_all; use helpers::{SUB_METHOD_NAME, UNSUB_METHOD_NAME}; -use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::core::traits::{Client, SubscriptionClient}; +use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::types::{Id, ParamsSer, RequestSer}; use jsonrpsee::ws_client::WsClientBuilder; use tokio::runtime::Runtime as TokioRuntime; diff --git a/core/src/server/helpers.rs b/core/src/server/helpers.rs index ba5f68afad..49769a7b8f 100644 --- a/core/src/server/helpers.rs +++ b/core/src/server/helpers.rs @@ -28,10 +28,11 @@ use std::io; use futures_channel::mpsc; use futures_util::stream::StreamExt; -use jsonrpsee_types::error::rpc::{ - CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, UNKNOWN_ERROR_CODE, +use jsonrpsee_types::error::{CallError, Error}; +use jsonrpsee_types::error_response::{ + ErrorCode, ErrorObject, ErrorResponse, CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, + UNKNOWN_ERROR_CODE, }; -use jsonrpsee_types::error::{CallError, Error, ErrorCode, ErrorObject, RpcError}; use jsonrpsee_types::{to_json_raw_value, Id, InvalidRequest, Response}; use serde::Serialize; @@ -137,7 +138,7 @@ impl MethodSink { /// Send a JSON-RPC error to the client pub fn send_error(&self, id: Id, error: ErrorObject) -> bool { - let json = match serde_json::to_string(&RpcError::new(error, id)) { + let json = match serde_json::to_string(&ErrorResponse::new(error, id)) { Ok(json) => json, Err(err) => { tracing::error!("Error serializing error message: {:?}", err); diff --git a/core/src/server/rpc_module.rs b/core/src/server/rpc_module.rs index c41a8fa37a..978fc53c61 100644 --- a/core/src/server/rpc_module.rs +++ b/core/src/server/rpc_module.rs @@ -32,13 +32,13 @@ use std::sync::Arc; use crate::server::helpers::MethodSink; use crate::server::resource_limiting::{ResourceGuard, ResourceTable, ResourceVec, Resources}; +use crate::traits::ToRpcParams; use beef::Cow; use futures_channel::{mpsc, oneshot}; use futures_util::{future::BoxFuture, FutureExt, StreamExt}; -use jsonrpsee_types::error::rpc::{invalid_subscription_err, CALL_EXECUTION_FAILED_CODE}; -use jsonrpsee_types::error::{Error, ErrorCode, SubscriptionClosedError}; +use jsonrpsee_types::error::{Error, SubscriptionClosedError}; +use jsonrpsee_types::error_response::{invalid_subscription_err, ErrorCode, CALL_EXECUTION_FAILED_CODE}; use jsonrpsee_types::to_json_raw_value; -use crate::traits::ToRpcParams; use jsonrpsee_types::{ DeserializeOwned, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, SubscriptionResponse, @@ -952,7 +952,7 @@ mod tests { #[tokio::test] async fn calling_method_without_server_using_proc_macro() { - use jsonrpsee::{proc_macros::rpc, core::async_trait}; + use jsonrpsee::{core::async_trait, proc_macros::rpc}; // Setup #[derive(Debug, Deserialize, Serialize)] #[allow(unreachable_pub)] diff --git a/core/src/traits.rs b/core/src/traits.rs index f990baccfe..4280bd3b44 100644 --- a/core/src/traits.rs +++ b/core/src/traits.rs @@ -24,9 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use async_trait::async_trait; use jsonrpsee_types::ParamsSer; use jsonrpsee_types::{Error, Subscription}; -use async_trait::async_trait; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::value::RawValue; diff --git a/examples/http.rs b/examples/http.rs index 3a5cfecf01..5d3e9eb17f 100644 --- a/examples/http.rs +++ b/examples/http.rs @@ -26,10 +26,10 @@ use std::net::SocketAddr; +use jsonrpsee::core::traits::Client; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; use jsonrpsee::rpc_params; -use jsonrpsee::core::traits::Client; #[tokio::main] async fn main() -> anyhow::Result<()> { diff --git a/examples/middleware_http.rs b/examples/middleware_http.rs index 0bb3f629f7..5c90fcd4c4 100644 --- a/examples/middleware_http.rs +++ b/examples/middleware_http.rs @@ -27,9 +27,9 @@ use std::net::SocketAddr; use std::time::Instant; +use jsonrpsee::core::{middleware, traits::Client}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; -use jsonrpsee::core::{middleware, traits::Client}; #[derive(Clone)] struct Timings; diff --git a/examples/multi_middleware.rs b/examples/multi_middleware.rs index 9653bd227e..dc894da40b 100644 --- a/examples/multi_middleware.rs +++ b/examples/multi_middleware.rs @@ -30,8 +30,8 @@ use std::net::SocketAddr; use std::process::Command; use std::time::Instant; -use jsonrpsee::rpc_params; use jsonrpsee::core::{middleware, traits::Client}; +use jsonrpsee::rpc_params; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/proc_macro.rs b/examples/proc_macro.rs index 172d21405d..c9461d6b01 100644 --- a/examples/proc_macro.rs +++ b/examples/proc_macro.rs @@ -26,8 +26,8 @@ use std::net::SocketAddr; -use jsonrpsee::proc_macros::rpc; use jsonrpsee::core::async_trait; +use jsonrpsee::proc_macros::rpc; use jsonrpsee::types::{error::Error, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder, WsServerHandle}; diff --git a/examples/ws_sub_with_params.rs b/examples/ws_sub_with_params.rs index 694ddb401c..ebd90e51cc 100644 --- a/examples/ws_sub_with_params.rs +++ b/examples/ws_sub_with_params.rs @@ -26,8 +26,8 @@ use std::net::SocketAddr; -use jsonrpsee::rpc_params; use jsonrpsee::core::traits::SubscriptionClient; +use jsonrpsee::rpc_params; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/ws_subscription.rs b/examples/ws_subscription.rs index 44c187552a..2fcd3fa90f 100644 --- a/examples/ws_subscription.rs +++ b/examples/ws_subscription.rs @@ -26,8 +26,8 @@ use std::net::SocketAddr; -use jsonrpsee::rpc_params; use jsonrpsee::core::traits::SubscriptionClient; +use jsonrpsee::rpc_params; use jsonrpsee::types::{Error, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/http-client/src/client.rs b/http-client/src/client.rs index b9d2c0fc59..7a4ed9d36a 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -28,12 +28,12 @@ use std::sync::Arc; use std::time::Duration; use crate::transport::HttpTransportClient; -use jsonrpsee_core::traits::{Client, SubscriptionClient}; use crate::types::{ - CertificateStore, Error, Id, NotificationSer, ParamsSer, RequestIdManager, RequestSer, Response, RpcError, + CertificateStore, Error, ErrorResponse, Id, NotificationSer, ParamsSer, RequestIdManager, RequestSer, Response, Subscription, TEN_MB_SIZE_BYTES, }; use async_trait::async_trait; +use jsonrpsee_core::traits::{Client, SubscriptionClient}; use rustc_hash::FxHashMap; use serde::de::DeserializeOwned; @@ -139,7 +139,7 @@ impl Client for HttpClient { let response: Response<_> = match serde_json::from_slice(&body) { Ok(response) => response, Err(_) => { - let err: RpcError = serde_json::from_slice(&body).map_err(Error::ParseError)?; + let err: ErrorResponse = serde_json::from_slice(&body).map_err(Error::ParseError)?; return Err(Error::Request(err.to_string())); } }; @@ -178,7 +178,7 @@ impl Client for HttpClient { }; let rps: Vec> = - serde_json::from_slice(&body).map_err(|_| match serde_json::from_slice::(&body) { + serde_json::from_slice(&body).map_err(|_| match serde_json::from_slice::(&body) { Ok(e) => Error::Request(e.to_string()), Err(e) => Error::ParseError(e), })?; diff --git a/http-client/src/tests.rs b/http-client/src/tests.rs index 3bf4b90157..a378045ee0 100644 --- a/http-client/src/tests.rs +++ b/http-client/src/tests.rs @@ -24,14 +24,15 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::types::error::{Error, ErrorCode, ErrorObject, RpcError}; -use jsonrpsee_core::traits::Client; +use crate::types::error::Error; +use crate::types::error_response::{ErrorCode, ErrorObject, ErrorResponse}; use crate::types::{JsonValue, ParamsSer}; use crate::HttpClientBuilder; +use jsonrpsee_core::rpc_params; +use jsonrpsee_core::traits::Client; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::Id; use jsonrpsee_test_utils::TimeoutFutureExt; -use jsonrpsee_core::rpc_params; #[tokio::test] async fn method_call_works() { @@ -147,7 +148,7 @@ async fn run_request_with_response(response: String) -> Result fn assert_jsonrpc_error_response(err: Error, exp: ErrorObject) { match &err { Error::Request(e) => { - let this: RpcError = serde_json::from_str(e).unwrap(); + let this: ErrorResponse = serde_json::from_str(e).unwrap(); assert_eq!(this.error, exp); } e => panic!("Expected error: \"{}\", got: {:?}", err, e), diff --git a/http-client/src/transport.rs b/http-client/src/transport.rs index 43127cabb7..d25ea2e21e 100644 --- a/http-client/src/transport.rs +++ b/http-client/src/transport.rs @@ -9,8 +9,8 @@ use crate::types::error::GenericTransportError; use hyper::client::{Client, HttpConnector}; use hyper::Uri; -use jsonrpsee_types::CertificateStore; use jsonrpsee_core::http_helpers; +use jsonrpsee_types::CertificateStore; use thiserror::Error; const CONTENT_TYPE_JSON: &str = "application/json"; diff --git a/http-server/src/lib.rs b/http-server/src/lib.rs index cf63e178c2..d96c19ed51 100644 --- a/http-server/src/lib.rs +++ b/http-server/src/lib.rs @@ -41,8 +41,8 @@ pub use access_control::{ hosts::{AllowHosts, DomainsValidation, Host}, AccessControl, AccessControlBuilder, }; -pub use jsonrpsee_types as types; pub use jsonrpsee_core::server::rpc_module::RpcModule; +pub use jsonrpsee_types as types; pub use server::{Builder as HttpServerBuilder, Server as HttpServer, ServerHandle as HttpServerHandle}; pub use tracing; diff --git a/http-server/src/response.rs b/http-server/src/response.rs index 62082cb4f1..8e3216dc15 100644 --- a/http-server/src/response.rs +++ b/http-server/src/response.rs @@ -26,7 +26,7 @@ //! Contains common builders for hyper responses. -use crate::types::error::{ErrorCode, RpcError}; +use crate::types::error_response::{ErrorCode, ErrorResponse}; use crate::types::Id; const JSON: &str = "application/json; charset=utf-8"; @@ -34,7 +34,7 @@ const TEXT: &str = "text/plain"; /// Create a response for json internal error. pub fn internal_error() -> hyper::Response { - let error = serde_json::to_string(&RpcError::new(ErrorCode::InternalError.into(), Id::Null)) + let error = serde_json::to_string(&ErrorResponse::new(ErrorCode::InternalError.into(), Id::Null)) .expect("built from known-good data; qed"); from_template(hyper::StatusCode::INTERNAL_SERVER_ERROR, error, JSON) @@ -74,7 +74,7 @@ pub fn invalid_allow_headers() -> hyper::Response { /// Create a json response for oversized requests (413) pub fn too_large() -> hyper::Response { - let error = serde_json::to_string(&RpcError::new(ErrorCode::OversizedRequest.into(), Id::Null)) + let error = serde_json::to_string(&ErrorResponse::new(ErrorCode::OversizedRequest.into(), Id::Null)) .expect("built from known-good data; qed"); from_template(hyper::StatusCode::PAYLOAD_TOO_LARGE, error, JSON) @@ -82,7 +82,7 @@ pub fn too_large() -> hyper::Response { /// Create a json response for empty or malformed requests (400) pub fn malformed() -> hyper::Response { - let error = serde_json::to_string(&RpcError::new(ErrorCode::ParseError.into(), Id::Null)) + let error = serde_json::to_string(&ErrorResponse::new(ErrorCode::ParseError.into(), Id::Null)) .expect("built from known-good data; qed"); from_template(hyper::StatusCode::BAD_REQUEST, error, JSON) diff --git a/http-server/src/server.rs b/http-server/src/server.rs index 8b8f02f155..a12a2990f8 100644 --- a/http-server/src/server.rs +++ b/http-server/src/server.rs @@ -36,13 +36,14 @@ use futures_util::{future::join_all, stream::StreamExt, FutureExt}; use hyper::server::{conn::AddrIncoming, Builder as HyperBuilder}; use hyper::service::{make_service_fn, service_fn}; use hyper::Error as HyperError; -use jsonrpsee_types::error::{Error, ErrorCode, GenericTransportError}; -use jsonrpsee_types::{Id, Notification, Request, TEN_MB_SIZE_BYTES}; use jsonrpsee_core::http_helpers::read_body; use jsonrpsee_core::middleware::Middleware; use jsonrpsee_core::server::helpers::{collect_batch_response, prepare_error, MethodSink}; use jsonrpsee_core::server::resource_limiting::Resources; use jsonrpsee_core::server::rpc_module::{MethodResult, Methods}; +use jsonrpsee_types::error::{Error, GenericTransportError}; +use jsonrpsee_types::error_response::ErrorCode; +use jsonrpsee_types::{Id, Notification, Request, TEN_MB_SIZE_BYTES}; use serde_json::value::RawValue; use socket2::{Domain, Socket, Type}; diff --git a/tests/tests/integration_tests.rs b/tests/tests/integration_tests.rs index 56248c62ed..9185f35c4f 100644 --- a/tests/tests/integration_tests.rs +++ b/tests/tests/integration_tests.rs @@ -31,10 +31,10 @@ use std::sync::Arc; use std::time::Duration; use helpers::{http_server, websocket_server, websocket_server_with_subscription}; +use jsonrpsee::core::traits::{Client, SubscriptionClient}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::rpc_params; use jsonrpsee::types::error::SubscriptionClosedError; -use jsonrpsee::core::traits::{Client, SubscriptionClient}; use jsonrpsee::types::{Error, JsonValue, Subscription}; use jsonrpsee::ws_client::WsClientBuilder; diff --git a/tests/tests/middleware.rs b/tests/tests/middleware.rs index 322c5633d6..c7fa7087d8 100644 --- a/tests/tests/middleware.rs +++ b/tests/tests/middleware.rs @@ -29,10 +29,10 @@ use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use std::time::Duration; +use jsonrpsee::core::{middleware::Middleware, traits::Client}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::core::{middleware::Middleware, traits::Client}; use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; diff --git a/tests/tests/proc_macros.rs b/tests/tests/proc_macros.rs index 802cf92c04..db03bf33a2 100644 --- a/tests/tests/proc_macros.rs +++ b/tests/tests/proc_macros.rs @@ -36,9 +36,9 @@ use jsonrpsee::ws_server::WsServerBuilder; use serde_json::json; mod rpc_impl { + use jsonrpsee::core::async_trait; use jsonrpsee::proc_macros::rpc; use jsonrpsee::types::RpcResult; - use jsonrpsee::core::async_trait; use jsonrpsee::ws_server::SubscriptionSink; #[rpc(client, server, namespace = "foo")] diff --git a/tests/tests/resource_limiting.rs b/tests/tests/resource_limiting.rs index 20091c9925..f53c586105 100644 --- a/tests/tests/resource_limiting.rs +++ b/tests/tests/resource_limiting.rs @@ -27,10 +27,10 @@ use std::net::SocketAddr; use std::time::Duration; +use jsonrpsee::core::traits::Client; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::core::traits::Client; use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; diff --git a/types/src/error/error.rs b/types/src/error.rs similarity index 100% rename from types/src/error/error.rs rename to types/src/error.rs diff --git a/types/src/error/mod.rs b/types/src/error/mod.rs deleted file mode 100644 index 7d357d05e2..0000000000 --- a/types/src/error/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// -// Permission is hereby granted, free of charge, to any -// person obtaining a copy of this software and associated -// documentation files (the "Software"), to deal in the -// Software without restriction, including without -// limitation the rights to use, copy, modify, merge, -// publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software -// is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice -// shall be included in all copies or substantial portions -// of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - -//! Types to handle in- and outgoing JSON-RPC requests and subscriptions according to the [spec](https://www.jsonrpc.org/specification). -/// Error type. - -/// Main `Error` type. -mod error; - -/// JSON-RPC error related types. -pub mod rpc; - -pub use error::{CallError, Error, GenericTransportError, SubscriptionClosedError}; -pub use rpc::{ErrorCode, ErrorObject, RpcError}; diff --git a/types/src/error/rpc.rs b/types/src/error_response.rs similarity index 94% rename from types/src/error/rpc.rs rename to types/src/error_response.rs index 8b1c1a190e..087644d517 100644 --- a/types/src/error/rpc.rs +++ b/types/src/error_response.rs @@ -36,7 +36,7 @@ use thiserror::Error; /// [Failed JSON-RPC response object](https://www.jsonrpc.org/specification#response_object). #[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct RpcError<'a> { +pub struct ErrorResponse<'a> { /// JSON-RPC version. pub jsonrpc: TwoPointZero, /// Error. @@ -46,14 +46,14 @@ pub struct RpcError<'a> { pub id: Id<'a>, } -impl<'a> RpcError<'a> { - /// Create a new `RpcError`. +impl<'a> ErrorResponse<'a> { + /// Create a new `ErrorResponse`. pub fn new(error: ErrorObject<'a>, id: Id<'a>) -> Self { Self { jsonrpc: TwoPointZero, error, id } } } -impl<'a> fmt::Display for RpcError<'a> { +impl<'a> fmt::Display for ErrorResponse<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", serde_json::to_string(&self).expect("infallible; qed")) } @@ -238,17 +238,17 @@ pub fn invalid_subscription_err(data: Option<&RawValue>) -> ErrorObject { #[cfg(test)] mod tests { - use super::{ErrorCode, ErrorObject, Id, RpcError, TwoPointZero}; + use super::{ErrorCode, ErrorObject, ErrorResponse, Id, TwoPointZero}; #[test] fn deserialize_works() { let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}"#; - let exp = RpcError { + let exp = ErrorResponse { jsonrpc: TwoPointZero, error: ErrorObject { code: ErrorCode::ParseError, message: "Parse error".into(), data: None }, id: Id::Null, }; - let err: RpcError = serde_json::from_str(ser).unwrap(); + let err: ErrorResponse = serde_json::from_str(ser).unwrap(); assert_eq!(exp, err); } @@ -256,12 +256,12 @@ mod tests { fn deserialize_with_optional_data() { let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error", "data":"vegan"},"id":null}"#; let data = serde_json::value::to_raw_value(&"vegan").unwrap(); - let exp = RpcError { + let exp = ErrorResponse { jsonrpc: TwoPointZero, error: ErrorObject { code: ErrorCode::ParseError, message: "Parse error".into(), data: Some(&*data) }, id: Id::Null, }; - let err: RpcError = serde_json::from_str(ser).unwrap(); + let err: ErrorResponse = serde_json::from_str(ser).unwrap(); assert_eq!(exp, err); } @@ -276,13 +276,13 @@ mod tests { "id": 7, "jsonrpc": "2.0" }"#; - let err: RpcError = serde_json::from_str(raw).unwrap(); + let err: ErrorResponse = serde_json::from_str(raw).unwrap(); let data = serde_json::value::to_raw_value(&"\\\"validate_transaction\\\"").unwrap(); assert_eq!( err, - RpcError { + ErrorResponse { error: ErrorObject { code: 1002.into(), message: "desc: \"Could not decode `ChargeAssetTxPayment::asset_id`\" } })".into(), @@ -297,7 +297,7 @@ mod tests { #[test] fn serialize_works() { let exp = r#"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":1337}"#; - let err = RpcError { + let err = ErrorResponse { jsonrpc: TwoPointZero, error: ErrorObject { code: ErrorCode::InternalError, message: "Internal error".into(), data: None }, id: Id::Number(1337), diff --git a/types/src/lib.rs b/types/src/lib.rs index f31002c8d0..0a1718705c 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -49,10 +49,13 @@ pub mod request; /// JSON-RPC response object related types. pub mod response; +/// JSON-RPC response error object related types. +pub mod error_response; + // pub use async_trait::async_trait; pub use beef::Cow; pub use client::*; -pub use error::{CallError, Error, RpcError}; +pub use error::{CallError, Error}; pub use params::{Id, Params, ParamsSequence, ParamsSer, SubscriptionId, TwoPointZero}; pub use serde::{de::DeserializeOwned, Serialize}; pub use serde_json::{ @@ -63,6 +66,7 @@ pub use serde_json::{ /// JSON-RPC result. pub type RpcResult = std::result::Result; +pub use error_response::ErrorResponse; pub use request::{InvalidRequest, Notification, NotificationSer, Request, RequestSer}; pub use response::{Response, SubscriptionPayload, SubscriptionResponse}; diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index 8cd0942cbd..59dcc18b31 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -33,10 +33,9 @@ use crate::helpers::{ }; use crate::manager::RequestManager; use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; -use jsonrpsee_core::traits::{Client, SubscriptionClient}; use crate::types::{ - BatchMessage, CertificateStore, Error, FrontToBack, Id, Notification, NotificationSer, ParamsSer, - RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, RpcError, Subscription, + BatchMessage, CertificateStore, Error, ErrorResponse, FrontToBack, Id, Notification, NotificationSer, ParamsSer, + RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, Subscription, SubscriptionKind, SubscriptionMessage, SubscriptionResponse, TEN_MB_SIZE_BYTES, }; use async_trait::async_trait; @@ -45,6 +44,7 @@ use futures::future::Either; use futures::prelude::*; use futures::sink::SinkExt; use http::uri::{InvalidUri, Uri}; +use jsonrpsee_core::traits::{Client, SubscriptionClient}; use serde::de::DeserializeOwned; use tokio::sync::Mutex; @@ -590,7 +590,7 @@ async fn background_task( } } // Error response - else if let Ok(err) = serde_json::from_slice::(&raw) { + else if let Ok(err) = serde_json::from_slice::(&raw) { tracing::debug!("[backend]: recv error response {:?}", err); if let Err(e) = process_error_response(&mut manager, err) { let _ = front_error.send(e); diff --git a/ws-client/src/helpers.rs b/ws-client/src/helpers.rs index f7a31e0e46..cd04ed3564 100644 --- a/ws-client/src/helpers.rs +++ b/ws-client/src/helpers.rs @@ -30,7 +30,7 @@ use std::time::Duration; use crate::manager::{RequestManager, RequestStatus}; use crate::transport::Sender as WsSender; use crate::types::{ - Error, Id, Notification, ParamsSer, RequestMessage, RequestSer, Response, RpcError, SubscriptionId, + Error, ErrorResponse, Id, Notification, ParamsSer, RequestMessage, RequestSer, Response, SubscriptionId, SubscriptionResponse, }; use futures::channel::{mpsc, oneshot}; @@ -202,7 +202,7 @@ pub fn build_unsubscribe_message( /// /// Returns `Ok` if the response was successfully sent. /// Returns `Err(_)` if the response ID was not found. -pub fn process_error_response(manager: &mut RequestManager, err: RpcError) -> Result<(), Error> { +pub fn process_error_response(manager: &mut RequestManager, err: ErrorResponse) -> Result<(), Error> { let id = err.id.as_number().copied().ok_or(Error::InvalidRequestId)?; match manager.request_status(&id) { RequestStatus::PendingMethodCall => { diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index 43acc9d4ad..dc1d40b965 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -25,14 +25,15 @@ // DEALINGS IN THE SOFTWARE. #![cfg(test)] -use crate::types::error::{Error, ErrorCode, ErrorObject, RpcError}; -use jsonrpsee_core::traits::{Client, SubscriptionClient}; +use crate::types::error::Error; +use crate::types::error_response::{ErrorCode, ErrorObject, ErrorResponse}; use crate::types::{ParamsSer, Subscription}; use crate::WsClientBuilder; +use jsonrpsee_core::rpc_params; +use jsonrpsee_core::traits::{Client, SubscriptionClient}; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, WebSocketTestServer}; use jsonrpsee_test_utils::TimeoutFutureExt; -use jsonrpsee_core::rpc_params; use serde_json::Value as JsonValue; #[tokio::test] @@ -248,7 +249,7 @@ async fn run_request_with_response(response: String) -> Result fn assert_error_response(err: Error, exp: ErrorObject) { match &err { Error::Request(e) => { - let this: RpcError = serde_json::from_str(e).unwrap(); + let this: ErrorResponse = serde_json::from_str(e).unwrap(); assert_eq!(this.error, exp); } e => panic!("Expected error: \"{}\", got: {:?}", err, e), diff --git a/ws-server/src/lib.rs b/ws-server/src/lib.rs index 224bd45bb9..514253b670 100644 --- a/ws-server/src/lib.rs +++ b/ws-server/src/lib.rs @@ -39,7 +39,7 @@ mod server; mod tests; pub use future::{ServerHandle as WsServerHandle, ShutdownWaiter as WsShutdownWaiter}; -pub use jsonrpsee_types as types; pub use jsonrpsee_core::server::rpc_module::{RpcModule, SubscriptionSink}; +pub use jsonrpsee_types as types; pub use server::{Builder as WsServerBuilder, Server as WsServer}; pub use tracing; diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index 6280a38822..7f5ecc2063 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -30,7 +30,8 @@ use std::pin::Pin; use std::task::{Context, Poll}; use crate::future::{FutureDriver, ServerHandle, StopMonitor}; -use crate::types::error::{Error, ErrorCode}; +use crate::types::error::Error; +use crate::types::error_response::ErrorCode; use crate::types::{Id, Request, TEN_MB_SIZE_BYTES}; use futures_channel::mpsc; use futures_util::future::{join_all, FutureExt}; diff --git a/ws-server/src/tests.rs b/ws-server/src/tests.rs index 5b6e8f826d..3be9011994 100644 --- a/ws-server/src/tests.rs +++ b/ws-server/src/tests.rs @@ -31,14 +31,14 @@ use std::time::Duration; use crate::types::error::{CallError, Error}; use crate::types::DeserializeOwned; -use crate::types::{self, Response, RpcError}; +use crate::types::{self, ErrorResponse, Response}; use crate::{future::ServerHandle, RpcModule, WsServerBuilder}; use anyhow::anyhow; use futures_util::future::join; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, TestContext, WebSocketTestClient, WebSocketTestError}; use jsonrpsee_test_utils::TimeoutFutureExt; -use jsonrpsee_types::error::rpc::invalid_subscription_err; +use jsonrpsee_types::error_response::invalid_subscription_err; use jsonrpsee_types::to_json_raw_value; use serde_json::Value as JsonValue; use tracing_subscriber::{EnvFilter, FmtSubscriber}; @@ -612,11 +612,11 @@ async fn unsubscribe_twice_should_indicate_error() { let unsub_call = call("unsubscribe_hello", vec![sub_id], Id::Num(2)); let unsub_2 = client.send_request_text(unsub_call).await.unwrap(); - let unsub_2_err: RpcError = serde_json::from_str(&unsub_2).unwrap(); + let unsub_2_err: ErrorResponse = serde_json::from_str(&unsub_2).unwrap(); let sub_id = to_json_raw_value(&sub_id).unwrap(); let err = Some(to_json_raw_value(&format!("Invalid subscription ID={}", sub_id)).unwrap()); - assert_eq!(unsub_2_err, RpcError::new(invalid_subscription_err(err.as_deref()), types::Id::Number(2))); + assert_eq!(unsub_2_err, ErrorResponse::new(invalid_subscription_err(err.as_deref()), types::Id::Number(2))); } #[tokio::test] @@ -627,7 +627,7 @@ async fn unsubscribe_wrong_sub_id_type() { let unsub = client.send_request_text(call("unsubscribe_hello", vec!["string_is_not_supported"], Id::Num(0))).await.unwrap(); - let unsub_2_err: RpcError = serde_json::from_str(&unsub).unwrap(); + let unsub_2_err: ErrorResponse = serde_json::from_str(&unsub).unwrap(); let err = Some(to_json_raw_value(&"Invalid subscription ID type, must be integer").unwrap()); - assert_eq!(unsub_2_err, RpcError::new(invalid_subscription_err(err.as_deref()), types::Id::Number(0))); + assert_eq!(unsub_2_err, ErrorResponse::new(invalid_subscription_err(err.as_deref()), types::Id::Number(0))); } From a9567f0dfffa53233c1399d65598e0256cf90eb1 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Tue, 14 Dec 2021 15:35:07 +0000 Subject: [PATCH 15/24] Merge types::client into core::client --- core/src/client.rs | 279 ++++++++++++++++++++++++++++ core/src/server/mod.rs | 3 + core/src/traits.rs | 3 +- examples/proc_macro.rs | 4 +- examples/ws_subscription.rs | 3 +- http-client/src/client.rs | 6 +- http-client/src/transport.rs | 2 +- proc-macros/src/render_client.rs | 2 +- tests/tests/integration_tests.rs | 3 +- types/src/client.rs | 305 ------------------------------- types/src/lib.rs | 4 - ws-client/src/client.rs | 9 +- ws-client/src/helpers.rs | 4 +- ws-client/src/tests.rs | 3 +- ws-client/src/transport.rs | 3 +- 15 files changed, 306 insertions(+), 327 deletions(-) delete mode 100644 types/src/client.rs diff --git a/core/src/client.rs b/core/src/client.rs index 671cfae334..bd0d542a11 100644 --- a/core/src/client.rs +++ b/core/src/client.rs @@ -25,6 +25,21 @@ // DEALINGS IN THE SOFTWARE. //! Shared utilities for `jsonrpsee` clients. +use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::task; + +use core::marker::PhantomData; +use futures_channel::{mpsc, oneshot}; +use futures_util::{ + future::FutureExt, + sink::SinkExt, + stream::{Stream, StreamExt}, +}; +use jsonrpsee_types::{error::SubscriptionClosedError, Error, SubscriptionId}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use serde_json::Value as JsonValue; #[doc(hidden)] pub mod __reexports { @@ -47,3 +62,267 @@ macro_rules! rpc_params { None } } + +/// Subscription kind +#[derive(Debug)] +#[non_exhaustive] +pub enum SubscriptionKind { + /// Get notifications based on Subscription ID. + Subscription(SubscriptionId<'static>), + /// Get notifications based on method name. + Method(String), +} + +/// Internal type to detect whether a subscription response from +/// the server was a valid notification or should be treated as an error. +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +enum NotifResponse { + Ok(Notif), + Err(SubscriptionClosedError), +} + +/// Active subscription on the client. +/// +/// It will automatically unsubscribe in the [`Subscription::drop`] so no need to explicitly call +/// the `unsubscribe method` if it is an an subscription based on [`SubscriptionId`]. +#[derive(Debug)] +pub struct Subscription { + /// Channel to send requests to the background task. + to_back: mpsc::Sender, + /// Channel from which we receive notifications from the server, as encoded `JsonValue`s. + notifs_rx: mpsc::Receiver, + /// Callback kind. + kind: SubscriptionKind, + /// Marker in order to pin the `Notif` parameter. + marker: PhantomData, +} + +// `Subscription` does not automatically implement this due to `PhantomData`, +// but type type has no need to be pinned. +impl std::marker::Unpin for Subscription {} + +impl Subscription { + /// Create a new subscription. + pub fn new( + to_back: mpsc::Sender, + notifs_rx: mpsc::Receiver, + kind: SubscriptionKind, + ) -> Self { + Self { to_back, notifs_rx, kind, marker: PhantomData } + } +} + +/// Batch request message. +#[derive(Debug)] +pub struct BatchMessage { + /// Serialized batch request. + pub raw: String, + /// Request IDs. + pub ids: Vec, + /// One-shot channel over which we send back the result of this request. + pub send_back: oneshot::Sender, Error>>, +} + +/// Request message. +#[derive(Debug)] +pub struct RequestMessage { + /// Serialized message. + pub raw: String, + /// Request ID. + pub id: u64, + /// One-shot channel over which we send back the result of this request. + pub send_back: Option>>, +} + +/// Subscription message. +#[derive(Debug)] +pub struct SubscriptionMessage { + /// Serialized message. + pub raw: String, + /// Request ID of the subscribe message. + pub subscribe_id: u64, + /// Request ID of the unsubscribe message. + pub unsubscribe_id: u64, + /// Method to use to unsubscribe later. Used if the channel unexpectedly closes. + pub unsubscribe_method: String, + /// If the subscription succeeds, we return a [`mpsc::Receiver`] that will receive notifications. + /// When we get a response from the server about that subscription, we send the result over + /// this channel. + pub send_back: oneshot::Sender, SubscriptionId<'static>), Error>>, +} + +/// RegisterNotification message. +#[derive(Debug)] +pub struct RegisterNotificationMessage { + /// Method name this notification handler is attached to + pub method: String, + /// We return a [`mpsc::Receiver`] that will receive notifications. + /// When we get a response from the server about that subscription, we send the result over + /// this channel. + pub send_back: oneshot::Sender, String), Error>>, +} + +/// Message that the Client can send to the background task. +#[derive(Debug)] +pub enum FrontToBack { + /// Send a batch request to the server. + Batch(BatchMessage), + /// Send a notification to the server. + Notification(String), + /// Send a request to the server. + Request(RequestMessage), + /// Send a subscription request to the server. + Subscribe(SubscriptionMessage), + /// Register a notification handler + RegisterNotification(RegisterNotificationMessage), + /// Unregister a notification handler + UnregisterNotification(String), + /// When a subscription channel is closed, we send this message to the background + /// task to mark it ready for garbage collection. + // NOTE: It is not possible to cancel pending subscriptions or pending requests. + // Such operations will be blocked until a response is received or the background + // thread has been terminated. + SubscriptionClosed(SubscriptionId<'static>), +} + +impl Subscription +where + Notif: DeserializeOwned, +{ + /// Returns the next notification from the stream. + /// This may return `None` if the subscription has been terminated, + /// which may happen if the channel becomes full or is dropped. + /// + /// **Note:** This has an identical signature to the [`StreamExt::next`] + /// method (and delegates to that). Import [`StreamExt`] if you'd like + /// access to other stream combinator methods. + #[allow(clippy::should_implement_trait)] + pub async fn next(&mut self) -> Option> { + StreamExt::next(self).await + } +} + +impl Stream for Subscription +where + Notif: DeserializeOwned, +{ + type Item = Result; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll> { + let n = futures_util::ready!(self.notifs_rx.poll_next_unpin(cx)); + let res = n.map(|n| match serde_json::from_value::>(n) { + Ok(NotifResponse::Ok(parsed)) => Ok(parsed), + Ok(NotifResponse::Err(e)) => Err(Error::SubscriptionClosed(e)), + Err(e) => Err(Error::ParseError(e)), + }); + task::Poll::Ready(res) + } +} + +impl Drop for Subscription { + fn drop(&mut self) { + // We can't actually guarantee that this goes through. If the background task is busy, then + // the channel's buffer will be full. + // However, when a notification arrives, the background task will realize that the channel + // to the `Callback` has been closed. + let kind = std::mem::replace(&mut self.kind, SubscriptionKind::Subscription(SubscriptionId::Num(0))); + + let msg = match kind { + SubscriptionKind::Method(notif) => FrontToBack::UnregisterNotification(notif), + SubscriptionKind::Subscription(sub_id) => FrontToBack::SubscriptionClosed(sub_id), + }; + let _ = self.to_back.send(msg).now_or_never(); + } +} + +#[derive(Debug)] +/// Keep track of request IDs. +pub struct RequestIdManager { + // Current pending requests. + current_pending: Arc<()>, + /// Max concurrent pending requests allowed. + max_concurrent_requests: usize, + /// Get the next request ID. + current_id: AtomicU64, +} + +impl RequestIdManager { + /// Create a new `RequestIdGuard` with the provided concurrency limit. + pub fn new(limit: usize) -> Self { + Self { current_pending: Arc::new(()), max_concurrent_requests: limit, current_id: AtomicU64::new(0) } + } + + fn get_slot(&self) -> Result, Error> { + // Strong count is 1 at start, so that's why we use `>` and not `>=`. + if Arc::strong_count(&self.current_pending) > self.max_concurrent_requests { + Err(Error::MaxSlotsExceeded) + } else { + Ok(self.current_pending.clone()) + } + } + + /// Attempts to get the next request ID. + /// + /// Fails if request limit has been exceeded. + pub fn next_request_id(&self) -> Result, Error> { + let rc = self.get_slot()?; + let id = self.current_id.fetch_add(1, Ordering::SeqCst); + Ok(RequestIdGuard { _rc: rc, id }) + } + + /// Attempts to get the `n` number next IDs that only counts as one request. + /// + /// Fails if request limit has been exceeded. + pub fn next_request_ids(&self, len: usize) -> Result>, Error> { + let rc = self.get_slot()?; + let mut ids = Vec::with_capacity(len); + for _ in 0..len { + ids.push(self.current_id.fetch_add(1, Ordering::SeqCst)); + } + Ok(RequestIdGuard { _rc: rc, id: ids }) + } +} + +/// Reference counted request ID. +#[derive(Debug)] +pub struct RequestIdGuard { + id: T, + /// Reference count decreased when dropped. + _rc: Arc<()>, +} + +impl RequestIdGuard { + /// Get the actual ID. + pub fn inner(&self) -> &T { + &self.id + } +} + +#[cfg(test)] +mod tests { + use super::RequestIdManager; + + #[test] + fn request_id_guard_works() { + let manager = RequestIdManager::new(2); + let _first = manager.next_request_id().unwrap(); + + { + let _second = manager.next_request_ids(13).unwrap(); + assert!(manager.next_request_id().is_err()); + // second dropped here. + } + + assert!(manager.next_request_id().is_ok()); + } +} + +/// What certificate store to use +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub enum CertificateStore { + /// Use the native system certificate store + Native, + /// Use WebPKI's certificate store + WebPki, +} diff --git a/core/src/server/mod.rs b/core/src/server/mod.rs index fe1a99277b..f7493ece6f 100644 --- a/core/src/server/mod.rs +++ b/core/src/server/mod.rs @@ -26,6 +26,9 @@ //! Shared modules for the JSON-RPC servers. +/// Client types. +// mod client; + /// Helpers. pub mod helpers; /// Resource limiting. Create generic "resources" and configure their limits to ensure servers are not overloaded. diff --git a/core/src/traits.rs b/core/src/traits.rs index 4280bd3b44..08b45b2079 100644 --- a/core/src/traits.rs +++ b/core/src/traits.rs @@ -24,9 +24,10 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::client::Subscription; use async_trait::async_trait; +use jsonrpsee_types::Error; use jsonrpsee_types::ParamsSer; -use jsonrpsee_types::{Error, Subscription}; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::value::RawValue; diff --git a/examples/proc_macro.rs b/examples/proc_macro.rs index c9461d6b01..d9ea961415 100644 --- a/examples/proc_macro.rs +++ b/examples/proc_macro.rs @@ -26,9 +26,9 @@ use std::net::SocketAddr; -use jsonrpsee::core::async_trait; +use jsonrpsee::core::{async_trait, client::Subscription}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::{error::Error, Subscription}; +use jsonrpsee::types::error::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder, WsServerHandle}; diff --git a/examples/ws_subscription.rs b/examples/ws_subscription.rs index 2fcd3fa90f..9543099ed1 100644 --- a/examples/ws_subscription.rs +++ b/examples/ws_subscription.rs @@ -26,9 +26,10 @@ use std::net::SocketAddr; +use jsonrpsee::core::client::Subscription; use jsonrpsee::core::traits::SubscriptionClient; use jsonrpsee::rpc_params; -use jsonrpsee::types::{Error, Subscription}; +use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/http-client/src/client.rs b/http-client/src/client.rs index 7a4ed9d36a..2da714dca2 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -28,11 +28,9 @@ use std::sync::Arc; use std::time::Duration; use crate::transport::HttpTransportClient; -use crate::types::{ - CertificateStore, Error, ErrorResponse, Id, NotificationSer, ParamsSer, RequestIdManager, RequestSer, Response, - Subscription, TEN_MB_SIZE_BYTES, -}; +use crate::types::{Error, ErrorResponse, Id, NotificationSer, ParamsSer, RequestSer, Response, TEN_MB_SIZE_BYTES}; use async_trait::async_trait; +use jsonrpsee_core::client::{CertificateStore, RequestIdManager, Subscription}; use jsonrpsee_core::traits::{Client, SubscriptionClient}; use rustc_hash::FxHashMap; use serde::de::DeserializeOwned; diff --git a/http-client/src/transport.rs b/http-client/src/transport.rs index d25ea2e21e..2dcbc0eae6 100644 --- a/http-client/src/transport.rs +++ b/http-client/src/transport.rs @@ -9,8 +9,8 @@ use crate::types::error::GenericTransportError; use hyper::client::{Client, HttpConnector}; use hyper::Uri; +use jsonrpsee_core::client::CertificateStore; use jsonrpsee_core::http_helpers; -use jsonrpsee_types::CertificateStore; use thiserror::Error; const CONTENT_TYPE_JSON: &str = "application/json"; diff --git a/proc-macros/src/render_client.rs b/proc-macros/src/render_client.rs index 591a97ce08..c440a5e4eb 100644 --- a/proc-macros/src/render_client.rs +++ b/proc-macros/src/render_client.rs @@ -125,7 +125,7 @@ impl RpcDescription { // `returns` represent the return type of the *rust method*, which is wrapped // into the `Subscription` object. - let sub_type = self.jrps_client_item(quote! { types::Subscription }); + let sub_type = self.jrps_client_item(quote! { core::client::Subscription }); let item = &sub.item; let returns = quote! { Result<#sub_type<#item>, #jrps_error> }; diff --git a/tests/tests/integration_tests.rs b/tests/tests/integration_tests.rs index 9185f35c4f..f4026958a8 100644 --- a/tests/tests/integration_tests.rs +++ b/tests/tests/integration_tests.rs @@ -31,11 +31,12 @@ use std::sync::Arc; use std::time::Duration; use helpers::{http_server, websocket_server, websocket_server_with_subscription}; +use jsonrpsee::core::client::Subscription; use jsonrpsee::core::traits::{Client, SubscriptionClient}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::rpc_params; use jsonrpsee::types::error::SubscriptionClosedError; -use jsonrpsee::types::{Error, JsonValue, Subscription}; +use jsonrpsee::types::{Error, JsonValue}; use jsonrpsee::ws_client::WsClientBuilder; mod helpers; diff --git a/types/src/client.rs b/types/src/client.rs deleted file mode 100644 index b58cc0be44..0000000000 --- a/types/src/client.rs +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// -// Permission is hereby granted, free of charge, to any -// person obtaining a copy of this software and associated -// documentation files (the "Software"), to deal in the -// Software without restriction, including without -// limitation the rights to use, copy, modify, merge, -// publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software -// is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice -// shall be included in all copies or substantial portions -// of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - -use std::pin::Pin; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; -use std::task; - -use crate::{error::SubscriptionClosedError, Error, SubscriptionId}; -use core::marker::PhantomData; -use futures_channel::{mpsc, oneshot}; -use futures_util::{ - future::FutureExt, - sink::SinkExt, - stream::{Stream, StreamExt}, -}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use serde_json::Value as JsonValue; - -/// Subscription kind -#[derive(Debug)] -#[non_exhaustive] -pub enum SubscriptionKind { - /// Get notifications based on Subscription ID. - Subscription(SubscriptionId<'static>), - /// Get notifications based on method name. - Method(String), -} - -/// Internal type to detect whether a subscription response from -/// the server was a valid notification or should be treated as an error. -#[derive(Debug, Deserialize, Serialize)] -#[serde(untagged)] -enum NotifResponse { - Ok(Notif), - Err(SubscriptionClosedError), -} - -/// Active subscription on the client. -/// -/// It will automatically unsubscribe in the [`Subscription::drop`] so no need to explicitly call -/// the `unsubscribe method` if it is an an subscription based on [`SubscriptionId`]. -#[derive(Debug)] -pub struct Subscription { - /// Channel to send requests to the background task. - to_back: mpsc::Sender, - /// Channel from which we receive notifications from the server, as encoded `JsonValue`s. - notifs_rx: mpsc::Receiver, - /// Callback kind. - kind: SubscriptionKind, - /// Marker in order to pin the `Notif` parameter. - marker: PhantomData, -} - -// `Subscription` does not automatically implement this due to `PhantomData`, -// but type type has no need to be pinned. -impl std::marker::Unpin for Subscription {} - -impl Subscription { - /// Create a new subscription. - pub fn new( - to_back: mpsc::Sender, - notifs_rx: mpsc::Receiver, - kind: SubscriptionKind, - ) -> Self { - Self { to_back, notifs_rx, kind, marker: PhantomData } - } -} - -/// Batch request message. -#[derive(Debug)] -pub struct BatchMessage { - /// Serialized batch request. - pub raw: String, - /// Request IDs. - pub ids: Vec, - /// One-shot channel over which we send back the result of this request. - pub send_back: oneshot::Sender, Error>>, -} - -/// Request message. -#[derive(Debug)] -pub struct RequestMessage { - /// Serialized message. - pub raw: String, - /// Request ID. - pub id: u64, - /// One-shot channel over which we send back the result of this request. - pub send_back: Option>>, -} - -/// Subscription message. -#[derive(Debug)] -pub struct SubscriptionMessage { - /// Serialized message. - pub raw: String, - /// Request ID of the subscribe message. - pub subscribe_id: u64, - /// Request ID of the unsubscribe message. - pub unsubscribe_id: u64, - /// Method to use to unsubscribe later. Used if the channel unexpectedly closes. - pub unsubscribe_method: String, - /// If the subscription succeeds, we return a [`mpsc::Receiver`] that will receive notifications. - /// When we get a response from the server about that subscription, we send the result over - /// this channel. - pub send_back: oneshot::Sender, SubscriptionId<'static>), Error>>, -} - -/// RegisterNotification message. -#[derive(Debug)] -pub struct RegisterNotificationMessage { - /// Method name this notification handler is attached to - pub method: String, - /// We return a [`mpsc::Receiver`] that will receive notifications. - /// When we get a response from the server about that subscription, we send the result over - /// this channel. - pub send_back: oneshot::Sender, String), Error>>, -} - -/// Message that the Client can send to the background task. -#[derive(Debug)] -pub enum FrontToBack { - /// Send a batch request to the server. - Batch(BatchMessage), - /// Send a notification to the server. - Notification(String), - /// Send a request to the server. - Request(RequestMessage), - /// Send a subscription request to the server. - Subscribe(SubscriptionMessage), - /// Register a notification handler - RegisterNotification(RegisterNotificationMessage), - /// Unregister a notification handler - UnregisterNotification(String), - /// When a subscription channel is closed, we send this message to the background - /// task to mark it ready for garbage collection. - // NOTE: It is not possible to cancel pending subscriptions or pending requests. - // Such operations will be blocked until a response is received or the background - // thread has been terminated. - SubscriptionClosed(SubscriptionId<'static>), -} - -impl Subscription -where - Notif: DeserializeOwned, -{ - /// Returns the next notification from the stream. - /// This may return `None` if the subscription has been terminated, - /// which may happen if the channel becomes full or is dropped. - /// - /// **Note:** This has an identical signature to the [`StreamExt::next`] - /// method (and delegates to that). Import [`StreamExt`] if you'd like - /// access to other stream combinator methods. - #[allow(clippy::should_implement_trait)] - pub async fn next(&mut self) -> Option> { - StreamExt::next(self).await - } -} - -impl Stream for Subscription -where - Notif: DeserializeOwned, -{ - type Item = Result; - fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll> { - let n = futures_util::ready!(self.notifs_rx.poll_next_unpin(cx)); - let res = n.map(|n| match serde_json::from_value::>(n) { - Ok(NotifResponse::Ok(parsed)) => Ok(parsed), - Ok(NotifResponse::Err(e)) => Err(Error::SubscriptionClosed(e)), - Err(e) => Err(Error::ParseError(e)), - }); - task::Poll::Ready(res) - } -} - -impl Drop for Subscription { - fn drop(&mut self) { - // We can't actually guarantee that this goes through. If the background task is busy, then - // the channel's buffer will be full. - // However, when a notification arrives, the background task will realize that the channel - // to the `Callback` has been closed. - let kind = std::mem::replace(&mut self.kind, SubscriptionKind::Subscription(SubscriptionId::Num(0))); - - let msg = match kind { - SubscriptionKind::Method(notif) => FrontToBack::UnregisterNotification(notif), - SubscriptionKind::Subscription(sub_id) => FrontToBack::SubscriptionClosed(sub_id), - }; - let _ = self.to_back.send(msg).now_or_never(); - } -} - -#[derive(Debug)] -/// Keep track of request IDs. -pub struct RequestIdManager { - // Current pending requests. - current_pending: Arc<()>, - /// Max concurrent pending requests allowed. - max_concurrent_requests: usize, - /// Get the next request ID. - current_id: AtomicU64, -} - -impl RequestIdManager { - /// Create a new `RequestIdGuard` with the provided concurrency limit. - pub fn new(limit: usize) -> Self { - Self { current_pending: Arc::new(()), max_concurrent_requests: limit, current_id: AtomicU64::new(0) } - } - - fn get_slot(&self) -> Result, Error> { - // Strong count is 1 at start, so that's why we use `>` and not `>=`. - if Arc::strong_count(&self.current_pending) > self.max_concurrent_requests { - Err(Error::MaxSlotsExceeded) - } else { - Ok(self.current_pending.clone()) - } - } - - /// Attempts to get the next request ID. - /// - /// Fails if request limit has been exceeded. - pub fn next_request_id(&self) -> Result, Error> { - let rc = self.get_slot()?; - let id = self.current_id.fetch_add(1, Ordering::SeqCst); - Ok(RequestIdGuard { _rc: rc, id }) - } - - /// Attempts to get the `n` number next IDs that only counts as one request. - /// - /// Fails if request limit has been exceeded. - pub fn next_request_ids(&self, len: usize) -> Result>, Error> { - let rc = self.get_slot()?; - let mut ids = Vec::with_capacity(len); - for _ in 0..len { - ids.push(self.current_id.fetch_add(1, Ordering::SeqCst)); - } - Ok(RequestIdGuard { _rc: rc, id: ids }) - } -} - -/// Reference counted request ID. -#[derive(Debug)] -pub struct RequestIdGuard { - id: T, - /// Reference count decreased when dropped. - _rc: Arc<()>, -} - -impl RequestIdGuard { - /// Get the actual ID. - pub fn inner(&self) -> &T { - &self.id - } -} - -#[cfg(test)] -mod tests { - use super::RequestIdManager; - - #[test] - fn request_id_guard_works() { - let manager = RequestIdManager::new(2); - let _first = manager.next_request_id().unwrap(); - - { - let _second = manager.next_request_ids(13).unwrap(); - assert!(manager.next_request_id().is_err()); - // second dropped here. - } - - assert!(manager.next_request_id().is_ok()); - } -} - -/// What certificate store to use -#[derive(Clone, Copy, Debug, PartialEq)] -#[non_exhaustive] -pub enum CertificateStore { - /// Use the native system certificate store - Native, - /// Use WebPKI's certificate store - WebPki, -} diff --git a/types/src/lib.rs b/types/src/lib.rs index 0a1718705c..d4b57b80c9 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -37,9 +37,6 @@ pub const TEN_MB_SIZE_BYTES: u32 = 10 * 1024 * 1024; /// Error type. pub mod error; -/// Client types. -mod client; - /// JSON-RPC params related types. pub mod params; @@ -54,7 +51,6 @@ pub mod error_response; // pub use async_trait::async_trait; pub use beef::Cow; -pub use client::*; pub use error::{CallError, Error}; pub use params::{Id, Params, ParamsSequence, ParamsSer, SubscriptionId, TwoPointZero}; pub use serde::{de::DeserializeOwned, Serialize}; diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index 59dcc18b31..8398f79939 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -34,9 +34,8 @@ use crate::helpers::{ use crate::manager::RequestManager; use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; use crate::types::{ - BatchMessage, CertificateStore, Error, ErrorResponse, FrontToBack, Id, Notification, NotificationSer, ParamsSer, - RegisterNotificationMessage, RequestIdManager, RequestMessage, RequestSer, Response, Subscription, - SubscriptionKind, SubscriptionMessage, SubscriptionResponse, TEN_MB_SIZE_BYTES, + Error, ErrorResponse, Id, Notification, NotificationSer, ParamsSer, RequestSer, Response, SubscriptionResponse, + TEN_MB_SIZE_BYTES, }; use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; @@ -44,6 +43,10 @@ use futures::future::Either; use futures::prelude::*; use futures::sink::SinkExt; use http::uri::{InvalidUri, Uri}; +use jsonrpsee_core::client::{ + BatchMessage, CertificateStore, FrontToBack, RegisterNotificationMessage, RequestIdManager, RequestMessage, + Subscription, SubscriptionKind, SubscriptionMessage, +}; use jsonrpsee_core::traits::{Client, SubscriptionClient}; use serde::de::DeserializeOwned; use tokio::sync::Mutex; diff --git a/ws-client/src/helpers.rs b/ws-client/src/helpers.rs index cd04ed3564..b111a6553d 100644 --- a/ws-client/src/helpers.rs +++ b/ws-client/src/helpers.rs @@ -30,10 +30,10 @@ use std::time::Duration; use crate::manager::{RequestManager, RequestStatus}; use crate::transport::Sender as WsSender; use crate::types::{ - Error, ErrorResponse, Id, Notification, ParamsSer, RequestMessage, RequestSer, Response, SubscriptionId, - SubscriptionResponse, + Error, ErrorResponse, Id, Notification, ParamsSer, RequestSer, Response, SubscriptionId, SubscriptionResponse, }; use futures::channel::{mpsc, oneshot}; +use jsonrpsee_core::client::RequestMessage; use serde_json::Value as JsonValue; /// Attempts to process a batch response. diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index dc1d40b965..1c5d7ca69b 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -27,8 +27,9 @@ #![cfg(test)] use crate::types::error::Error; use crate::types::error_response::{ErrorCode, ErrorObject, ErrorResponse}; -use crate::types::{ParamsSer, Subscription}; +use crate::types::ParamsSer; use crate::WsClientBuilder; +use jsonrpsee_core::client::Subscription; use jsonrpsee_core::rpc_params; use jsonrpsee_core::traits::{Client, SubscriptionClient}; use jsonrpsee_test_utils::helpers::*; diff --git a/ws-client/src/transport.rs b/ws-client/src/transport.rs index 026ec58eb8..0390dbc5e8 100644 --- a/ws-client/src/transport.rs +++ b/ws-client/src/transport.rs @@ -29,10 +29,11 @@ use std::io; use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; -use crate::{stream::EitherStream, types::CertificateStore}; +use crate::stream::EitherStream; use beef::Cow; use futures::io::{BufReader, BufWriter}; use http::Uri; +use jsonrpsee_core::client::CertificateStore; use soketto::connection; use soketto::handshake::client::{Client as WsHandshakeClient, Header, ServerResponse}; use thiserror::Error; From f914dcab5ca8c109c35399975f98b63b27abcf38 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Wed, 15 Dec 2021 16:14:24 +0000 Subject: [PATCH 16/24] Continued move types -> core --- core/Cargo.toml | 5 +- core/src/client.rs | 14 +- core/src/error.rs | 212 +++++++++++++ core/src/http_helpers.rs | 2 +- core/src/lib.rs | 18 +- core/src/server/helpers.rs | 10 +- core/src/server/resource_limiting.rs | 4 +- core/src/server/rpc_module.rs | 11 +- core/src/traits.rs | 2 +- examples/proc_macro.rs | 3 +- examples/ws_subscription.rs | 2 +- http-client/src/client.rs | 3 +- http-client/src/tests.rs | 7 +- http-client/src/transport.rs | 2 +- http-server/src/access_control/mod.rs | 4 +- http-server/src/response.rs | 2 +- http-server/src/server.rs | 4 +- http-server/src/tests.rs | 4 +- proc-macros/src/helpers.rs | 8 +- proc-macros/src/lib.rs | 2 +- proc-macros/src/render_client.rs | 8 +- tests/tests/helpers.rs | 2 +- tests/tests/integration_tests.rs | 4 +- tests/tests/middleware.rs | 3 +- tests/tests/proc_macros.rs | 5 +- tests/tests/resource_limiting.rs | 2 +- types/src/error.rs | 422 ++++++++++++++++---------- types/src/error_response.rs | 308 ------------------- types/src/lib.rs | 18 +- ws-client/src/client.rs | 3 +- ws-client/src/helpers.rs | 4 +- ws-client/src/manager.rs | 4 +- ws-client/src/tests.rs | 4 +- ws-server/src/future.rs | 2 +- ws-server/src/server.rs | 4 +- ws-server/src/tests.rs | 7 +- 36 files changed, 559 insertions(+), 560 deletions(-) create mode 100644 core/src/error.rs delete mode 100644 types/src/error_response.rs diff --git a/core/Cargo.toml b/core/Cargo.toml index 5ddf804ef4..2db97fecf1 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -7,10 +7,11 @@ edition = "2018" license = "MIT" [dependencies] +anyhow = "1" arrayvec = "0.7.1" async-trait = "0.1" beef = { version = "0.5.1", features = ["impl_serde"] } -thiserror = { version = "1", optional = true } +thiserror = "1" futures-channel = { version = "0.3.14", default-features = false, optional = true } futures-util = { version = "0.3.14", default-features = false, optional = true } hyper = { version = "0.14.10", default-features = false, features = ["stream"], optional = true } @@ -20,6 +21,7 @@ rustc-hash = { version = "1", optional = true } rand = { version = "0.8", optional = true } serde = { version = "1.0", default-features = false, features = ["derive"], optional = true } serde_json = { version = "1", features = ["raw_value"], optional = true } +soketto = "0.7.1" parking_lot = { version = "0.11", optional = true } tokio = { version = "1.8", features = ["rt"], optional = true } @@ -27,7 +29,6 @@ tokio = { version = "1.8", features = ["rt"], optional = true } default = [] http-helpers = ["hyper", "futures-util", "jsonrpsee-types"] server = [ - "thiserror", "futures-channel", "futures-util", "jsonrpsee-types", diff --git a/core/src/client.rs b/core/src/client.rs index bd0d542a11..017640a10a 100644 --- a/core/src/client.rs +++ b/core/src/client.rs @@ -30,20 +30,20 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::task; +use crate::error::{Error, SubscriptionClosedError}; use core::marker::PhantomData; use futures_channel::{mpsc, oneshot}; -use futures_util::{ - future::FutureExt, - sink::SinkExt, - stream::{Stream, StreamExt}, -}; -use jsonrpsee_types::{error::SubscriptionClosedError, Error, SubscriptionId}; +use futures_util::future::FutureExt; +use futures_util::sink::SinkExt; +use futures_util::stream::{Stream, StreamExt}; +use jsonrpsee_types::SubscriptionId; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value as JsonValue; #[doc(hidden)] pub mod __reexports { - pub use jsonrpsee_types::{to_json_value, ParamsSer}; + pub use crate::to_json_value; + pub use jsonrpsee_types::ParamsSer; } #[macro_export] diff --git a/core/src/error.rs b/core/src/error.rs new file mode 100644 index 0000000000..97c738e306 --- /dev/null +++ b/core/src/error.rs @@ -0,0 +1,212 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// +// Permission is hereby granted, free of charge, to any +// person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the +// Software without restriction, including without +// limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software +// is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice +// shall be included in all copies or substantial portions +// of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +use std::fmt; + +use jsonrpsee_types::error::CallError; +use serde::{Deserialize, Serialize}; + +/// Convenience type for displaying errors. +#[derive(Clone, Debug, PartialEq)] +pub struct Mismatch { + /// Expected value. + pub expected: T, + /// Actual value. + pub got: T, +} + +impl fmt::Display for Mismatch { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_fmt(format_args!("Expected: {}, Got: {}", self.expected, self.got)) + } +} + +// NOTE(niklasad1): this `From` impl is a bit opinionated to regard all generic errors as `CallError`. +// In practice this should be the most common use case for users of this library. +impl From for Error { + fn from(err: anyhow::Error) -> Self { + Error::Call(CallError::Failed(err)) + } +} + +/// Error type. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// Error that occurs when a call failed. + #[error("Server call failed: {0}")] + Call(#[from] CallError), + /// Networking error or error on the low-level protocol layer. + #[error("Networking or low-level protocol error: {0}")] + Transport(#[source] anyhow::Error), + /// JSON-RPC request error. + #[error("JSON-RPC request error: {0:?}")] + Request(String), + /// Frontend/backend channel error. + #[error("Frontend/backend channel error: {0}")] + Internal(#[from] futures_channel::mpsc::SendError), + /// Invalid response, + #[error("Invalid response: {0}")] + InvalidResponse(Mismatch), + /// The background task has been terminated. + #[error("The background task been terminated because: {0}; restart required")] + RestartNeeded(String), + /// Failed to parse the data. + #[error("Parse error: {0}")] + ParseError(#[from] serde_json::Error), + /// Invalid subscription ID. + #[error("Invalid subscription ID")] + InvalidSubscriptionId, + /// Invalid request ID. + #[error("Invalid request ID")] + InvalidRequestId, + /// Client received a notification with an unregistered method + #[error("Unregistered notification method")] + UnregisteredNotification(String), + /// A request with the same request ID has already been registered. + #[error("A request with the same request ID has already been registered")] + DuplicateRequestId, + /// Method was already registered. + #[error("Method: {0} was already registered")] + MethodAlreadyRegistered(String), + /// Method with that name has not yet been registered. + #[error("Method: {0} has not yet been registered")] + MethodNotFound(String), + /// Subscribe and unsubscribe method names are the same. + #[error("Cannot use the same method name for subscribe and unsubscribe, used: {0}")] + SubscriptionNameConflict(String), + /// Subscription got closed. + #[error("Subscription closed: {0:?}")] + SubscriptionClosed(SubscriptionClosedError), + /// Request timeout + #[error("Request timeout")] + RequestTimeout, + /// Configured max number of request slots exceeded. + #[error("Configured max number of request slots exceeded")] + MaxSlotsExceeded, + /// Attempted to stop server that is already stopped. + #[error("Attempted to stop server that is already stopped")] + AlreadyStopped, + /// List passed into `set_allowed_origins` was empty + #[error("Must set at least one allowed value for the {0} header")] + EmptyAllowList(&'static str), + /// Failed to execute a method because a resource was already at capacity + #[error("Resource at capacity: {0}")] + ResourceAtCapacity(&'static str), + /// Failed to register a resource due to a name conflict + #[error("Resource name already taken: {0}")] + ResourceNameAlreadyTaken(&'static str), + /// Failed to initialize resources for a method at startup + #[error("Resource name `{0}` not found for method `{1}`")] + ResourceNameNotFoundForMethod(&'static str, &'static str), + /// Trying to claim resources for a method execution, but the method resources have not been initialized + #[error("Method `{0}` has uninitialized resources")] + UninitializedMethod(Box), + /// Failed to register a resource due to a maximum number of resources already registered + #[error("Maximum number of resources reached")] + MaxResourcesReached, + /// Custom error. + #[error("Custom error: {0}")] + Custom(String), + /// Not implemented for HTTP clients. + #[error("Not implemented")] + HttpNotImplemented, +} + +impl Error { + /// Create `Error::CallError` from a generic error. + /// Useful if you don't care about specific JSON-RPC error code and + /// just wants to return your custom error type. + pub fn to_call_error(err: E) -> Self + where + E: std::error::Error + Send + Sync + 'static, + { + Error::Call(CallError::from_std_error(err)) + } +} + +/// Error type with a special `subscription_closed` field to detect that +/// a subscription has been closed to distinguish valid items produced +/// by the server on the subscription stream from an error. +#[derive(Deserialize, Serialize, Debug, PartialEq)] +pub struct SubscriptionClosedError { + subscription_closed: String, + id: u64, +} + +impl SubscriptionClosedError { + /// Create a new subscription closed error. + pub fn new(reason: impl Into, id: u64) -> Self { + Self { subscription_closed: reason.into(), id } + } + + /// Get the reason why the subscription was closed. + pub fn close_reason(&self) -> &str { + &self.subscription_closed + } + + /// Get the subscription ID. + pub fn subscription_id(&self) -> u64 { + self.id + } +} + +/// Generic transport error. +#[derive(Debug, thiserror::Error)] +pub enum GenericTransportError { + /// Request was too large. + #[error("The request was too big")] + TooLarge, + /// Malformed request + #[error("Malformed request")] + Malformed, + /// Concrete transport error. + #[error("Transport error: {0}")] + Inner(T), +} + +impl From for Error { + fn from(io_err: std::io::Error) -> Error { + Error::Transport(io_err.into()) + } +} + +impl From for Error { + fn from(handshake_err: soketto::handshake::Error) -> Error { + Error::Transport(handshake_err.into()) + } +} + +impl From for Error { + fn from(conn_err: soketto::connection::Error) -> Error { + Error::Transport(conn_err.into()) + } +} + +impl From for Error { + fn from(hyper_err: hyper::Error) -> Error { + Error::Transport(hyper_err.into()) + } +} diff --git a/core/src/http_helpers.rs b/core/src/http_helpers.rs index 4fc43abbf6..a8daaea3a7 100644 --- a/core/src/http_helpers.rs +++ b/core/src/http_helpers.rs @@ -26,8 +26,8 @@ //! Utility methods relying on hyper +use crate::error::GenericTransportError; use futures_util::stream::StreamExt; -use jsonrpsee_types::error::GenericTransportError; /// Read a data from a [`hyper::Body`] and return the data if it is valid and within the allowed size range. /// diff --git a/core/src/lib.rs b/core/src/lib.rs index 05d10d32ce..396d7c1301 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -28,12 +28,15 @@ #![warn(missing_docs, missing_debug_implementations, unreachable_pub)] -/// Middleware trait and implementation. -pub mod middleware; +/// Error type. +pub mod error; /// Traits pub mod traits; +/// Middleware trait and implementation. +pub mod middleware; + /// Shared hyper helpers. #[cfg(feature = "http-helpers")] pub mod http_helpers; @@ -47,6 +50,10 @@ pub mod server; pub mod client; pub use async_trait::async_trait; +pub use error::Error; + +/// JSON-RPC result. +pub type RpcResult = std::result::Result; /// Re-exports for proc-macro library to not require any additional /// dependencies to be explicitly added on the client side. @@ -56,3 +63,10 @@ pub mod __reexports { pub use serde; pub use serde_json; } + +pub use beef::Cow; +pub use serde::{de::DeserializeOwned, Serialize}; +pub use serde_json::{ + to_value as to_json_value, value::to_raw_value as to_json_raw_value, value::RawValue as JsonRawValue, + Value as JsonValue, +}; diff --git a/core/src/server/helpers.rs b/core/src/server/helpers.rs index 49769a7b8f..0a099db81d 100644 --- a/core/src/server/helpers.rs +++ b/core/src/server/helpers.rs @@ -26,14 +26,14 @@ use std::io; +use crate::{to_json_raw_value, Error}; use futures_channel::mpsc; use futures_util::stream::StreamExt; -use jsonrpsee_types::error::{CallError, Error}; -use jsonrpsee_types::error_response::{ - ErrorCode, ErrorObject, ErrorResponse, CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, - UNKNOWN_ERROR_CODE, +use jsonrpsee_types::error::{ + CallError, ErrorCode, ErrorObject, ErrorResponse, CALL_EXECUTION_FAILED_CODE, OVERSIZED_RESPONSE_CODE, + OVERSIZED_RESPONSE_MSG, UNKNOWN_ERROR_CODE, }; -use jsonrpsee_types::{to_json_raw_value, Id, InvalidRequest, Response}; +use jsonrpsee_types::{Id, InvalidRequest, Response}; use serde::Serialize; /// Bounded writer that allows writing at most `max_len` bytes. diff --git a/core/src/server/resource_limiting.rs b/core/src/server/resource_limiting.rs index 3127176e5e..c36a457a2c 100644 --- a/core/src/server/resource_limiting.rs +++ b/core/src/server/resource_limiting.rs @@ -52,7 +52,7 @@ //! `#[method]` attribute: //! //! ``` -//! # use jsonrpsee::{types::RpcResult, proc_macros::rpc}; +//! # use jsonrpsee::{core::RpcResult, proc_macros::rpc}; //! # //! #[rpc(server)] //! pub trait Rpc { @@ -91,8 +91,8 @@ use std::sync::Arc; +use crate::Error; use arrayvec::ArrayVec; -use jsonrpsee_types::error::Error; use parking_lot::Mutex; // The number of kinds of resources that can be used for limiting. diff --git a/core/src/server/rpc_module.rs b/core/src/server/rpc_module.rs index 978fc53c61..c78a6a7adf 100644 --- a/core/src/server/rpc_module.rs +++ b/core/src/server/rpc_module.rs @@ -30,22 +30,21 @@ use std::future::Future; use std::ops::{Deref, DerefMut}; use std::sync::Arc; +use crate::error::{Error, SubscriptionClosedError}; use crate::server::helpers::MethodSink; use crate::server::resource_limiting::{ResourceGuard, ResourceTable, ResourceVec, Resources}; +use crate::to_json_raw_value; use crate::traits::ToRpcParams; use beef::Cow; use futures_channel::{mpsc, oneshot}; use futures_util::{future::BoxFuture, FutureExt, StreamExt}; -use jsonrpsee_types::error::{Error, SubscriptionClosedError}; -use jsonrpsee_types::error_response::{invalid_subscription_err, ErrorCode, CALL_EXECUTION_FAILED_CODE}; -use jsonrpsee_types::to_json_raw_value; +use jsonrpsee_types::error::{invalid_subscription_err, ErrorCode, CALL_EXECUTION_FAILED_CODE}; use jsonrpsee_types::{ - DeserializeOwned, Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, - SubscriptionResponse, + Id, Params, Request, Response, SubscriptionId as RpcSubscriptionId, SubscriptionPayload, SubscriptionResponse, }; use parking_lot::Mutex; use rustc_hash::FxHashMap; -use serde::Serialize; +use serde::{de::DeserializeOwned, Serialize}; /// A `MethodCallback` is an RPC endpoint, callable with a standard JSON-RPC request, /// implemented as a function pointer to a `Fn` function taking four arguments: diff --git a/core/src/traits.rs b/core/src/traits.rs index 08b45b2079..6f1ffe3595 100644 --- a/core/src/traits.rs +++ b/core/src/traits.rs @@ -25,8 +25,8 @@ // DEALINGS IN THE SOFTWARE. use crate::client::Subscription; +use crate::Error; use async_trait::async_trait; -use jsonrpsee_types::Error; use jsonrpsee_types::ParamsSer; use serde::de::DeserializeOwned; use serde::Serialize; diff --git a/examples/proc_macro.rs b/examples/proc_macro.rs index d9ea961415..685bf9448c 100644 --- a/examples/proc_macro.rs +++ b/examples/proc_macro.rs @@ -26,9 +26,8 @@ use std::net::SocketAddr; -use jsonrpsee::core::{async_trait, client::Subscription}; +use jsonrpsee::core::{async_trait, client::Subscription, Error}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::error::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder, WsServerHandle}; diff --git a/examples/ws_subscription.rs b/examples/ws_subscription.rs index 9543099ed1..5e8ce32004 100644 --- a/examples/ws_subscription.rs +++ b/examples/ws_subscription.rs @@ -28,8 +28,8 @@ use std::net::SocketAddr; use jsonrpsee::core::client::Subscription; use jsonrpsee::core::traits::SubscriptionClient; +use jsonrpsee::core::Error; use jsonrpsee::rpc_params; -use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/http-client/src/client.rs b/http-client/src/client.rs index 2da714dca2..637a7d2c4a 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -28,10 +28,11 @@ use std::sync::Arc; use std::time::Duration; use crate::transport::HttpTransportClient; -use crate::types::{Error, ErrorResponse, Id, NotificationSer, ParamsSer, RequestSer, Response, TEN_MB_SIZE_BYTES}; +use crate::types::{ErrorResponse, Id, NotificationSer, ParamsSer, RequestSer, Response, TEN_MB_SIZE_BYTES}; use async_trait::async_trait; use jsonrpsee_core::client::{CertificateStore, RequestIdManager, Subscription}; use jsonrpsee_core::traits::{Client, SubscriptionClient}; +use jsonrpsee_core::Error; use rustc_hash::FxHashMap; use serde::de::DeserializeOwned; diff --git a/http-client/src/tests.rs b/http-client/src/tests.rs index a378045ee0..417ab06324 100644 --- a/http-client/src/tests.rs +++ b/http-client/src/tests.rs @@ -24,15 +24,16 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::types::error::Error; -use crate::types::error_response::{ErrorCode, ErrorObject, ErrorResponse}; -use crate::types::{JsonValue, ParamsSer}; +use crate::types::error::{ErrorCode, ErrorObject, ErrorResponse}; +use crate::types::ParamsSer; use crate::HttpClientBuilder; use jsonrpsee_core::rpc_params; use jsonrpsee_core::traits::Client; +use jsonrpsee_core::Error; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::Id; use jsonrpsee_test_utils::TimeoutFutureExt; +use serde_json::value::Value as JsonValue; #[tokio::test] async fn method_call_works() { diff --git a/http-client/src/transport.rs b/http-client/src/transport.rs index 2dcbc0eae6..74375098b4 100644 --- a/http-client/src/transport.rs +++ b/http-client/src/transport.rs @@ -6,10 +6,10 @@ // that we need to be guaranteed that hyper doesn't re-use an existing connection if we ever reset // the JSON-RPC request id to a value that might have already been used. -use crate::types::error::GenericTransportError; use hyper::client::{Client, HttpConnector}; use hyper::Uri; use jsonrpsee_core::client::CertificateStore; +use jsonrpsee_core::error::GenericTransportError; use jsonrpsee_core::http_helpers; use thiserror::Error; diff --git a/http-server/src/access_control/mod.rs b/http-server/src/access_control/mod.rs index ae1101e90e..8c0fd0d76b 100644 --- a/http-server/src/access_control/mod.rs +++ b/http-server/src/access_control/mod.rs @@ -30,12 +30,10 @@ pub(crate) mod cors; pub(crate) mod hosts; mod matcher; -use crate::types::Error; - use cors::{AccessControlAllowHeaders, AccessControlAllowOrigin}; use hosts::{AllowHosts, Host}; use hyper::header; -use jsonrpsee_core::http_helpers; +use jsonrpsee_core::{http_helpers, Error}; /// Define access on control on HTTP layer. #[derive(Clone, Debug)] diff --git a/http-server/src/response.rs b/http-server/src/response.rs index 8e3216dc15..8dbdb20ec6 100644 --- a/http-server/src/response.rs +++ b/http-server/src/response.rs @@ -26,7 +26,7 @@ //! Contains common builders for hyper responses. -use crate::types::error_response::{ErrorCode, ErrorResponse}; +use crate::types::error::{ErrorCode, ErrorResponse}; use crate::types::Id; const JSON: &str = "application/json; charset=utf-8"; diff --git a/http-server/src/server.rs b/http-server/src/server.rs index a12a2990f8..c159e592b0 100644 --- a/http-server/src/server.rs +++ b/http-server/src/server.rs @@ -36,13 +36,13 @@ use futures_util::{future::join_all, stream::StreamExt, FutureExt}; use hyper::server::{conn::AddrIncoming, Builder as HyperBuilder}; use hyper::service::{make_service_fn, service_fn}; use hyper::Error as HyperError; +use jsonrpsee_core::error::{Error, GenericTransportError}; use jsonrpsee_core::http_helpers::read_body; use jsonrpsee_core::middleware::Middleware; use jsonrpsee_core::server::helpers::{collect_batch_response, prepare_error, MethodSink}; use jsonrpsee_core::server::resource_limiting::Resources; use jsonrpsee_core::server::rpc_module::{MethodResult, Methods}; -use jsonrpsee_types::error::{Error, GenericTransportError}; -use jsonrpsee_types::error_response::ErrorCode; +use jsonrpsee_types::error::ErrorCode; use jsonrpsee_types::{Id, Notification, Request, TEN_MB_SIZE_BYTES}; use serde_json::value::RawValue; use socket2::{Domain, Socket, Type}; diff --git a/http-server/src/tests.rs b/http-server/src/tests.rs index 6fa15b26e7..40d043f335 100644 --- a/http-server/src/tests.rs +++ b/http-server/src/tests.rs @@ -29,9 +29,9 @@ use std::net::SocketAddr; use std::time::Duration; -use crate::types::error::{CallError, Error}; +use crate::types::error::CallError; use crate::{server::ServerHandle, HttpServerBuilder, RpcModule}; - +use jsonrpsee_core::Error; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, StatusCode, TestContext}; use jsonrpsee_test_utils::TimeoutFutureExt; diff --git a/proc-macros/src/helpers.rs b/proc-macros/src/helpers.rs index 471f069f0f..4c6c3f4e37 100644 --- a/proc-macros/src/helpers.rs +++ b/proc-macros/src/helpers.rs @@ -104,17 +104,17 @@ pub(crate) fn generate_where_clause( if is_client { if visitor.input_params.contains(&ty.ident) { - bounds.push(parse_quote!(jsonrpsee::types::Serialize)) + bounds.push(parse_quote!(jsonrpsee::core::Serialize)) } if visitor.ret_params.contains(&ty.ident) || visitor.sub_params.contains(&ty.ident) { - bounds.push(parse_quote!(jsonrpsee::types::DeserializeOwned)) + bounds.push(parse_quote!(jsonrpsee::core::DeserializeOwned)) } } else { if visitor.input_params.contains(&ty.ident) { - bounds.push(parse_quote!(jsonrpsee::types::DeserializeOwned)) + bounds.push(parse_quote!(jsonrpsee::core::DeserializeOwned)) } if visitor.ret_params.contains(&ty.ident) || visitor.sub_params.contains(&ty.ident) { - bounds.push(parse_quote!(jsonrpsee::types::Serialize)) + bounds.push(parse_quote!(jsonrpsee::core::Serialize)) } } diff --git a/proc-macros/src/lib.rs b/proc-macros/src/lib.rs index 842da11429..9c9a9b96ce 100644 --- a/proc-macros/src/lib.rs +++ b/proc-macros/src/lib.rs @@ -101,7 +101,7 @@ pub(crate) mod visitor; /// // Note that `subscription_sink` was added automatically. /// fn sub(&self, subscription_sink: SubscriptionSink); /// -/// fn into_rpc(self) -> Result { +/// fn into_rpc(self) -> Result { /// // Actual implementation stripped, but inside we will create /// // a module with one method and one subscription /// } diff --git a/proc-macros/src/render_client.rs b/proc-macros/src/render_client.rs index c440a5e4eb..1258887f4d 100644 --- a/proc-macros/src/render_client.rs +++ b/proc-macros/src/render_client.rs @@ -71,7 +71,7 @@ impl RpcDescription { fn render_method(&self, method: &RpcMethod) -> Result { // `jsonrpsee::Error` - let jrps_error = self.jrps_client_item(quote! { types::Error }); + let jrps_error = self.jrps_client_item(quote! { core::Error }); // Rust method to invoke (e.g. `self.(...)`). let rust_method_name = &method.signature.sig.ident; // List of inputs to put into `Params` (e.g. `self.foo(<12, "baz">)`). @@ -81,7 +81,7 @@ impl RpcDescription { let rpc_method_name = self.rpc_identifier(&method.name); // Called method is either `request` or `notification`. - // `returns` represent the return type of the *rust method* (`Result< <..>, jsonrpsee::Error`). + // `returns` represent the return type of the *rust method* (`Result< <..>, jsonrpsee::core::Error`). let (called_method, returns) = if let Some(returns) = &method.returns { let called_method = quote::format_ident!("request"); let returns = quote! { #returns }; @@ -112,8 +112,8 @@ impl RpcDescription { } fn render_sub(&self, sub: &RpcSubscription) -> Result { - // `jsonrpsee::Error` - let jrps_error = self.jrps_client_item(quote! { types::Error }); + // `jsonrpsee::core::Error` + let jrps_error = self.jrps_client_item(quote! { core::Error }); // Rust method to invoke (e.g. `self.(...)`). let rust_method_name = &sub.signature.sig.ident; // List of inputs to put into `Params` (e.g. `self.foo(<12, "baz">)`). diff --git a/tests/tests/helpers.rs b/tests/tests/helpers.rs index 04f0c019ea..a191f1f3ea 100644 --- a/tests/tests/helpers.rs +++ b/tests/tests/helpers.rs @@ -27,8 +27,8 @@ use std::net::SocketAddr; use std::time::Duration; +use jsonrpsee::core::Error; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; -use jsonrpsee::types::Error; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; diff --git a/tests/tests/integration_tests.rs b/tests/tests/integration_tests.rs index f4026958a8..831ea4bf7a 100644 --- a/tests/tests/integration_tests.rs +++ b/tests/tests/integration_tests.rs @@ -32,11 +32,11 @@ use std::time::Duration; use helpers::{http_server, websocket_server, websocket_server_with_subscription}; use jsonrpsee::core::client::Subscription; +use jsonrpsee::core::error::SubscriptionClosedError; use jsonrpsee::core::traits::{Client, SubscriptionClient}; +use jsonrpsee::core::{Error, JsonValue}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::rpc_params; -use jsonrpsee::types::error::SubscriptionClosedError; -use jsonrpsee::types::{Error, JsonValue}; use jsonrpsee::ws_client::WsClientBuilder; mod helpers; diff --git a/tests/tests/middleware.rs b/tests/tests/middleware.rs index c7fa7087d8..d02fc21576 100644 --- a/tests/tests/middleware.rs +++ b/tests/tests/middleware.rs @@ -29,11 +29,10 @@ use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use std::time::Duration; -use jsonrpsee::core::{middleware::Middleware, traits::Client}; +use jsonrpsee::core::{middleware::Middleware, traits::Client, Error}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; diff --git a/tests/tests/proc_macros.rs b/tests/tests/proc_macros.rs index db03bf33a2..494258147e 100644 --- a/tests/tests/proc_macros.rs +++ b/tests/tests/proc_macros.rs @@ -28,17 +28,16 @@ use std::net::SocketAddr; +use jsonrpsee::core::Error; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::HttpServerBuilder; -use jsonrpsee::types::Error; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::WsServerBuilder; use serde_json::json; mod rpc_impl { - use jsonrpsee::core::async_trait; + use jsonrpsee::core::{async_trait, RpcResult}; use jsonrpsee::proc_macros::rpc; - use jsonrpsee::types::RpcResult; use jsonrpsee::ws_server::SubscriptionSink; #[rpc(client, server, namespace = "foo")] diff --git a/tests/tests/resource_limiting.rs b/tests/tests/resource_limiting.rs index f53c586105..f0616f3367 100644 --- a/tests/tests/resource_limiting.rs +++ b/tests/tests/resource_limiting.rs @@ -28,10 +28,10 @@ use std::net::SocketAddr; use std::time::Duration; use jsonrpsee::core::traits::Client; +use jsonrpsee::core::Error; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::Error; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{WsServerBuilder, WsServerHandle}; use jsonrpsee::RpcModule; diff --git a/types/src/error.rs b/types/src/error.rs index 04264824db..3bbe1e1014 100644 --- a/types/src/error.rs +++ b/types/src/error.rs @@ -26,21 +26,208 @@ use std::fmt; +use crate::params::{Id, TwoPointZero}; +use beef::Cow; +use serde::de::Deserializer; +use serde::ser::Serializer; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; +use thiserror::Error; -/// Convenience type for displaying errors. -#[derive(Clone, Debug, PartialEq)] -pub struct Mismatch { - /// Expected value. - pub expected: T, - /// Actual value. - pub got: T, +/// [Failed JSON-RPC response object](https://www.jsonrpc.org/specification#response_object). +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct ErrorResponse<'a> { + /// JSON-RPC version. + pub jsonrpc: TwoPointZero, + /// Error. + #[serde(borrow)] + pub error: ErrorObject<'a>, + /// Request ID + pub id: Id<'a>, } -impl fmt::Display for Mismatch { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_fmt(format_args!("Expected: {}, Got: {}", self.expected, self.got)) +impl<'a> ErrorResponse<'a> { + /// Create a new `ErrorResponse`. + pub fn new(error: ErrorObject<'a>, id: Id<'a>) -> Self { + Self { jsonrpc: TwoPointZero, error, id } + } +} + +impl<'a> fmt::Display for ErrorResponse<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", serde_json::to_string(&self).expect("infallible; qed")) + } +} + +/// JSON-RPC error object. +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct ErrorObject<'a> { + /// Code + pub code: ErrorCode, + /// Message + #[serde(borrow)] + pub message: Cow<'a, str>, + /// Optional data + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(borrow)] + pub data: Option<&'a RawValue>, +} + +impl<'a> ErrorObject<'a> { + /// Create a new `ErrorObject` with optional data. + pub fn new(code: ErrorCode, data: Option<&'a RawValue>) -> ErrorObject<'a> { + Self { code, message: code.message().into(), data } + } +} + +impl<'a> From for ErrorObject<'a> { + fn from(code: ErrorCode) -> Self { + Self { code, message: code.message().into(), data: None } + } +} + +impl<'a> PartialEq for ErrorObject<'a> { + fn eq(&self, other: &Self) -> bool { + let this_raw = self.data.map(|r| r.get()); + let other_raw = other.data.map(|r| r.get()); + self.code == other.code && self.message == other.message && this_raw == other_raw + } +} + +/// Parse error code. +pub const PARSE_ERROR_CODE: i32 = -32700; +/// Oversized request error code. +pub const OVERSIZED_REQUEST_CODE: i32 = -32701; +/// Oversized response error code. +pub const OVERSIZED_RESPONSE_CODE: i32 = -32702; +/// Internal error code. +pub const INTERNAL_ERROR_CODE: i32 = -32603; +/// Invalid params error code. +pub const INVALID_PARAMS_CODE: i32 = -32602; +/// Invalid request error code. +pub const INVALID_REQUEST_CODE: i32 = -32600; +/// Method not found error code. +pub const METHOD_NOT_FOUND_CODE: i32 = -32601; +/// Server is busy error code. +pub const SERVER_IS_BUSY_CODE: i32 = -32604; +/// Custom server error when a call failed. +pub const CALL_EXECUTION_FAILED_CODE: i32 = -32000; +/// Unknown error. +pub const UNKNOWN_ERROR_CODE: i32 = -32001; +/// Invalid subscription error code. +pub const INVALID_SUBSCRIPTION_CODE: i32 = -32002; + +/// Parse error message +pub const PARSE_ERROR_MSG: &str = "Parse error"; +/// Oversized request message +pub const OVERSIZED_REQUEST_MSG: &str = "Request is too big"; +/// Oversized response message +pub const OVERSIZED_RESPONSE_MSG: &str = "Response is too big"; +/// Internal error message. +pub const INTERNAL_ERROR_MSG: &str = "Internal error"; +/// Invalid params error message. +pub const INVALID_PARAMS_MSG: &str = "Invalid params"; +/// Invalid request error message. +pub const INVALID_REQUEST_MSG: &str = "Invalid request"; +/// Method not found error message. +pub const METHOD_NOT_FOUND_MSG: &str = "Method not found"; +/// Server is busy error message. +pub const SERVER_IS_BUSY_MSG: &str = "Server is busy, try again later"; +/// Reserved for implementation-defined server-errors. +pub const SERVER_ERROR_MSG: &str = "Server error"; + +/// JSONRPC error code +#[derive(Error, Debug, PartialEq, Copy, Clone)] +pub enum ErrorCode { + /// Invalid JSON was received by the server. + /// An error occurred on the server while parsing the JSON text. + ParseError, + /// The request was too big. + OversizedRequest, + /// The JSON sent is not a valid Request object. + InvalidRequest, + /// The method does not exist / is not available. + MethodNotFound, + /// Server is busy / resources are at capacity. + ServerIsBusy, + /// Invalid method parameter(s). + InvalidParams, + /// Internal JSON-RPC error. + InternalError, + /// Reserved for implementation-defined server-errors. + ServerError(i32), +} + +impl ErrorCode { + /// Returns integer code value + pub const fn code(&self) -> i32 { + use ErrorCode::*; + match *self { + ParseError => PARSE_ERROR_CODE, + OversizedRequest => OVERSIZED_REQUEST_CODE, + InvalidRequest => INVALID_REQUEST_CODE, + MethodNotFound => METHOD_NOT_FOUND_CODE, + ServerIsBusy => SERVER_IS_BUSY_CODE, + InvalidParams => INVALID_PARAMS_CODE, + InternalError => INTERNAL_ERROR_CODE, + ServerError(code) => code, + } + } + + /// Returns the message for the given error code. + pub const fn message(&self) -> &'static str { + use ErrorCode::*; + match self { + ParseError => PARSE_ERROR_MSG, + OversizedRequest => OVERSIZED_REQUEST_MSG, + InvalidRequest => INVALID_REQUEST_MSG, + MethodNotFound => METHOD_NOT_FOUND_MSG, + ServerIsBusy => SERVER_IS_BUSY_MSG, + InvalidParams => INVALID_PARAMS_MSG, + InternalError => INTERNAL_ERROR_MSG, + ServerError(_) => SERVER_ERROR_MSG, + } + } +} + +impl fmt::Display for ErrorCode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}: {}", self.code(), self.message()) + } +} + +impl From for ErrorCode { + fn from(code: i32) -> Self { + use ErrorCode::*; + match code { + PARSE_ERROR_CODE => ParseError, + OVERSIZED_REQUEST_CODE => OversizedRequest, + INVALID_REQUEST_CODE => InvalidRequest, + METHOD_NOT_FOUND_CODE => MethodNotFound, + INVALID_PARAMS_CODE => InvalidParams, + INTERNAL_ERROR_CODE => InternalError, + code => ServerError(code), + } + } +} + +impl<'a> serde::Deserialize<'a> for ErrorCode { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'a>, + { + let code: i32 = Deserialize::deserialize(deserializer)?; + Ok(ErrorCode::from(code)) + } +} + +impl serde::Serialize for ErrorCode { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_i32(self.code()) } } @@ -75,169 +262,78 @@ impl CallError { } } -// NOTE(niklasad1): this `From` impl is a bit opinionated to regard all generic errors as `CallError`. -// In practice this should be the most common use case for users of this library. -impl From for Error { - fn from(err: anyhow::Error) -> Self { - Error::Call(CallError::Failed(err)) - } +/// Create a invalid subscription ID error. +pub fn invalid_subscription_err(data: Option<&RawValue>) -> ErrorObject { + ErrorObject::new(ErrorCode::ServerError(INVALID_SUBSCRIPTION_CODE), data) } -/// Error type. -#[derive(Debug, thiserror::Error)] -pub enum Error { - /// Error that occurs when a call failed. - #[error("Server call failed: {0}")] - Call(#[from] CallError), - /// Networking error or error on the low-level protocol layer. - #[error("Networking or low-level protocol error: {0}")] - Transport(#[source] anyhow::Error), - /// JSON-RPC request error. - #[error("JSON-RPC request error: {0:?}")] - Request(String), - /// Frontend/backend channel error. - #[error("Frontend/backend channel error: {0}")] - Internal(#[from] futures_channel::mpsc::SendError), - /// Invalid response, - #[error("Invalid response: {0}")] - InvalidResponse(Mismatch), - /// The background task has been terminated. - #[error("The background task been terminated because: {0}; restart required")] - RestartNeeded(String), - /// Failed to parse the data. - #[error("Parse error: {0}")] - ParseError(#[from] serde_json::Error), - /// Invalid subscription ID. - #[error("Invalid subscription ID")] - InvalidSubscriptionId, - /// Invalid request ID. - #[error("Invalid request ID")] - InvalidRequestId, - /// Client received a notification with an unregistered method - #[error("Unregistered notification method")] - UnregisteredNotification(String), - /// A request with the same request ID has already been registered. - #[error("A request with the same request ID has already been registered")] - DuplicateRequestId, - /// Method was already registered. - #[error("Method: {0} was already registered")] - MethodAlreadyRegistered(String), - /// Method with that name has not yet been registered. - #[error("Method: {0} has not yet been registered")] - MethodNotFound(String), - /// Subscribe and unsubscribe method names are the same. - #[error("Cannot use the same method name for subscribe and unsubscribe, used: {0}")] - SubscriptionNameConflict(String), - /// Subscription got closed. - #[error("Subscription closed: {0:?}")] - SubscriptionClosed(SubscriptionClosedError), - /// Request timeout - #[error("Request timeout")] - RequestTimeout, - /// Configured max number of request slots exceeded. - #[error("Configured max number of request slots exceeded")] - MaxSlotsExceeded, - /// Attempted to stop server that is already stopped. - #[error("Attempted to stop server that is already stopped")] - AlreadyStopped, - /// List passed into `set_allowed_origins` was empty - #[error("Must set at least one allowed value for the {0} header")] - EmptyAllowList(&'static str), - /// Failed to execute a method because a resource was already at capacity - #[error("Resource at capacity: {0}")] - ResourceAtCapacity(&'static str), - /// Failed to register a resource due to a name conflict - #[error("Resource name already taken: {0}")] - ResourceNameAlreadyTaken(&'static str), - /// Failed to initialize resources for a method at startup - #[error("Resource name `{0}` not found for method `{1}`")] - ResourceNameNotFoundForMethod(&'static str, &'static str), - /// Trying to claim resources for a method execution, but the method resources have not been initialized - #[error("Method `{0}` has uninitialized resources")] - UninitializedMethod(Box), - /// Failed to register a resource due to a maximum number of resources already registered - #[error("Maximum number of resources reached")] - MaxResourcesReached, - /// Custom error. - #[error("Custom error: {0}")] - Custom(String), - /// Not implemented for HTTP clients. - #[error("Not implemented")] - HttpNotImplemented, -} - -impl Error { - /// Create `Error::CallError` from a generic error. - /// Useful if you don't care about specific JSON-RPC error code and - /// just wants to return your custom error type. - pub fn to_call_error(err: E) -> Self - where - E: std::error::Error + Send + Sync + 'static, - { - Error::Call(CallError::from_std_error(err)) - } -} - -/// Error type with a special `subscription_closed` field to detect that -/// a subscription has been closed to distinguish valid items produced -/// by the server on the subscription stream from an error. -#[derive(Deserialize, Serialize, Debug, PartialEq)] -pub struct SubscriptionClosedError { - subscription_closed: String, - id: u64, -} +#[cfg(test)] +mod tests { + use super::{ErrorCode, ErrorObject, ErrorResponse, Id, TwoPointZero}; -impl SubscriptionClosedError { - /// Create a new subscription closed error. - pub fn new(reason: impl Into, id: u64) -> Self { - Self { subscription_closed: reason.into(), id } + #[test] + fn deserialize_works() { + let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}"#; + let exp = ErrorResponse { + jsonrpc: TwoPointZero, + error: ErrorObject { code: ErrorCode::ParseError, message: "Parse error".into(), data: None }, + id: Id::Null, + }; + let err: ErrorResponse = serde_json::from_str(ser).unwrap(); + assert_eq!(exp, err); } - /// Get the reason why the subscription was closed. - pub fn close_reason(&self) -> &str { - &self.subscription_closed + #[test] + fn deserialize_with_optional_data() { + let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error", "data":"vegan"},"id":null}"#; + let data = serde_json::value::to_raw_value(&"vegan").unwrap(); + let exp = ErrorResponse { + jsonrpc: TwoPointZero, + error: ErrorObject { code: ErrorCode::ParseError, message: "Parse error".into(), data: Some(&*data) }, + id: Id::Null, + }; + let err: ErrorResponse = serde_json::from_str(ser).unwrap(); + assert_eq!(exp, err); } - /// Get the subscription ID. - pub fn subscription_id(&self) -> u64 { - self.id - } -} - -/// Generic transport error. -#[derive(Debug, thiserror::Error)] -pub enum GenericTransportError { - /// Request was too large. - #[error("The request was too big")] - TooLarge, - /// Malformed request - #[error("Malformed request")] - Malformed, - /// Concrete transport error. - #[error("Transport error: {0}")] - Inner(T), -} - -impl From for Error { - fn from(io_err: std::io::Error) -> Error { - Error::Transport(io_err.into()) - } -} + #[test] + fn deserialized_error_with_quoted_str() { + let raw = r#"{ + "error": { + "code": 1002, + "message": "desc: \"Could not decode `ChargeAssetTxPayment::asset_id`\" } })", + "data": "\\\"validate_transaction\\\"" + }, + "id": 7, + "jsonrpc": "2.0" + }"#; + let err: ErrorResponse = serde_json::from_str(raw).unwrap(); -impl From for Error { - fn from(handshake_err: soketto::handshake::Error) -> Error { - Error::Transport(handshake_err.into()) - } -} + let data = serde_json::value::to_raw_value(&"\\\"validate_transaction\\\"").unwrap(); -impl From for Error { - fn from(conn_err: soketto::connection::Error) -> Error { - Error::Transport(conn_err.into()) + assert_eq!( + err, + ErrorResponse { + error: ErrorObject { + code: 1002.into(), + message: "desc: \"Could not decode `ChargeAssetTxPayment::asset_id`\" } })".into(), + data: Some(&*data), + }, + id: Id::Number(7), + jsonrpc: TwoPointZero, + } + ); } -} -impl From for Error { - fn from(hyper_err: hyper::Error) -> Error { - Error::Transport(hyper_err.into()) + #[test] + fn serialize_works() { + let exp = r#"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":1337}"#; + let err = ErrorResponse { + jsonrpc: TwoPointZero, + error: ErrorObject { code: ErrorCode::InternalError, message: "Internal error".into(), data: None }, + id: Id::Number(1337), + }; + let ser = serde_json::to_string(&err).unwrap(); + assert_eq!(exp, ser); } } diff --git a/types/src/error_response.rs b/types/src/error_response.rs deleted file mode 100644 index 087644d517..0000000000 --- a/types/src/error_response.rs +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2019-2021 Parity Technologies (UK) Ltd. -// -// Permission is hereby granted, free of charge, to any -// person obtaining a copy of this software and associated -// documentation files (the "Software"), to deal in the -// Software without restriction, including without -// limitation the rights to use, copy, modify, merge, -// publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software -// is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice -// shall be included in all copies or substantial portions -// of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - -use std::fmt; - -use crate::params::{Id, TwoPointZero}; -use beef::Cow; -use serde::de::Deserializer; -use serde::ser::Serializer; -use serde::{Deserialize, Serialize}; -use serde_json::value::RawValue; -use thiserror::Error; - -/// [Failed JSON-RPC response object](https://www.jsonrpc.org/specification#response_object). -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct ErrorResponse<'a> { - /// JSON-RPC version. - pub jsonrpc: TwoPointZero, - /// Error. - #[serde(borrow)] - pub error: ErrorObject<'a>, - /// Request ID - pub id: Id<'a>, -} - -impl<'a> ErrorResponse<'a> { - /// Create a new `ErrorResponse`. - pub fn new(error: ErrorObject<'a>, id: Id<'a>) -> Self { - Self { jsonrpc: TwoPointZero, error, id } - } -} - -impl<'a> fmt::Display for ErrorResponse<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", serde_json::to_string(&self).expect("infallible; qed")) - } -} - -/// JSON-RPC error object. -#[derive(Debug, Deserialize, Serialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct ErrorObject<'a> { - /// Code - pub code: ErrorCode, - /// Message - #[serde(borrow)] - pub message: Cow<'a, str>, - /// Optional data - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(borrow)] - pub data: Option<&'a RawValue>, -} - -impl<'a> ErrorObject<'a> { - /// Create a new `ErrorObject` with optional data. - pub fn new(code: ErrorCode, data: Option<&'a RawValue>) -> ErrorObject<'a> { - Self { code, message: code.message().into(), data } - } -} - -impl<'a> From for ErrorObject<'a> { - fn from(code: ErrorCode) -> Self { - Self { code, message: code.message().into(), data: None } - } -} - -impl<'a> PartialEq for ErrorObject<'a> { - fn eq(&self, other: &Self) -> bool { - let this_raw = self.data.map(|r| r.get()); - let other_raw = other.data.map(|r| r.get()); - self.code == other.code && self.message == other.message && this_raw == other_raw - } -} - -/// Parse error code. -pub const PARSE_ERROR_CODE: i32 = -32700; -/// Oversized request error code. -pub const OVERSIZED_REQUEST_CODE: i32 = -32701; -/// Oversized response error code. -pub const OVERSIZED_RESPONSE_CODE: i32 = -32702; -/// Internal error code. -pub const INTERNAL_ERROR_CODE: i32 = -32603; -/// Invalid params error code. -pub const INVALID_PARAMS_CODE: i32 = -32602; -/// Invalid request error code. -pub const INVALID_REQUEST_CODE: i32 = -32600; -/// Method not found error code. -pub const METHOD_NOT_FOUND_CODE: i32 = -32601; -/// Server is busy error code. -pub const SERVER_IS_BUSY_CODE: i32 = -32604; -/// Custom server error when a call failed. -pub const CALL_EXECUTION_FAILED_CODE: i32 = -32000; -/// Unknown error. -pub const UNKNOWN_ERROR_CODE: i32 = -32001; -/// Invalid subscription error code. -pub const INVALID_SUBSCRIPTION_CODE: i32 = -32002; - -/// Parse error message -pub const PARSE_ERROR_MSG: &str = "Parse error"; -/// Oversized request message -pub const OVERSIZED_REQUEST_MSG: &str = "Request is too big"; -/// Oversized response message -pub const OVERSIZED_RESPONSE_MSG: &str = "Response is too big"; -/// Internal error message. -pub const INTERNAL_ERROR_MSG: &str = "Internal error"; -/// Invalid params error message. -pub const INVALID_PARAMS_MSG: &str = "Invalid params"; -/// Invalid request error message. -pub const INVALID_REQUEST_MSG: &str = "Invalid request"; -/// Method not found error message. -pub const METHOD_NOT_FOUND_MSG: &str = "Method not found"; -/// Server is busy error message. -pub const SERVER_IS_BUSY_MSG: &str = "Server is busy, try again later"; -/// Reserved for implementation-defined server-errors. -pub const SERVER_ERROR_MSG: &str = "Server error"; - -/// JSONRPC error code -#[derive(Error, Debug, PartialEq, Copy, Clone)] -pub enum ErrorCode { - /// Invalid JSON was received by the server. - /// An error occurred on the server while parsing the JSON text. - ParseError, - /// The request was too big. - OversizedRequest, - /// The JSON sent is not a valid Request object. - InvalidRequest, - /// The method does not exist / is not available. - MethodNotFound, - /// Server is busy / resources are at capacity. - ServerIsBusy, - /// Invalid method parameter(s). - InvalidParams, - /// Internal JSON-RPC error. - InternalError, - /// Reserved for implementation-defined server-errors. - ServerError(i32), -} - -impl ErrorCode { - /// Returns integer code value - pub const fn code(&self) -> i32 { - use ErrorCode::*; - match *self { - ParseError => PARSE_ERROR_CODE, - OversizedRequest => OVERSIZED_REQUEST_CODE, - InvalidRequest => INVALID_REQUEST_CODE, - MethodNotFound => METHOD_NOT_FOUND_CODE, - ServerIsBusy => SERVER_IS_BUSY_CODE, - InvalidParams => INVALID_PARAMS_CODE, - InternalError => INTERNAL_ERROR_CODE, - ServerError(code) => code, - } - } - - /// Returns the message for the given error code. - pub const fn message(&self) -> &'static str { - use ErrorCode::*; - match self { - ParseError => PARSE_ERROR_MSG, - OversizedRequest => OVERSIZED_REQUEST_MSG, - InvalidRequest => INVALID_REQUEST_MSG, - MethodNotFound => METHOD_NOT_FOUND_MSG, - ServerIsBusy => SERVER_IS_BUSY_MSG, - InvalidParams => INVALID_PARAMS_MSG, - InternalError => INTERNAL_ERROR_MSG, - ServerError(_) => SERVER_ERROR_MSG, - } - } -} - -impl fmt::Display for ErrorCode { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}: {}", self.code(), self.message()) - } -} - -impl From for ErrorCode { - fn from(code: i32) -> Self { - use ErrorCode::*; - match code { - PARSE_ERROR_CODE => ParseError, - OVERSIZED_REQUEST_CODE => OversizedRequest, - INVALID_REQUEST_CODE => InvalidRequest, - METHOD_NOT_FOUND_CODE => MethodNotFound, - INVALID_PARAMS_CODE => InvalidParams, - INTERNAL_ERROR_CODE => InternalError, - code => ServerError(code), - } - } -} - -impl<'a> serde::Deserialize<'a> for ErrorCode { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'a>, - { - let code: i32 = Deserialize::deserialize(deserializer)?; - Ok(ErrorCode::from(code)) - } -} - -impl serde::Serialize for ErrorCode { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_i32(self.code()) - } -} - -/// Create a invalid subscription ID error. -pub fn invalid_subscription_err(data: Option<&RawValue>) -> ErrorObject { - ErrorObject::new(ErrorCode::ServerError(INVALID_SUBSCRIPTION_CODE), data) -} - -#[cfg(test)] -mod tests { - use super::{ErrorCode, ErrorObject, ErrorResponse, Id, TwoPointZero}; - - #[test] - fn deserialize_works() { - let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}"#; - let exp = ErrorResponse { - jsonrpc: TwoPointZero, - error: ErrorObject { code: ErrorCode::ParseError, message: "Parse error".into(), data: None }, - id: Id::Null, - }; - let err: ErrorResponse = serde_json::from_str(ser).unwrap(); - assert_eq!(exp, err); - } - - #[test] - fn deserialize_with_optional_data() { - let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error", "data":"vegan"},"id":null}"#; - let data = serde_json::value::to_raw_value(&"vegan").unwrap(); - let exp = ErrorResponse { - jsonrpc: TwoPointZero, - error: ErrorObject { code: ErrorCode::ParseError, message: "Parse error".into(), data: Some(&*data) }, - id: Id::Null, - }; - let err: ErrorResponse = serde_json::from_str(ser).unwrap(); - assert_eq!(exp, err); - } - - #[test] - fn deserialized_error_with_quoted_str() { - let raw = r#"{ - "error": { - "code": 1002, - "message": "desc: \"Could not decode `ChargeAssetTxPayment::asset_id`\" } })", - "data": "\\\"validate_transaction\\\"" - }, - "id": 7, - "jsonrpc": "2.0" - }"#; - let err: ErrorResponse = serde_json::from_str(raw).unwrap(); - - let data = serde_json::value::to_raw_value(&"\\\"validate_transaction\\\"").unwrap(); - - assert_eq!( - err, - ErrorResponse { - error: ErrorObject { - code: 1002.into(), - message: "desc: \"Could not decode `ChargeAssetTxPayment::asset_id`\" } })".into(), - data: Some(&*data), - }, - id: Id::Number(7), - jsonrpc: TwoPointZero, - } - ); - } - - #[test] - fn serialize_works() { - let exp = r#"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":1337}"#; - let err = ErrorResponse { - jsonrpc: TwoPointZero, - error: ErrorObject { code: ErrorCode::InternalError, message: "Internal error".into(), data: None }, - id: Id::Number(1337), - }; - let ser = serde_json::to_string(&err).unwrap(); - assert_eq!(exp, ser); - } -} diff --git a/types/src/lib.rs b/types/src/lib.rs index d4b57b80c9..9b3d5909c6 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -34,9 +34,6 @@ extern crate alloc; /// Ten megabytes. pub const TEN_MB_SIZE_BYTES: u32 = 10 * 1024 * 1024; -/// Error type. -pub mod error; - /// JSON-RPC params related types. pub mod params; @@ -47,22 +44,11 @@ pub mod request; pub mod response; /// JSON-RPC response error object related types. -pub mod error_response; +pub mod error; // pub use async_trait::async_trait; -pub use beef::Cow; -pub use error::{CallError, Error}; +pub use error::ErrorResponse; pub use params::{Id, Params, ParamsSequence, ParamsSer, SubscriptionId, TwoPointZero}; -pub use serde::{de::DeserializeOwned, Serialize}; -pub use serde_json::{ - to_value as to_json_value, value::to_raw_value as to_json_raw_value, value::RawValue as JsonRawValue, - Value as JsonValue, -}; - -/// JSON-RPC result. -pub type RpcResult = std::result::Result; - -pub use error_response::ErrorResponse; pub use request::{InvalidRequest, Notification, NotificationSer, Request, RequestSer}; pub use response::{Response, SubscriptionPayload, SubscriptionResponse}; diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index 8398f79939..9551aba1df 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -34,7 +34,7 @@ use crate::helpers::{ use crate::manager::RequestManager; use crate::transport::{Receiver as WsReceiver, Sender as WsSender, WsHandshakeError, WsTransportClientBuilder}; use crate::types::{ - Error, ErrorResponse, Id, Notification, NotificationSer, ParamsSer, RequestSer, Response, SubscriptionResponse, + ErrorResponse, Id, Notification, NotificationSer, ParamsSer, RequestSer, Response, SubscriptionResponse, TEN_MB_SIZE_BYTES, }; use async_trait::async_trait; @@ -48,6 +48,7 @@ use jsonrpsee_core::client::{ Subscription, SubscriptionKind, SubscriptionMessage, }; use jsonrpsee_core::traits::{Client, SubscriptionClient}; +use jsonrpsee_core::Error; use serde::de::DeserializeOwned; use tokio::sync::Mutex; diff --git a/ws-client/src/helpers.rs b/ws-client/src/helpers.rs index b111a6553d..6527105130 100644 --- a/ws-client/src/helpers.rs +++ b/ws-client/src/helpers.rs @@ -30,10 +30,10 @@ use std::time::Duration; use crate::manager::{RequestManager, RequestStatus}; use crate::transport::Sender as WsSender; use crate::types::{ - Error, ErrorResponse, Id, Notification, ParamsSer, RequestSer, Response, SubscriptionId, SubscriptionResponse, + ErrorResponse, Id, Notification, ParamsSer, RequestSer, Response, SubscriptionId, SubscriptionResponse, }; use futures::channel::{mpsc, oneshot}; -use jsonrpsee_core::client::RequestMessage; +use jsonrpsee_core::{client::RequestMessage, Error}; use serde_json::Value as JsonValue; /// Attempts to process a batch response. diff --git a/ws-client/src/manager.rs b/ws-client/src/manager.rs index 48d2b146c0..337786e4d6 100644 --- a/ws-client/src/manager.rs +++ b/ws-client/src/manager.rs @@ -34,9 +34,11 @@ use std::collections::hash_map::{Entry, HashMap}; -use crate::types::{Error, JsonValue, SubscriptionId}; +use crate::types::SubscriptionId; use futures::channel::{mpsc, oneshot}; +use jsonrpsee_core::Error; use rustc_hash::FxHashMap; +use serde_json::value::Value as JsonValue; #[derive(Debug)] enum Kind { diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index 1c5d7ca69b..82cc57d8f9 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -25,13 +25,13 @@ // DEALINGS IN THE SOFTWARE. #![cfg(test)] -use crate::types::error::Error; -use crate::types::error_response::{ErrorCode, ErrorObject, ErrorResponse}; +use crate::types::error::{ErrorCode, ErrorObject, ErrorResponse}; use crate::types::ParamsSer; use crate::WsClientBuilder; use jsonrpsee_core::client::Subscription; use jsonrpsee_core::rpc_params; use jsonrpsee_core::traits::{Client, SubscriptionClient}; +use jsonrpsee_core::Error; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, WebSocketTestServer}; use jsonrpsee_test_utils::TimeoutFutureExt; diff --git a/ws-server/src/future.rs b/ws-server/src/future.rs index f13f3ab2ae..9ce47508cb 100644 --- a/ws-server/src/future.rs +++ b/ws-server/src/future.rs @@ -32,9 +32,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Weak}; use std::task::{Context, Poll}; -use crate::types::error::Error; use futures_util::future::FutureExt; use futures_util::task::AtomicWaker; +use jsonrpsee_core::Error; use tokio::time::{self, Duration, Interval}; /// Polling for server stop monitor interval in milliseconds. diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index 7f5ecc2063..e556b03019 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -30,8 +30,7 @@ use std::pin::Pin; use std::task::{Context, Poll}; use crate::future::{FutureDriver, ServerHandle, StopMonitor}; -use crate::types::error::Error; -use crate::types::error_response::ErrorCode; +use crate::types::error::ErrorCode; use crate::types::{Id, Request, TEN_MB_SIZE_BYTES}; use futures_channel::mpsc; use futures_util::future::{join_all, FutureExt}; @@ -41,6 +40,7 @@ use jsonrpsee_core::middleware::Middleware; use jsonrpsee_core::server::helpers::{collect_batch_response, prepare_error, MethodSink}; use jsonrpsee_core::server::resource_limiting::Resources; use jsonrpsee_core::server::rpc_module::{ConnectionId, MethodResult, Methods}; +use jsonrpsee_core::Error; use soketto::connection::Error as SokettoError; use soketto::handshake::{server::Response, Server as SokettoServer}; use soketto::Sender; diff --git a/ws-server/src/tests.rs b/ws-server/src/tests.rs index 3be9011994..cc2225c6b5 100644 --- a/ws-server/src/tests.rs +++ b/ws-server/src/tests.rs @@ -29,17 +29,16 @@ use std::fmt; use std::net::SocketAddr; use std::time::Duration; -use crate::types::error::{CallError, Error}; -use crate::types::DeserializeOwned; +use crate::types::error::CallError; use crate::types::{self, ErrorResponse, Response}; use crate::{future::ServerHandle, RpcModule, WsServerBuilder}; use anyhow::anyhow; use futures_util::future::join; +use jsonrpsee_core::{to_json_raw_value, DeserializeOwned, Error}; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, TestContext, WebSocketTestClient, WebSocketTestError}; use jsonrpsee_test_utils::TimeoutFutureExt; -use jsonrpsee_types::error_response::invalid_subscription_err; -use jsonrpsee_types::to_json_raw_value; +use jsonrpsee_types::error::invalid_subscription_err; use serde_json::Value as JsonValue; use tracing_subscriber::{EnvFilter, FmtSubscriber}; From 6c15874de81e1d4ab0e93d844af36b8572c2a96d Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Wed, 15 Dec 2021 16:30:30 +0000 Subject: [PATCH 17/24] Removing features to make checks pass --- core/Cargo.toml | 18 +++++++----------- core/src/server/rpc_module.rs | 1 + core/src/traits.rs | 2 ++ 3 files changed, 10 insertions(+), 11 deletions(-) diff --git a/core/Cargo.toml b/core/Cargo.toml index 2db97fecf1..a37c4268a8 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -12,35 +12,31 @@ arrayvec = "0.7.1" async-trait = "0.1" beef = { version = "0.5.1", features = ["impl_serde"] } thiserror = "1" -futures-channel = { version = "0.3.14", default-features = false, optional = true } +futures-channel = { version = "0.3.14", default-features = false } futures-util = { version = "0.3.14", default-features = false, optional = true } -hyper = { version = "0.14.10", default-features = false, features = ["stream"], optional = true } -jsonrpsee-types = { path = "../types", version = "0.6.0", optional = true } +hyper = { version = "0.14.10", default-features = false, features = ["stream"] } +jsonrpsee-types = { path = "../types", version = "0.6.0" } tracing = { version = "0.1", optional = true } rustc-hash = { version = "1", optional = true } rand = { version = "0.8", optional = true } -serde = { version = "1.0", default-features = false, features = ["derive"], optional = true } -serde_json = { version = "1", features = ["raw_value"], optional = true } +serde = { version = "1.0", default-features = false, features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } soketto = "0.7.1" parking_lot = { version = "0.11", optional = true } tokio = { version = "1.8", features = ["rt"], optional = true } [features] default = [] -http-helpers = ["hyper", "futures-util", "jsonrpsee-types"] +http-helpers = ["futures-util"] server = [ - "futures-channel", "futures-util", - "jsonrpsee-types", "rustc-hash", - "serde", - "serde_json", "tracing", "parking_lot", "rand", "tokio", ] -client = ["jsonrpsee-types"] +client = [] [dev-dependencies] serde_json = "1.0" diff --git a/core/src/server/rpc_module.rs b/core/src/server/rpc_module.rs index c78a6a7adf..c8b3a5b799 100644 --- a/core/src/server/rpc_module.rs +++ b/core/src/server/rpc_module.rs @@ -869,6 +869,7 @@ mod tests { use super::*; use jsonrpsee_types::EmptyParams; + // use jsonrpsee::core::Error; use serde::Deserialize; #[test] diff --git a/core/src/traits.rs b/core/src/traits.rs index 6f1ffe3595..481227cfc7 100644 --- a/core/src/traits.rs +++ b/core/src/traits.rs @@ -24,6 +24,7 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +#[cfg(feature = "client")] use crate::client::Subscription; use crate::Error; use async_trait::async_trait; @@ -55,6 +56,7 @@ pub trait Client { } /// [JSON-RPC](https://www.jsonrpc.org/specification) client interface that can make requests, notifications and subscriptions. +#[cfg(feature = "client")] #[async_trait] pub trait SubscriptionClient: Client { /// Initiate a subscription by performing a JSON-RPC method call where the server responds with From 7ed231644556a17334838caca30213ba216ec1e5 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 16 Dec 2021 13:24:29 +0000 Subject: [PATCH 18/24] Move rpc_module tests to tests crate --- core/src/server/resource_limiting.rs | 2 +- core/src/server/rpc_module.rs | 216 ---------------- proc-macros/src/helpers.rs | 2 +- proc-macros/src/lib.rs | 2 +- .../ui/correct/alias_doesnt_use_namespace.rs | 2 +- proc-macros/tests/ui/correct/basic.rs | 3 +- proc-macros/tests/ui/correct/only_client.rs | 2 +- proc-macros/tests/ui/correct/only_server.rs | 3 +- proc-macros/tests/ui/correct/param_kind.rs | 3 +- .../tests/ui/correct/parse_angle_brackets.rs | 2 +- .../tests/ui/correct/rpc_deny_missing_docs.rs | 2 +- .../ui/incorrect/method/method_no_name.rs | 2 +- .../method/method_unexpected_field.rs | 2 +- .../tests/ui/incorrect/rpc/rpc_assoc_items.rs | 4 +- .../ui/incorrect/rpc/rpc_conflicting_alias.rs | 2 +- .../ui/incorrect/rpc/rpc_deprecated_method.rs | 3 +- .../rpc/rpc_deprecated_method.stderr | 4 +- .../ui/incorrect/rpc/rpc_name_conflict.rs | 2 +- .../tests/ui/incorrect/rpc/rpc_no_impls.rs | 2 +- .../ui/incorrect/rpc/rpc_not_qualified.rs | 2 +- .../ui/incorrect/rpc/rpc_not_qualified.stderr | 4 +- .../ui/incorrect/sub/sub_conflicting_alias.rs | 2 +- .../ui/incorrect/sub/sub_dup_name_override.rs | 2 +- .../ui/incorrect/sub/sub_name_override.rs | 2 +- tests/Cargo.toml | 1 + tests/tests/rpc_module.rs | 238 ++++++++++++++++++ ws-server/src/server.rs | 2 +- 27 files changed, 266 insertions(+), 247 deletions(-) create mode 100644 tests/tests/rpc_module.rs diff --git a/core/src/server/resource_limiting.rs b/core/src/server/resource_limiting.rs index c36a457a2c..98e77fba8d 100644 --- a/core/src/server/resource_limiting.rs +++ b/core/src/server/resource_limiting.rs @@ -67,7 +67,7 @@ //! Alternatively, you can use the `resource` method when creating a module manually without the help of the macro: //! //! ``` -//! # use jsonrpsee::{RpcModule, types::RpcResult}; +//! # use jsonrpsee::{RpcModule, core::RpcResult}; //! # //! # fn main() -> RpcResult<()> { //! # diff --git a/core/src/server/rpc_module.rs b/core/src/server/rpc_module.rs index c8b3a5b799..79660099f9 100644 --- a/core/src/server/rpc_module.rs +++ b/core/src/server/rpc_module.rs @@ -862,219 +862,3 @@ impl Drop for Subscription { self.close(); } } - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - - use super::*; - use jsonrpsee_types::EmptyParams; - // use jsonrpsee::core::Error; - use serde::Deserialize; - - #[test] - fn rpc_modules_with_different_contexts_can_be_merged() { - let cx = Vec::::new(); - let mut mod1 = RpcModule::new(cx); - mod1.register_method("bla with Vec context", |_: Params, _| Ok(())).unwrap(); - let mut mod2 = RpcModule::new(String::new()); - mod2.register_method("bla with String context", |_: Params, _| Ok(())).unwrap(); - - mod1.merge(mod2).unwrap(); - - assert!(mod1.method("bla with Vec context").is_some()); - assert!(mod1.method("bla with String context").is_some()); - } - - #[test] - fn rpc_context_modules_can_register_subscriptions() { - let cx = (); - let mut cxmodule = RpcModule::new(cx); - let _subscription = cxmodule.register_subscription("hi", "hi", "goodbye", |_, _, _| Ok(())); - - assert!(cxmodule.method("hi").is_some()); - assert!(cxmodule.method("goodbye").is_some()); - } - - #[test] - fn rpc_register_alias() { - let mut module = RpcModule::new(()); - - module.register_method("hello_world", |_: Params, _| Ok(())).unwrap(); - module.register_alias("hello_foobar", "hello_world").unwrap(); - - assert!(module.method("hello_world").is_some()); - assert!(module.method("hello_foobar").is_some()); - } - - #[tokio::test] - async fn calling_method_without_server() { - // Call sync method with no params - let mut module = RpcModule::new(()); - module.register_method("boo", |_: Params, _| Ok(String::from("boo!"))).unwrap(); - - let res: String = module.call("boo", EmptyParams::new()).await.unwrap(); - assert_eq!(&res, "boo!"); - - // Call sync method with params - module - .register_method("foo", |params, _| { - let n: u16 = params.one()?; - Ok(n * 2) - }) - .unwrap(); - let res: u64 = module.call("foo", [3_u64]).await.unwrap(); - assert_eq!(res, 6); - - // Call sync method with bad param - let err = module.call::<_, ()>("foo", (false,)).await.unwrap_err(); - assert!( - matches!(err, Error::Request(err) if err == r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid type: boolean `false`, expected u16 at line 1 column 6"},"id":0}"#) - ); - - // Call async method with params and context - struct MyContext; - impl MyContext { - fn roo(&self, things: Vec) -> u16 { - things.iter().sum::().into() - } - } - let mut module = RpcModule::new(MyContext); - module - .register_async_method("roo", |params, ctx| { - let ns: Vec = params.parse().expect("valid params please"); - async move { Ok(ctx.roo(ns)) } - }) - .unwrap(); - let res: u64 = module.call("roo", [12, 13]).await.unwrap(); - assert_eq!(res, 25); - } - - #[tokio::test] - async fn calling_method_without_server_using_proc_macro() { - use jsonrpsee::{core::async_trait, proc_macros::rpc}; - // Setup - #[derive(Debug, Deserialize, Serialize)] - #[allow(unreachable_pub)] - pub struct Gun { - shoots: bool, - } - - #[derive(Debug, Deserialize, Serialize)] - #[allow(unreachable_pub)] - pub struct Beverage { - ice: bool, - } - - #[rpc(server)] - pub trait Cool { - /// Sync method, no params. - #[method(name = "rebel_without_cause")] - fn rebel_without_cause(&self) -> Result; - - /// Sync method. - #[method(name = "rebel")] - fn rebel(&self, gun: Gun, map: HashMap) -> Result; - - /// Async method. - #[method(name = "revolution")] - async fn can_have_any_name(&self, beverage: Beverage, some_bytes: Vec) -> Result; - } - - struct CoolServerImpl; - - #[async_trait] - impl CoolServer for CoolServerImpl { - fn rebel_without_cause(&self) -> Result { - Ok(false) - } - - fn rebel(&self, gun: Gun, map: HashMap) -> Result { - Ok(format!("{} {:?}", map.values().len(), gun)) - } - - async fn can_have_any_name(&self, beverage: Beverage, some_bytes: Vec) -> Result { - Ok(format!("drink: {:?}, phases: {:?}", beverage, some_bytes)) - } - } - let module = CoolServerImpl.into_rpc(); - - // Call sync method with no params - let res: bool = module.call("rebel_without_cause", EmptyParams::new()).await.unwrap(); - assert!(!res); - - // Call sync method with params - let res: String = module.call("rebel", (Gun { shoots: true }, HashMap::::default())).await.unwrap(); - assert_eq!(&res, "0 Gun { shoots: true }"); - - // Call sync method with bad params - let err = module.call::<_, ()>("rebel", (Gun { shoots: true }, false)).await.unwrap_err(); - assert!(matches!( - err, - Error::Request(err) if err == r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid type: boolean `false`, expected a map at line 1 column 5"},"id":0}"# - )); - - // Call async method with params and context - let result: String = module.call("revolution", (Beverage { ice: true }, vec![1, 2, 3])).await.unwrap(); - assert_eq!(&result, "drink: Beverage { ice: true }, phases: [1, 2, 3]"); - } - - #[tokio::test] - async fn subscribing_without_server() { - let mut module = RpcModule::new(()); - module - .register_subscription("my_sub", "my_sub", "my_unsub", |_, mut sink, _| { - let mut stream_data = vec!['0', '1', '2']; - std::thread::spawn(move || loop { - tracing::debug!("This is your friendly subscription sending data."); - if let Some(letter) = stream_data.pop() { - if let Err(Error::SubscriptionClosed(_)) = sink.send(&letter) { - return; - } - } else { - return; - } - std::thread::sleep(std::time::Duration::from_millis(500)); - }); - Ok(()) - }) - .unwrap(); - - let mut my_sub = module.subscribe("my_sub", EmptyParams::new()).await.unwrap(); - for i in (0..=2).rev() { - let (val, id) = my_sub.next::().await.unwrap().unwrap(); - assert_eq!(val, std::char::from_digit(i, 10).unwrap()); - assert_eq!(id, RpcSubscriptionId::Num(my_sub.subscription_id())); - } - - // The subscription is now closed by the server. - let (sub_closed_err, _) = my_sub.next::().await.unwrap().unwrap(); - assert_eq!(sub_closed_err.subscription_id(), my_sub.subscription_id()); - assert_eq!(sub_closed_err.close_reason(), "Closed by the server"); - } - - #[tokio::test] - async fn close_test_subscribing_without_server() { - let mut module = RpcModule::new(()); - module - .register_subscription("my_sub", "my_sub", "my_unsub", |_, mut sink, _| { - std::thread::spawn(move || loop { - if let Err(Error::SubscriptionClosed(_)) = sink.send(&"lo") { - return; - } - std::thread::sleep(std::time::Duration::from_millis(500)); - }); - Ok(()) - }) - .unwrap(); - - let mut my_sub = module.subscribe("my_sub", EmptyParams::new()).await.unwrap(); - let (val, id) = my_sub.next::().await.unwrap().unwrap(); - assert_eq!(&val, "lo"); - assert_eq!(id, RpcSubscriptionId::Num(my_sub.subscription_id())); - - // close the subscription to ensure it doesn't return any items. - my_sub.close(); - assert!(matches!(my_sub.next::().await, None)); - } -} diff --git a/proc-macros/src/helpers.rs b/proc-macros/src/helpers.rs index 4c6c3f4e37..2df5bb5fa8 100644 --- a/proc-macros/src/helpers.rs +++ b/proc-macros/src/helpers.rs @@ -71,7 +71,7 @@ fn find_jsonrpsee_crate(http_name: &str, ws_name: &str) -> Result { diff --git a/proc-macros/src/lib.rs b/proc-macros/src/lib.rs index 9c9a9b96ce..f56cb568cb 100644 --- a/proc-macros/src/lib.rs +++ b/proc-macros/src/lib.rs @@ -206,7 +206,7 @@ pub(crate) mod visitor; /// /// // RPC is put into a separate module to clearly show names of generated entities. /// mod rpc_impl { -/// use jsonrpsee::{proc_macros::rpc, core::async_trait, types::RpcResult, ws_server::SubscriptionSink}; +/// use jsonrpsee::{proc_macros::rpc, core::async_trait, core::RpcResult, ws_server::SubscriptionSink}; /// /// // Generate both server and client implementations, prepend all the methods with `foo_` prefix. /// #[rpc(client, server, namespace = "foo")] diff --git a/proc-macros/tests/ui/correct/alias_doesnt_use_namespace.rs b/proc-macros/tests/ui/correct/alias_doesnt_use_namespace.rs index 5ba32df63e..524697d5b0 100644 --- a/proc-macros/tests/ui/correct/alias_doesnt_use_namespace.rs +++ b/proc-macros/tests/ui/correct/alias_doesnt_use_namespace.rs @@ -1,4 +1,4 @@ -use jsonrpsee::{proc_macros::rpc, types::RpcResult}; +use jsonrpsee::{proc_macros::rpc, core::RpcResult}; #[rpc(client, server, namespace = "myapi")] pub trait Rpc { diff --git a/proc-macros/tests/ui/correct/basic.rs b/proc-macros/tests/ui/correct/basic.rs index 6dbd649fdf..2f3fb06c4a 100644 --- a/proc-macros/tests/ui/correct/basic.rs +++ b/proc-macros/tests/ui/correct/basic.rs @@ -4,8 +4,7 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; use jsonrpsee::rpc_params; -use jsonrpsee::core::{async_trait, traits::Client}; -use jsonrpsee::types::RpcResult; +use jsonrpsee::core::{async_trait, traits::Client, RpcResult}; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; diff --git a/proc-macros/tests/ui/correct/only_client.rs b/proc-macros/tests/ui/correct/only_client.rs index 23d3d1fd48..db68b7638b 100644 --- a/proc-macros/tests/ui/correct/only_client.rs +++ b/proc-macros/tests/ui/correct/only_client.rs @@ -1,6 +1,6 @@ //! Example of using proc macro to generate working client and server. -use jsonrpsee::{proc_macros::rpc, types::RpcResult}; +use jsonrpsee::{proc_macros::rpc, core::RpcResult}; #[rpc(client)] pub trait Rpc { diff --git a/proc-macros/tests/ui/correct/only_server.rs b/proc-macros/tests/ui/correct/only_server.rs index ba3d3c27b7..b82f7ddcf5 100644 --- a/proc-macros/tests/ui/correct/only_server.rs +++ b/proc-macros/tests/ui/correct/only_server.rs @@ -1,8 +1,7 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::core::async_trait; -use jsonrpsee::types::RpcResult; +use jsonrpsee::core::{async_trait, RpcResult}; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; #[rpc(server)] diff --git a/proc-macros/tests/ui/correct/param_kind.rs b/proc-macros/tests/ui/correct/param_kind.rs index 018e45b594..efd50f2fe4 100644 --- a/proc-macros/tests/ui/correct/param_kind.rs +++ b/proc-macros/tests/ui/correct/param_kind.rs @@ -1,8 +1,7 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::core::async_trait; -use jsonrpsee::types::RpcResult; +use jsonrpsee::core::{async_trait, RpcResult}; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::WsServerBuilder; diff --git a/proc-macros/tests/ui/correct/parse_angle_brackets.rs b/proc-macros/tests/ui/correct/parse_angle_brackets.rs index 037e86c155..f9e75625f2 100644 --- a/proc-macros/tests/ui/correct/parse_angle_brackets.rs +++ b/proc-macros/tests/ui/correct/parse_angle_brackets.rs @@ -1,4 +1,4 @@ -use jsonrpsee::{proc_macros::rpc, types::RpcResult}; +use jsonrpsee::{proc_macros::rpc, core::RpcResult}; fn main() { #[rpc(server)] diff --git a/proc-macros/tests/ui/correct/rpc_deny_missing_docs.rs b/proc-macros/tests/ui/correct/rpc_deny_missing_docs.rs index cbb60b44b0..9575fa9a42 100644 --- a/proc-macros/tests/ui/correct/rpc_deny_missing_docs.rs +++ b/proc-macros/tests/ui/correct/rpc_deny_missing_docs.rs @@ -3,7 +3,7 @@ #![deny(missing_docs)] use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::RpcResult; +use jsonrpsee::core::RpcResult; #[rpc(client, server)] pub trait ApiWithDocumentation { diff --git a/proc-macros/tests/ui/incorrect/method/method_no_name.rs b/proc-macros/tests/ui/incorrect/method/method_no_name.rs index 7c9f102e4c..d1aa39a3fe 100644 --- a/proc-macros/tests/ui/incorrect/method/method_no_name.rs +++ b/proc-macros/tests/ui/incorrect/method/method_no_name.rs @@ -4,7 +4,7 @@ use jsonrpsee::proc_macros::rpc; #[rpc(client, server)] pub trait NoMethodName { #[method()] - async fn async_method(&self) -> jsonrpsee::types::RpcResult; + async fn async_method(&self) -> jsonrpsee::core::RpcResult; } fn main() {} diff --git a/proc-macros/tests/ui/incorrect/method/method_unexpected_field.rs b/proc-macros/tests/ui/incorrect/method/method_unexpected_field.rs index a88a0d73bd..57349114d1 100644 --- a/proc-macros/tests/ui/incorrect/method/method_unexpected_field.rs +++ b/proc-macros/tests/ui/incorrect/method/method_unexpected_field.rs @@ -4,7 +4,7 @@ use jsonrpsee::proc_macros::rpc; #[rpc(client, server)] pub trait UnexpectedField { #[method(name = "foo", magic = false)] - async fn async_method(&self) -> jsonrpsee::types::RpcResult; + async fn async_method(&self) -> jsonrpsee::core::RpcResult; } fn main() {} diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_assoc_items.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_assoc_items.rs index 0b3ed3287e..e032a30a5a 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_assoc_items.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_assoc_items.rs @@ -6,7 +6,7 @@ pub trait AssociatedConst { const WOO: usize; #[method(name = "foo")] - async fn async_method(&self) -> jsonrpsee::types::RpcResult; + async fn async_method(&self) -> jsonrpsee::core::RpcResult; } #[rpc(client, server)] @@ -14,7 +14,7 @@ pub trait AssociatedType { type Woo; #[method(name = "foo")] - async fn async_method(&self) -> jsonrpsee::types::RpcResult; + async fn async_method(&self) -> jsonrpsee::core::RpcResult; } fn main() {} diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_conflicting_alias.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_conflicting_alias.rs index 3ba041a144..458a4bb961 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_conflicting_alias.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_conflicting_alias.rs @@ -1,5 +1,5 @@ use jsonrpsee::proc_macros::rpc; -use jsonrpsee::types::RpcResult; +use jsonrpsee::core::RpcResult; #[rpc(client, server)] pub trait DuplicatedAlias { #[method(name = "foo", aliases = ["foo_dup", "foo_dup"])] diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs index 8f006944b2..01938556d3 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.rs @@ -6,8 +6,7 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; -use jsonrpsee::core::async_trait; -use jsonrpsee::types::RpcResult; +use jsonrpsee::core::{async_trait, RpcResult}; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::WsServerBuilder; diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr index 0f80a6749a..7a3018a819 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_deprecated_method.stderr @@ -1,7 +1,7 @@ error: use of deprecated associated function `DeprecatedClient::async_method`: please use `new_method` instead - --> $DIR/rpc_deprecated_method.rs:64:20 + --> $DIR/rpc_deprecated_method.rs:63:20 | -64 | assert_eq!(client.async_method().await.unwrap(), 16); +63 | assert_eq!(client.async_method().await.unwrap(), 16); | ^^^^^^^^^^^^ | note: the lint level is defined here diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_name_conflict.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_name_conflict.rs index 0d2e696161..d3a1204caa 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_name_conflict.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_name_conflict.rs @@ -1,4 +1,4 @@ -use jsonrpsee::{proc_macros::rpc, types::RpcResult}; +use jsonrpsee::{proc_macros::rpc, core::RpcResult}; // Associated items are forbidden. #[rpc(client, server)] diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_no_impls.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_no_impls.rs index f371922ef9..d09e33eed6 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_no_impls.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_no_impls.rs @@ -4,7 +4,7 @@ use jsonrpsee::proc_macros::rpc; #[rpc()] pub trait NoImpls { #[method(name = "foo")] - async fn async_method(&self) -> jsonrpsee::types::RpcResult; + async fn async_method(&self) -> jsonrpsee::core::RpcResult; } fn main() {} diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.rs b/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.rs index a5cb32e072..84c1252614 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.rs +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.rs @@ -3,7 +3,7 @@ use jsonrpsee::proc_macros::rpc; // Method without type marker, `#[method(…)]` or `#[subscription(…)]`. #[rpc(client, server)] pub trait NotQualified { - async fn async_method(&self) -> jsonrpsee::types::RpcResult; + async fn async_method(&self) -> jsonrpsee::core::RpcResult; } fn main() {} diff --git a/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.stderr b/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.stderr index bd72dc752a..ade498d4db 100644 --- a/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.stderr +++ b/proc-macros/tests/ui/incorrect/rpc/rpc_not_qualified.stderr @@ -1,5 +1,5 @@ error: Methods must have either 'method' or 'subscription' attribute --> $DIR/rpc_not_qualified.rs:6:2 | -6 | async fn async_method(&self) -> jsonrpsee::types::RpcResult; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +6 | async fn async_method(&self) -> jsonrpsee::core::RpcResult; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/proc-macros/tests/ui/incorrect/sub/sub_conflicting_alias.rs b/proc-macros/tests/ui/incorrect/sub/sub_conflicting_alias.rs index 993063c51a..8301534c18 100644 --- a/proc-macros/tests/ui/incorrect/sub/sub_conflicting_alias.rs +++ b/proc-macros/tests/ui/incorrect/sub/sub_conflicting_alias.rs @@ -1,4 +1,4 @@ -use jsonrpsee::{proc_macros::rpc, types::RpcResult}; +use jsonrpsee::{proc_macros::rpc, core::RpcResult}; #[rpc(client, server)] pub trait DuplicatedSubAlias { diff --git a/proc-macros/tests/ui/incorrect/sub/sub_dup_name_override.rs b/proc-macros/tests/ui/incorrect/sub/sub_dup_name_override.rs index 53adf3fe2e..9a04dda824 100644 --- a/proc-macros/tests/ui/incorrect/sub/sub_dup_name_override.rs +++ b/proc-macros/tests/ui/incorrect/sub/sub_dup_name_override.rs @@ -1,4 +1,4 @@ -use jsonrpsee::{proc_macros::rpc, types::RpcResult}; +use jsonrpsee::{proc_macros::rpc, core::RpcResult}; // Subscription method must not use the same override name. #[rpc(client, server)] diff --git a/proc-macros/tests/ui/incorrect/sub/sub_name_override.rs b/proc-macros/tests/ui/incorrect/sub/sub_name_override.rs index 740b30699f..8f53d28302 100644 --- a/proc-macros/tests/ui/incorrect/sub/sub_name_override.rs +++ b/proc-macros/tests/ui/incorrect/sub/sub_name_override.rs @@ -1,4 +1,4 @@ -use jsonrpsee::{proc_macros::rpc, types::RpcResult}; +use jsonrpsee::{proc_macros::rpc, core::RpcResult}; // Subscription method name conflict with notif override. #[rpc(client, server)] diff --git a/tests/Cargo.toml b/tests/Cargo.toml index b293fe52e9..9daa5653e2 100644 --- a/tests/Cargo.toml +++ b/tests/Cargo.toml @@ -14,4 +14,5 @@ futures = { version = "0.3.14", default-features = false, features = ["std"] } jsonrpsee = { path = "../jsonrpsee", features = ["full"] } tokio = { version = "1.8", features = ["full"] } tracing = "0.1" +serde = "1" serde_json = "1" diff --git a/tests/tests/rpc_module.rs b/tests/tests/rpc_module.rs new file mode 100644 index 0000000000..5a46297ba4 --- /dev/null +++ b/tests/tests/rpc_module.rs @@ -0,0 +1,238 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// +// Permission is hereby granted, free of charge, to any +// person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the +// Software without restriction, including without +// limitation the rights to use, copy, modify, merge, +// publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software +// is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice +// shall be included in all copies or substantial portions +// of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +use std::collections::HashMap; + +use jsonrpsee::core::error::{Error, SubscriptionClosedError}; +use jsonrpsee::core::server::rpc_module::*; +use jsonrpsee::types::{EmptyParams, Params, SubscriptionId as RpcSubscriptionId}; +use serde::{Deserialize, Serialize}; + +#[test] +fn rpc_modules_with_different_contexts_can_be_merged() { + let cx = Vec::::new(); + let mut mod1 = RpcModule::new(cx); + mod1.register_method("bla with Vec context", |_: Params, _| Ok(())).unwrap(); + let mut mod2 = RpcModule::new(String::new()); + mod2.register_method("bla with String context", |_: Params, _| Ok(())).unwrap(); + + mod1.merge(mod2).unwrap(); + + assert!(mod1.method("bla with Vec context").is_some()); + assert!(mod1.method("bla with String context").is_some()); +} + +#[test] +fn rpc_context_modules_can_register_subscriptions() { + let cx = (); + let mut cxmodule = RpcModule::new(cx); + let _subscription = cxmodule.register_subscription("hi", "hi", "goodbye", |_, _, _| Ok(())); + + assert!(cxmodule.method("hi").is_some()); + assert!(cxmodule.method("goodbye").is_some()); +} + +#[test] +fn rpc_register_alias() { + let mut module = RpcModule::new(()); + + module.register_method("hello_world", |_: Params, _| Ok(())).unwrap(); + module.register_alias("hello_foobar", "hello_world").unwrap(); + + assert!(module.method("hello_world").is_some()); + assert!(module.method("hello_foobar").is_some()); +} + +#[tokio::test] +async fn calling_method_without_server() { + // Call sync method with no params + let mut module = RpcModule::new(()); + module.register_method("boo", |_: Params, _| Ok(String::from("boo!"))).unwrap(); + + let res: String = module.call("boo", EmptyParams::new()).await.unwrap(); + assert_eq!(&res, "boo!"); + + // Call sync method with params + module + .register_method("foo", |params, _| { + let n: u16 = params.one()?; + Ok(n * 2) + }) + .unwrap(); + let res: u64 = module.call("foo", [3_u64]).await.unwrap(); + assert_eq!(res, 6); + + // Call sync method with bad param + let err = module.call::<_, ()>("foo", (false,)).await.unwrap_err(); + assert!( + matches!(err, Error::Request(err) if err == r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid type: boolean `false`, expected u16 at line 1 column 6"},"id":0}"#) + ); + + // Call async method with params and context + struct MyContext; + impl MyContext { + fn roo(&self, things: Vec) -> u16 { + things.iter().sum::().into() + } + } + let mut module = RpcModule::new(MyContext); + module + .register_async_method("roo", |params, ctx| { + let ns: Vec = params.parse().expect("valid params please"); + async move { Ok(ctx.roo(ns)) } + }) + .unwrap(); + let res: u64 = module.call("roo", [12, 13]).await.unwrap(); + assert_eq!(res, 25); +} + +#[tokio::test] +async fn calling_method_without_server_using_proc_macro() { + use jsonrpsee::{core::async_trait, proc_macros::rpc}; + // Setup + #[derive(Debug, Deserialize, Serialize)] + #[allow(unreachable_pub)] + pub struct Gun { + shoots: bool, + } + + #[derive(Debug, Deserialize, Serialize)] + #[allow(unreachable_pub)] + pub struct Beverage { + ice: bool, + } + + #[rpc(server)] + pub trait Cool { + /// Sync method, no params. + #[method(name = "rebel_without_cause")] + fn rebel_without_cause(&self) -> Result; + + /// Sync method. + #[method(name = "rebel")] + fn rebel(&self, gun: Gun, map: HashMap) -> Result; + + /// Async method. + #[method(name = "revolution")] + async fn can_have_any_name(&self, beverage: Beverage, some_bytes: Vec) -> Result; + } + + struct CoolServerImpl; + + #[async_trait] + impl CoolServer for CoolServerImpl { + fn rebel_without_cause(&self) -> Result { + Ok(false) + } + + fn rebel(&self, gun: Gun, map: HashMap) -> Result { + Ok(format!("{} {:?}", map.values().len(), gun)) + } + + async fn can_have_any_name(&self, beverage: Beverage, some_bytes: Vec) -> Result { + Ok(format!("drink: {:?}, phases: {:?}", beverage, some_bytes)) + } + } + let module = CoolServerImpl.into_rpc(); + + // Call sync method with no params + let res: bool = module.call("rebel_without_cause", EmptyParams::new()).await.unwrap(); + assert!(!res); + + // Call sync method with params + let res: String = module.call("rebel", (Gun { shoots: true }, HashMap::::default())).await.unwrap(); + assert_eq!(&res, "0 Gun { shoots: true }"); + + // Call sync method with bad params + let err = module.call::<_, ()>("rebel", (Gun { shoots: true }, false)).await.unwrap_err(); + assert!(matches!( + err, + Error::Request(err) if err == r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid type: boolean `false`, expected a map at line 1 column 5"},"id":0}"# + )); + + // Call async method with params and context + let result: String = module.call("revolution", (Beverage { ice: true }, vec![1, 2, 3])).await.unwrap(); + assert_eq!(&result, "drink: Beverage { ice: true }, phases: [1, 2, 3]"); +} + +#[tokio::test] +async fn subscribing_without_server() { + let mut module = RpcModule::new(()); + module + .register_subscription("my_sub", "my_sub", "my_unsub", |_, mut sink, _| { + let mut stream_data = vec!['0', '1', '2']; + std::thread::spawn(move || loop { + tracing::debug!("This is your friendly subscription sending data."); + if let Some(letter) = stream_data.pop() { + if let Err(Error::SubscriptionClosed(_)) = sink.send(&letter) { + return; + } + } else { + return; + } + std::thread::sleep(std::time::Duration::from_millis(500)); + }); + Ok(()) + }) + .unwrap(); + + let mut my_sub = module.subscribe("my_sub", EmptyParams::new()).await.unwrap(); + for i in (0..=2).rev() { + let (val, id) = my_sub.next::().await.unwrap().unwrap(); + assert_eq!(val, std::char::from_digit(i, 10).unwrap()); + assert_eq!(id, RpcSubscriptionId::Num(my_sub.subscription_id())); + } + + // The subscription is now closed by the server. + let (sub_closed_err, _) = my_sub.next::().await.unwrap().unwrap(); + assert_eq!(sub_closed_err.subscription_id(), my_sub.subscription_id()); + assert_eq!(sub_closed_err.close_reason(), "Closed by the server"); +} + +#[tokio::test] +async fn close_test_subscribing_without_server() { + let mut module = RpcModule::new(()); + module + .register_subscription("my_sub", "my_sub", "my_unsub", |_, mut sink, _| { + std::thread::spawn(move || loop { + if let Err(Error::SubscriptionClosed(_)) = sink.send(&"lo") { + return; + } + std::thread::sleep(std::time::Duration::from_millis(500)); + }); + Ok(()) + }) + .unwrap(); + + let mut my_sub = module.subscribe("my_sub", EmptyParams::new()).await.unwrap(); + let (val, id) = my_sub.next::().await.unwrap().unwrap(); + assert_eq!(&val, "lo"); + assert_eq!(id, RpcSubscriptionId::Num(my_sub.subscription_id())); + + // close the subscription to ensure it doesn't return any items. + my_sub.close(); + assert!(matches!(my_sub.next::().await, None)); +} diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index e556b03019..95b01969dd 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -21,7 +21,7 @@ // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -// IN background_task WITH THE SOFTWARE OR THE USE OR OTHER +// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. use std::future::Future; From dc4ab0282dfedb0cbe1c3814e0bb45c01a43225d Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 16 Dec 2021 14:52:47 +0000 Subject: [PATCH 19/24] Fixed doc comment links --- http-server/src/server.rs | 2 +- ws-client/src/client.rs | 2 +- ws-server/src/server.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/http-server/src/server.rs b/http-server/src/server.rs index c159e592b0..5e51f06c37 100644 --- a/http-server/src/server.rs +++ b/http-server/src/server.rs @@ -80,7 +80,7 @@ impl Builder { } impl Builder { - /// Add a middleware to the builder [`Middleware`](../jsonrpsee_types/middleware/trait.Middleware.html). + /// Add a middleware to the builder [`Middleware`](../jsonrpsee_core/middleware/trait.Middleware.html). /// /// ``` /// use std::time::Instant; diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index 9551aba1df..f709b621f8 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -193,7 +193,7 @@ impl<'a> WsClientBuilder<'a> { /// will be dropped. /// /// You can also prevent the subscription being dropped by calling - /// [`Subscription::next()`](crate::types::Subscription) frequently enough such that the buffer capacity doesn't + /// [`Subscription::next()`](../../jsonrpsee_core/client/struct.Subscription.html#method.next) frequently enough such that the buffer capacity doesn't /// exceeds. /// /// **Note**: The actual capacity is `num_senders + max_subscription_capacity` diff --git a/ws-server/src/server.rs b/ws-server/src/server.rs index 95b01969dd..8adaef98fc 100644 --- a/ws-server/src/server.rs +++ b/ws-server/src/server.rs @@ -571,7 +571,7 @@ impl Builder { Ok(self) } - /// Add a middleware to the builder [`Middleware`](../jsonrpsee_types/middleware/trait.Middleware.html). + /// Add a middleware to the builder [`Middleware`](../jsonrpsee_core/middleware/trait.Middleware.html). /// /// ``` /// use std::time::Instant; From 394a3c2f3db42a3cc6df8482aa1c29bb41c45d98 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 16 Dec 2021 15:26:50 +0000 Subject: [PATCH 20/24] Add futures-util dependency for client --- core/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/Cargo.toml b/core/Cargo.toml index a37c4268a8..77fd26206f 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -36,7 +36,7 @@ server = [ "rand", "tokio", ] -client = [] +client = ["futures-util"] [dev-dependencies] serde_json = "1.0" From c38ec7608aece7bed0befd1ea267ef0739167bbc Mon Sep 17 00:00:00 2001 From: Maciej Hirsz <1096222+maciejhirsz@users.noreply.github.com> Date: Thu, 16 Dec 2021 16:34:54 +0100 Subject: [PATCH 21/24] Remove dead code Co-authored-by: Niklas Adolfsson --- core/src/server/mod.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/src/server/mod.rs b/core/src/server/mod.rs index f7493ece6f..7d988501ed 100644 --- a/core/src/server/mod.rs +++ b/core/src/server/mod.rs @@ -26,8 +26,6 @@ //! Shared modules for the JSON-RPC servers. -/// Client types. -// mod client; /// Helpers. pub mod helpers; From e93c2d9958a2f45bd1538e75f3088afbe1a5911d Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Thu, 16 Dec 2021 15:46:58 +0000 Subject: [PATCH 22/24] fmt --- core/src/server/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/core/src/server/mod.rs b/core/src/server/mod.rs index 7d988501ed..fe1a99277b 100644 --- a/core/src/server/mod.rs +++ b/core/src/server/mod.rs @@ -26,7 +26,6 @@ //! Shared modules for the JSON-RPC servers. - /// Helpers. pub mod helpers; /// Resource limiting. Create generic "resources" and configure their limits to ensure servers are not overloaded. From 51eec241dfb062cdeefece15d30223b329d47c7a Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Fri, 17 Dec 2021 14:23:59 +0000 Subject: [PATCH 23/24] Feature gate the Client trait --- core/src/traits.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core/src/traits.rs b/core/src/traits.rs index 481227cfc7..5283018210 100644 --- a/core/src/traits.rs +++ b/core/src/traits.rs @@ -26,14 +26,19 @@ #[cfg(feature = "client")] use crate::client::Subscription; +#[cfg(feature = "client")] use crate::Error; +#[cfg(feature = "client")] use async_trait::async_trait; +#[cfg(feature = "client")] use jsonrpsee_types::ParamsSer; +#[cfg(feature = "client")] use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::value::RawValue; /// [JSON-RPC](https://www.jsonrpc.org/specification) client interface that can make requests and notifications. +#[cfg(feature = "client")] #[async_trait] pub trait Client { /// Send a [notification request](https://www.jsonrpc.org/specification#notification) From 9a88c70933a2bc408495b41880d24acd3c819c44 Mon Sep 17 00:00:00 2001 From: Maciej Hirsz Date: Fri, 17 Dec 2021 14:44:50 +0000 Subject: [PATCH 24/24] Move `Client` traits to `client` module --- benches/bench.rs | 2 +- core/src/client.rs | 58 ++++++++++++++++++++++- core/src/traits.rs | 67 --------------------------- examples/http.rs | 2 +- examples/middleware_http.rs | 2 +- examples/middleware_ws.rs | 2 +- examples/multi_middleware.rs | 2 +- examples/ws.rs | 2 +- examples/ws_sub_with_params.rs | 2 +- examples/ws_subscription.rs | 3 +- http-client/src/client.rs | 3 +- http-client/src/tests.rs | 2 +- proc-macros/src/render_client.rs | 4 +- proc-macros/tests/ui/correct/basic.rs | 2 +- tests/tests/integration_tests.rs | 3 +- tests/tests/middleware.rs | 2 +- tests/tests/resource_limiting.rs | 2 +- ws-client/src/client.rs | 5 +- ws-client/src/tests.rs | 2 +- 19 files changed, 76 insertions(+), 91 deletions(-) diff --git a/benches/bench.rs b/benches/bench.rs index 2588a682ff..dc4617531d 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use criterion::*; use futures_util::future::join_all; use helpers::{SUB_METHOD_NAME, UNSUB_METHOD_NAME}; -use jsonrpsee::core::traits::{Client, SubscriptionClient}; +use jsonrpsee::core::client::{Client, SubscriptionClient}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::types::{Id, ParamsSer, RequestSer}; use jsonrpsee::ws_client::WsClientBuilder; diff --git a/core/src/client.rs b/core/src/client.rs index fde202bcf9..268bdac18a 100644 --- a/core/src/client.rs +++ b/core/src/client.rs @@ -31,12 +31,13 @@ use std::sync::Arc; use std::task; use crate::error::{Error, SubscriptionClosed}; +use async_trait::async_trait; use core::marker::PhantomData; use futures_channel::{mpsc, oneshot}; use futures_util::future::FutureExt; use futures_util::sink::SinkExt; use futures_util::stream::{Stream, StreamExt}; -use jsonrpsee_types::SubscriptionId; +use jsonrpsee_types::{ParamsSer, SubscriptionId}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value as JsonValue; @@ -46,6 +47,61 @@ pub mod __reexports { pub use jsonrpsee_types::ParamsSer; } +/// [JSON-RPC](https://www.jsonrpc.org/specification) client interface that can make requests and notifications. +#[async_trait] +pub trait Client { + /// Send a [notification request](https://www.jsonrpc.org/specification#notification) + async fn notification<'a>(&self, method: &'a str, params: Option>) -> Result<(), Error>; + + /// Send a [method call request](https://www.jsonrpc.org/specification#request_object). + async fn request<'a, R>(&self, method: &'a str, params: Option>) -> Result + where + R: DeserializeOwned; + + /// Send a [batch request](https://www.jsonrpc.org/specification#batch). + /// + /// The response to batch are returned in the same order as it was inserted in the batch. + /// + /// Returns `Ok` if all requests in the batch were answered successfully. + /// Returns `Error` if any of the requests in batch fails. + async fn batch_request<'a, R>(&self, batch: Vec<(&'a str, Option>)>) -> Result, Error> + where + R: DeserializeOwned + Default + Clone; +} + +/// [JSON-RPC](https://www.jsonrpc.org/specification) client interface that can make requests, notifications and subscriptions. +#[async_trait] +pub trait SubscriptionClient: Client { + /// Initiate a subscription by performing a JSON-RPC method call where the server responds with + /// a `Subscription ID` that is used to fetch messages on that subscription, + /// + /// The `subscribe_method` and `params` are used to ask for the subscription towards the + /// server. + /// + /// The params may be used as input for the subscription for the server to process. + /// + /// The `unsubscribe_method` is used to close the subscription + /// + /// The `Notif` param is a generic type to receive generic subscriptions, see [`Subscription`] for further + /// documentation. + async fn subscribe<'a, Notif>( + &self, + subscribe_method: &'a str, + params: Option>, + unsubscribe_method: &'a str, + ) -> Result, Error> + where + Notif: DeserializeOwned; + + /// Register a method subscription, this is used to filter only server notifications that a user is interested in. + /// + /// The `Notif` param is a generic type to receive generic subscriptions, see [`Subscription`] for further + /// documentation. + async fn subscribe_to_method<'a, Notif>(&self, method: &'a str) -> Result, Error> + where + Notif: DeserializeOwned; +} + #[macro_export] /// Convert the given values to a [`jsonrpsee_types::ParamsSer`] as expected by a jsonrpsee Client (http or websocket). macro_rules! rpc_params { diff --git a/core/src/traits.rs b/core/src/traits.rs index 5283018210..3bb03cb9d6 100644 --- a/core/src/traits.rs +++ b/core/src/traits.rs @@ -24,76 +24,9 @@ // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -#[cfg(feature = "client")] -use crate::client::Subscription; -#[cfg(feature = "client")] -use crate::Error; -#[cfg(feature = "client")] -use async_trait::async_trait; -#[cfg(feature = "client")] -use jsonrpsee_types::ParamsSer; -#[cfg(feature = "client")] -use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::value::RawValue; -/// [JSON-RPC](https://www.jsonrpc.org/specification) client interface that can make requests and notifications. -#[cfg(feature = "client")] -#[async_trait] -pub trait Client { - /// Send a [notification request](https://www.jsonrpc.org/specification#notification) - async fn notification<'a>(&self, method: &'a str, params: Option>) -> Result<(), Error>; - - /// Send a [method call request](https://www.jsonrpc.org/specification#request_object). - async fn request<'a, R>(&self, method: &'a str, params: Option>) -> Result - where - R: DeserializeOwned; - - /// Send a [batch request](https://www.jsonrpc.org/specification#batch). - /// - /// The response to batch are returned in the same order as it was inserted in the batch. - /// - /// Returns `Ok` if all requests in the batch were answered successfully. - /// Returns `Error` if any of the requests in batch fails. - async fn batch_request<'a, R>(&self, batch: Vec<(&'a str, Option>)>) -> Result, Error> - where - R: DeserializeOwned + Default + Clone; -} - -/// [JSON-RPC](https://www.jsonrpc.org/specification) client interface that can make requests, notifications and subscriptions. -#[cfg(feature = "client")] -#[async_trait] -pub trait SubscriptionClient: Client { - /// Initiate a subscription by performing a JSON-RPC method call where the server responds with - /// a `Subscription ID` that is used to fetch messages on that subscription, - /// - /// The `subscribe_method` and `params` are used to ask for the subscription towards the - /// server. - /// - /// The params may be used as input for the subscription for the server to process. - /// - /// The `unsubscribe_method` is used to close the subscription - /// - /// The `Notif` param is a generic type to receive generic subscriptions, see [`Subscription`] for further - /// documentation. - async fn subscribe<'a, Notif>( - &self, - subscribe_method: &'a str, - params: Option>, - unsubscribe_method: &'a str, - ) -> Result, Error> - where - Notif: DeserializeOwned; - - /// Register a method subscription, this is used to filter only server notifications that a user is interested in. - /// - /// The `Notif` param is a generic type to receive generic subscriptions, see [`Subscription`] for further - /// documentation. - async fn subscribe_to_method<'a, Notif>(&self, method: &'a str) -> Result, Error> - where - Notif: DeserializeOwned; -} - /// Marker trait for types that can be serialized as JSON array/sequence. /// /// If your type isn't a sequence, for example `String`, `usize` or similar diff --git a/examples/http.rs b/examples/http.rs index 5d3e9eb17f..c2dc66603d 100644 --- a/examples/http.rs +++ b/examples/http.rs @@ -26,7 +26,7 @@ use std::net::SocketAddr; -use jsonrpsee::core::traits::Client; +use jsonrpsee::core::client::Client; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; use jsonrpsee::rpc_params; diff --git a/examples/middleware_http.rs b/examples/middleware_http.rs index 5c90fcd4c4..124c7612e0 100644 --- a/examples/middleware_http.rs +++ b/examples/middleware_http.rs @@ -27,7 +27,7 @@ use std::net::SocketAddr; use std::time::Instant; -use jsonrpsee::core::{middleware, traits::Client}; +use jsonrpsee::core::{client::Client, middleware}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle, RpcModule}; diff --git a/examples/middleware_ws.rs b/examples/middleware_ws.rs index 5b12da410d..aac3556453 100644 --- a/examples/middleware_ws.rs +++ b/examples/middleware_ws.rs @@ -27,7 +27,7 @@ use std::net::SocketAddr; use std::time::Instant; -use jsonrpsee::core::{middleware, traits::Client}; +use jsonrpsee::core::{client::Client, middleware}; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/multi_middleware.rs b/examples/multi_middleware.rs index dc894da40b..6b411115e5 100644 --- a/examples/multi_middleware.rs +++ b/examples/multi_middleware.rs @@ -30,7 +30,7 @@ use std::net::SocketAddr; use std::process::Command; use std::time::Instant; -use jsonrpsee::core::{middleware, traits::Client}; +use jsonrpsee::core::{client::Client, middleware}; use jsonrpsee::rpc_params; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/ws.rs b/examples/ws.rs index 2f0ef69859..a6a5032173 100644 --- a/examples/ws.rs +++ b/examples/ws.rs @@ -26,7 +26,7 @@ use std::net::SocketAddr; -use jsonrpsee::core::traits::Client; +use jsonrpsee::core::client::Client; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/ws_sub_with_params.rs b/examples/ws_sub_with_params.rs index ebd90e51cc..90b65129a2 100644 --- a/examples/ws_sub_with_params.rs +++ b/examples/ws_sub_with_params.rs @@ -26,7 +26,7 @@ use std::net::SocketAddr; -use jsonrpsee::core::traits::SubscriptionClient; +use jsonrpsee::core::client::SubscriptionClient; use jsonrpsee::rpc_params; use jsonrpsee::ws_client::WsClientBuilder; use jsonrpsee::ws_server::{RpcModule, WsServerBuilder}; diff --git a/examples/ws_subscription.rs b/examples/ws_subscription.rs index 5e8ce32004..1ce239c2ef 100644 --- a/examples/ws_subscription.rs +++ b/examples/ws_subscription.rs @@ -26,8 +26,7 @@ use std::net::SocketAddr; -use jsonrpsee::core::client::Subscription; -use jsonrpsee::core::traits::SubscriptionClient; +use jsonrpsee::core::client::{Subscription, SubscriptionClient}; use jsonrpsee::core::Error; use jsonrpsee::rpc_params; use jsonrpsee::ws_client::WsClientBuilder; diff --git a/http-client/src/client.rs b/http-client/src/client.rs index 637a7d2c4a..364c7fb616 100644 --- a/http-client/src/client.rs +++ b/http-client/src/client.rs @@ -30,8 +30,7 @@ use std::time::Duration; use crate::transport::HttpTransportClient; use crate::types::{ErrorResponse, Id, NotificationSer, ParamsSer, RequestSer, Response, TEN_MB_SIZE_BYTES}; use async_trait::async_trait; -use jsonrpsee_core::client::{CertificateStore, RequestIdManager, Subscription}; -use jsonrpsee_core::traits::{Client, SubscriptionClient}; +use jsonrpsee_core::client::{CertificateStore, Client, RequestIdManager, Subscription, SubscriptionClient}; use jsonrpsee_core::Error; use rustc_hash::FxHashMap; use serde::de::DeserializeOwned; diff --git a/http-client/src/tests.rs b/http-client/src/tests.rs index 417ab06324..c14fabea1a 100644 --- a/http-client/src/tests.rs +++ b/http-client/src/tests.rs @@ -27,8 +27,8 @@ use crate::types::error::{ErrorCode, ErrorObject, ErrorResponse}; use crate::types::ParamsSer; use crate::HttpClientBuilder; +use jsonrpsee_core::client::Client; use jsonrpsee_core::rpc_params; -use jsonrpsee_core::traits::Client; use jsonrpsee_core::Error; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::Id; diff --git a/proc-macros/src/render_client.rs b/proc-macros/src/render_client.rs index 1258887f4d..6ba94cedd9 100644 --- a/proc-macros/src/render_client.rs +++ b/proc-macros/src/render_client.rs @@ -41,9 +41,9 @@ impl RpcDescription { let (impl_generics, type_generics, _) = self.trait_def.generics.split_for_impl(); let super_trait = if self.subscriptions.is_empty() { - quote! { #jsonrpsee::core::traits::Client } + quote! { #jsonrpsee::core::client::Client } } else { - quote! { #jsonrpsee::core::traits::SubscriptionClient } + quote! { #jsonrpsee::core::client::SubscriptionClient } }; let method_impls = diff --git a/proc-macros/tests/ui/correct/basic.rs b/proc-macros/tests/ui/correct/basic.rs index 2f3fb06c4a..f97095ae3f 100644 --- a/proc-macros/tests/ui/correct/basic.rs +++ b/proc-macros/tests/ui/correct/basic.rs @@ -4,7 +4,7 @@ use std::net::SocketAddr; use jsonrpsee::proc_macros::rpc; use jsonrpsee::rpc_params; -use jsonrpsee::core::{async_trait, traits::Client, RpcResult}; +use jsonrpsee::core::{async_trait, client::Client, RpcResult}; use jsonrpsee::ws_client::*; use jsonrpsee::ws_server::{SubscriptionSink, WsServerBuilder}; diff --git a/tests/tests/integration_tests.rs b/tests/tests/integration_tests.rs index 508722bb65..50b964214d 100644 --- a/tests/tests/integration_tests.rs +++ b/tests/tests/integration_tests.rs @@ -31,9 +31,8 @@ use std::sync::Arc; use std::time::Duration; use helpers::{http_server, websocket_server, websocket_server_with_subscription}; -use jsonrpsee::core::client::Subscription; +use jsonrpsee::core::client::{Client, Subscription, SubscriptionClient}; use jsonrpsee::core::error::SubscriptionClosedReason; -use jsonrpsee::core::traits::{Client, SubscriptionClient}; use jsonrpsee::core::{Error, JsonValue}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::rpc_params; diff --git a/tests/tests/middleware.rs b/tests/tests/middleware.rs index d02fc21576..28fee2fbde 100644 --- a/tests/tests/middleware.rs +++ b/tests/tests/middleware.rs @@ -29,7 +29,7 @@ use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use std::time::Duration; -use jsonrpsee::core::{middleware::Middleware, traits::Client, Error}; +use jsonrpsee::core::{client::Client, middleware::Middleware, Error}; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; use jsonrpsee::proc_macros::rpc; diff --git a/tests/tests/resource_limiting.rs b/tests/tests/resource_limiting.rs index f0616f3367..f0d0837a7c 100644 --- a/tests/tests/resource_limiting.rs +++ b/tests/tests/resource_limiting.rs @@ -27,7 +27,7 @@ use std::net::SocketAddr; use std::time::Duration; -use jsonrpsee::core::traits::Client; +use jsonrpsee::core::client::Client; use jsonrpsee::core::Error; use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle}; diff --git a/ws-client/src/client.rs b/ws-client/src/client.rs index f709b621f8..778f859ec2 100644 --- a/ws-client/src/client.rs +++ b/ws-client/src/client.rs @@ -44,10 +44,9 @@ use futures::prelude::*; use futures::sink::SinkExt; use http::uri::{InvalidUri, Uri}; use jsonrpsee_core::client::{ - BatchMessage, CertificateStore, FrontToBack, RegisterNotificationMessage, RequestIdManager, RequestMessage, - Subscription, SubscriptionKind, SubscriptionMessage, + BatchMessage, CertificateStore, Client, FrontToBack, RegisterNotificationMessage, RequestIdManager, RequestMessage, + Subscription, SubscriptionClient, SubscriptionKind, SubscriptionMessage, }; -use jsonrpsee_core::traits::{Client, SubscriptionClient}; use jsonrpsee_core::Error; use serde::de::DeserializeOwned; use tokio::sync::Mutex; diff --git a/ws-client/src/tests.rs b/ws-client/src/tests.rs index 82cc57d8f9..a8f7b7bec5 100644 --- a/ws-client/src/tests.rs +++ b/ws-client/src/tests.rs @@ -29,8 +29,8 @@ use crate::types::error::{ErrorCode, ErrorObject, ErrorResponse}; use crate::types::ParamsSer; use crate::WsClientBuilder; use jsonrpsee_core::client::Subscription; +use jsonrpsee_core::client::{Client, SubscriptionClient}; use jsonrpsee_core::rpc_params; -use jsonrpsee_core::traits::{Client, SubscriptionClient}; use jsonrpsee_core::Error; use jsonrpsee_test_utils::helpers::*; use jsonrpsee_test_utils::mocks::{Id, WebSocketTestServer};