Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename and reorg types #462

Merged
merged 10 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 15 additions & 18 deletions benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use jsonrpsee::{
types::traits::SubscriptionClient,
types::{
traits::Client,
v2::params::{Id, JsonRpcParams},
v2::request::JsonRpcCallSer,
v2::params::{Id, ParamsSer},
v2::request::RequestSer,
},
ws_client::WsClientBuilder,
};
Expand Down Expand Up @@ -55,24 +55,24 @@ impl RequestType {
}
}

fn v2_serialize(req: JsonRpcCallSer<'_>) -> String {
fn v2_serialize(req: RequestSer<'_>) -> String {
serde_json::to_string(&req).unwrap()
}

pub fn jsonrpsee_types_v2(crit: &mut Criterion) {
crit.bench_function("jsonrpsee_types_v2_array_ref", |b| {
b.iter(|| {
let params = &[1_u64.into(), 2_u32.into()];
let params = JsonRpcParams::ArrayRef(params);
let request = JsonRpcCallSer::new(Id::Number(0), "say_hello", params);
let params = ParamsSer::ArrayRef(params);
let request = RequestSer::new(Id::Number(0), "say_hello", params);
v2_serialize(request);
})
});

crit.bench_function("jsonrpsee_types_v2_vec", |b| {
b.iter(|| {
let params = JsonRpcParams::Array(vec![1_u64.into(), 2_u32.into()]);
let request = JsonRpcCallSer::new(Id::Number(0), "say_hello", params);
let params = ParamsSer::Array(vec![1_u64.into(), 2_u32.into()]);
let request = RequestSer::new(Id::Number(0), "say_hello", params);
v2_serialize(request);
})
});
Expand Down Expand Up @@ -138,7 +138,7 @@ impl RequestBencher for AsyncBencher {
fn run_round_trip(rt: &TokioRuntime, crit: &mut Criterion, client: Arc<impl Client>, name: &str, request: RequestType) {
crit.bench_function(&request.group_name(name), |b| {
b.to_async(rt).iter(|| async {
black_box(client.request::<String>(request.method_name(), JsonRpcParams::NoParams).await.unwrap());
black_box(client.request::<String>(request.method_name(), ParamsSer::NoParams).await.unwrap());
})
});
}
Expand All @@ -148,7 +148,7 @@ fn run_sub_round_trip(rt: &TokioRuntime, crit: &mut Criterion, client: Arc<impl
group.bench_function("subscribe", |b| {
b.to_async(rt).iter_with_large_drop(|| async {
black_box(
client.subscribe::<String>(SUB_METHOD_NAME, JsonRpcParams::NoParams, UNSUB_METHOD_NAME).await.unwrap(),
client.subscribe::<String>(SUB_METHOD_NAME, ParamsSer::NoParams, UNSUB_METHOD_NAME).await.unwrap(),
);
})
});
Expand All @@ -160,7 +160,7 @@ fn run_sub_round_trip(rt: &TokioRuntime, crit: &mut Criterion, client: Arc<impl
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(async {
client
.subscribe::<String>(SUB_METHOD_NAME, JsonRpcParams::NoParams, UNSUB_METHOD_NAME)
.subscribe::<String>(SUB_METHOD_NAME, ParamsSer::NoParams, UNSUB_METHOD_NAME)
.await
.unwrap()
})
Expand All @@ -179,10 +179,7 @@ fn run_sub_round_trip(rt: &TokioRuntime, crit: &mut Criterion, client: Arc<impl
b.iter_with_setup(
|| {
rt.block_on(async {
client
.subscribe::<String>(SUB_METHOD_NAME, JsonRpcParams::NoParams, UNSUB_METHOD_NAME)
.await
.unwrap()
client.subscribe::<String>(SUB_METHOD_NAME, ParamsSer::NoParams, UNSUB_METHOD_NAME).await.unwrap()
})
},
|sub| {
Expand All @@ -205,7 +202,7 @@ fn run_round_trip_with_batch(
) {
let mut group = crit.benchmark_group(request.group_name(name));
for batch_size in [2, 5, 10, 50, 100usize].iter() {
let batch = vec![(request.method_name(), JsonRpcParams::NoParams); *batch_size];
let batch = vec![(request.method_name(), ParamsSer::NoParams); *batch_size];
group.throughput(Throughput::Elements(*batch_size as u64));
group.bench_with_input(BenchmarkId::from_parameter(batch_size), batch_size, |b, _| {
b.to_async(rt).iter(|| async { client.batch_request::<String>(batch.clone()).await.unwrap() })
Expand All @@ -230,7 +227,7 @@ fn run_concurrent_round_trip<C: 'static + Client + Send + Sync>(
let tasks = clients.map(|client| {
rt.spawn(async move {
let _ = black_box(
client.request::<String>(request.method_name(), JsonRpcParams::NoParams).await.unwrap(),
client.request::<String>(request.method_name(), ParamsSer::NoParams).await.unwrap(),
);
})
});
Expand Down Expand Up @@ -265,7 +262,7 @@ fn run_ws_concurrent_connections(rt: &TokioRuntime, crit: &mut Criterion, url: &
let tasks = clients.into_iter().map(|client| {
rt.spawn(async move {
let _ = black_box(
client.request::<String>(request.method_name(), JsonRpcParams::NoParams).await.unwrap(),
client.request::<String>(request.method_name(), ParamsSer::NoParams).await.unwrap(),
);
})
});
Expand Down Expand Up @@ -293,7 +290,7 @@ fn run_http_concurrent_connections(
let tasks = clients.map(|client| {
rt.spawn(async move {
let _ = black_box(
client.request::<String>(request.method_name(), JsonRpcParams::NoParams).await.unwrap(),
client.request::<String>(request.method_name(), ParamsSer::NoParams).await.unwrap(),
);
})
});
Expand Down
4 changes: 2 additions & 2 deletions examples/weather.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
//! mutation.

use jsonrpsee::{
types::{traits::SubscriptionClient, v2::params::JsonRpcParams},
types::{traits::SubscriptionClient, v2::params::ParamsSer},
ws_client::WsClientBuilder,
ws_server::RpcModule,
ws_server::WsServerBuilder,
Expand Down Expand Up @@ -83,7 +83,7 @@ async fn main() -> anyhow::Result<()> {
let client = WsClientBuilder::default().build(&url).await?;

// Subscription to the London weather
let params = JsonRpcParams::Array(vec!["London,uk".into(), "metric".into()]);
let params = ParamsSer::Array(vec!["London,uk".into(), "metric".into()]);
let mut weather_sub = client.subscribe::<Weather>("weather_sub", params, "weather_unsub").await?;
while let Ok(Some(w)) = weather_sub.next().await {
println!("[client] London weather: {:?}", w);
Expand Down
4 changes: 2 additions & 2 deletions examples/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
// DEALINGS IN THE SOFTWARE.

use jsonrpsee::{
types::{traits::Client, v2::params::JsonRpcParams},
types::{traits::Client, v2::params::ParamsSer},
ws_client::WsClientBuilder,
ws_server::{RpcModule, WsServerBuilder},
};
Expand All @@ -38,7 +38,7 @@ async fn main() -> anyhow::Result<()> {
let url = format!("ws://{}", addr);

let client = WsClientBuilder::default().build(&url).await?;
let response: String = client.request("say_hello", JsonRpcParams::NoParams).await?;
let response: String = client.request("say_hello", ParamsSer::NoParams).await?;
println!("r: {:?}", response);

Ok(())
Expand Down
6 changes: 3 additions & 3 deletions examples/ws_sub_with_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
// DEALINGS IN THE SOFTWARE.

use jsonrpsee::{
types::{traits::SubscriptionClient, v2::params::JsonRpcParams},
types::{traits::SubscriptionClient, v2::params::ParamsSer},
ws_client::WsClientBuilder,
ws_server::{RpcModule, WsServerBuilder},
};
Expand All @@ -40,12 +40,12 @@ async fn main() -> anyhow::Result<()> {
let client = WsClientBuilder::default().build(&url).await?;

// Subscription with a single parameter
let params = JsonRpcParams::Array(vec![3.into()]);
let params = ParamsSer::Array(vec![3.into()]);
let mut sub_params_one = client.subscribe::<Option<char>>("sub_one_param", params, "unsub_one_param").await?;
println!("subscription with one param: {:?}", sub_params_one.next().await);

// Subscription with multiple parameters
let params = JsonRpcParams::Array(vec![2.into(), 5.into()]);
let params = ParamsSer::Array(vec![2.into(), 5.into()]);
let mut sub_params_two = client.subscribe::<String>("sub_params_two", params, "unsub_params_two").await?;
println!("subscription with two params: {:?}", sub_params_two.next().await);

Expand Down
4 changes: 2 additions & 2 deletions examples/ws_subscription.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
// DEALINGS IN THE SOFTWARE.

use jsonrpsee::{
types::{traits::SubscriptionClient, v2::params::JsonRpcParams, Error, Subscription},
types::{traits::SubscriptionClient, v2::params::ParamsSer, Error, Subscription},
ws_client::WsClientBuilder,
ws_server::{RpcModule, WsServerBuilder},
};
Expand All @@ -41,7 +41,7 @@ async fn main() -> anyhow::Result<()> {

let client = WsClientBuilder::default().build(&url).await?;
let mut subscribe_hello: Subscription<String> =
client.subscribe("subscribe_hello", JsonRpcParams::NoParams, "unsubscribe_hello").await?;
client.subscribe("subscribe_hello", ParamsSer::NoParams, "unsubscribe_hello").await?;

let mut i = 0;
while i <= NUM_SUBSCRIPTION_RESPONSES {
Expand Down
28 changes: 14 additions & 14 deletions http-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ use crate::transport::HttpTransportClient;
use crate::types::{
traits::Client,
v2::{
error::JsonRpcError,
params::{Id, JsonRpcParams},
request::{JsonRpcCallSer, JsonRpcNotificationSer},
response::JsonRpcResponse,
error::RpcError,
params::{Id, ParamsSer},
request::{NotificationSer, RequestSer},
response::Response,
},
Error, TEN_MB_SIZE_BYTES,
};
Expand Down Expand Up @@ -88,8 +88,8 @@ pub struct HttpClient {

#[async_trait]
impl Client for HttpClient {
async fn notification<'a>(&self, method: &'a str, params: JsonRpcParams<'a>) -> Result<(), Error> {
let notif = JsonRpcNotificationSer::new(method, params);
async fn notification<'a>(&self, method: &'a str, params: ParamsSer<'a>) -> Result<(), Error> {
let notif = NotificationSer::new(method, params);
let fut = self.transport.send(serde_json::to_string(&notif).map_err(Error::ParseError)?);
match tokio::time::timeout(self.request_timeout, fut).await {
Ok(Ok(ok)) => Ok(ok),
Expand All @@ -99,13 +99,13 @@ impl Client for HttpClient {
}

/// Perform a request towards the server.
async fn request<'a, R>(&self, method: &'a str, params: JsonRpcParams<'a>) -> Result<R, Error>
async fn request<'a, R>(&self, method: &'a str, params: ParamsSer<'a>) -> Result<R, Error>
where
R: DeserializeOwned,
{
// NOTE: `fetch_add` wraps on overflow which is intended.
let id = self.request_id.fetch_add(1, Ordering::SeqCst);
let request = JsonRpcCallSer::new(Id::Number(id), method, params);
let request = RequestSer::new(Id::Number(id), method, params);

let fut = self.transport.send_and_read_body(serde_json::to_string(&request).map_err(Error::ParseError)?);
let body = match tokio::time::timeout(self.request_timeout, fut).await {
Expand All @@ -114,10 +114,10 @@ impl Client for HttpClient {
Ok(Err(e)) => return Err(Error::Transport(e.into())),
};

let response: JsonRpcResponse<_> = match serde_json::from_slice(&body) {
let response: Response<_> = match serde_json::from_slice(&body) {
Ok(response) => response,
Err(_) => {
let err: JsonRpcError = serde_json::from_slice(&body).map_err(Error::ParseError)?;
let err: RpcError = serde_json::from_slice(&body).map_err(Error::ParseError)?;
return Err(Error::Request(err.to_string()));
}
};
Expand All @@ -131,7 +131,7 @@ impl Client for HttpClient {
}
}

async fn batch_request<'a, R>(&self, batch: Vec<(&'a str, JsonRpcParams<'a>)>) -> Result<Vec<R>, Error>
async fn batch_request<'a, R>(&self, batch: Vec<(&'a str, ParamsSer<'a>)>) -> Result<Vec<R>, Error>
where
R: DeserializeOwned + Default + Clone,
{
Expand All @@ -142,7 +142,7 @@ impl Client for HttpClient {

for (pos, (method, params)) in batch.into_iter().enumerate() {
let id = self.request_id.fetch_add(1, Ordering::SeqCst);
batch_request.push(JsonRpcCallSer::new(Id::Number(id), method, params));
batch_request.push(RequestSer::new(Id::Number(id), method, params));
ordered_requests.push(id);
request_set.insert(id, pos);
}
Expand All @@ -155,10 +155,10 @@ impl Client for HttpClient {
Ok(Err(e)) => return Err(Error::Transport(e.into())),
};

let rps: Vec<JsonRpcResponse<_>> = match serde_json::from_slice(&body) {
let rps: Vec<Response<_>> = match serde_json::from_slice(&body) {
Ok(response) => response,
Err(_) => {
let err: JsonRpcError = serde_json::from_slice(&body).map_err(Error::ParseError)?;
let err: RpcError = serde_json::from_slice(&body).map_err(Error::ParseError)?;
return Err(Error::Request(err.to_string()));
}
};
Expand Down
36 changes: 18 additions & 18 deletions http-client/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
use crate::types::{
traits::Client,
v2::{
error::{JsonRpcError, JsonRpcErrorCode, JsonRpcErrorObject},
params::JsonRpcParams,
error::{ErrorCode, ErrorObject, RpcError},
params::ParamsSer,
},
Error, JsonValue,
};
Expand All @@ -53,7 +53,7 @@ async fn notification_works() {
let uri = format!("http://{}", server_addr);
let client = HttpClientBuilder::default().build(&uri).unwrap();
client
.notification("i_dont_care_about_the_response_because_the_server_should_not_respond", JsonRpcParams::NoParams)
.notification("i_dont_care_about_the_response_because_the_server_should_not_respond", ParamsSer::NoParams)
.with_default_timeout()
.await
.unwrap()
Expand All @@ -74,34 +74,34 @@ async fn response_with_wrong_id() {
async fn response_method_not_found() {
let err =
run_request_with_response(method_not_found(Id::Num(0))).with_default_timeout().await.unwrap().unwrap_err();
assert_jsonrpc_error_response(err, JsonRpcErrorCode::MethodNotFound.into());
assert_jsonrpc_error_response(err, ErrorCode::MethodNotFound.into());
}

#[tokio::test]
async fn response_parse_error() {
let err = run_request_with_response(parse_error(Id::Num(0))).with_default_timeout().await.unwrap().unwrap_err();
assert_jsonrpc_error_response(err, JsonRpcErrorCode::ParseError.into());
assert_jsonrpc_error_response(err, ErrorCode::ParseError.into());
}

#[tokio::test]
async fn invalid_request_works() {
let err =
run_request_with_response(invalid_request(Id::Num(0_u64))).with_default_timeout().await.unwrap().unwrap_err();
assert_jsonrpc_error_response(err, JsonRpcErrorCode::InvalidRequest.into());
assert_jsonrpc_error_response(err, ErrorCode::InvalidRequest.into());
}

#[tokio::test]
async fn invalid_params_works() {
let err =
run_request_with_response(invalid_params(Id::Num(0_u64))).with_default_timeout().await.unwrap().unwrap_err();
assert_jsonrpc_error_response(err, JsonRpcErrorCode::InvalidParams.into());
assert_jsonrpc_error_response(err, ErrorCode::InvalidParams.into());
}

#[tokio::test]
async fn internal_error_works() {
let err =
run_request_with_response(internal_error(Id::Num(0_u64))).with_default_timeout().await.unwrap().unwrap_err();
assert_jsonrpc_error_response(err, JsonRpcErrorCode::InternalError.into());
assert_jsonrpc_error_response(err, ErrorCode::InternalError.into());
}

#[tokio::test]
Expand All @@ -114,9 +114,9 @@ async fn subscription_response_to_request() {
#[tokio::test]
async fn batch_request_works() {
let batch_request = vec![
("say_hello", JsonRpcParams::NoParams),
("say_goodbye", JsonRpcParams::Array(vec![0_u64.into(), 1.into(), 2.into()])),
("get_swag", JsonRpcParams::NoParams),
("say_hello", ParamsSer::NoParams),
("say_goodbye", ParamsSer::Array(vec![0_u64.into(), 1.into(), 2.into()])),
("get_swag", ParamsSer::NoParams),
];
let server_response = r#"[{"jsonrpc":"2.0","result":"hello","id":0}, {"jsonrpc":"2.0","result":"goodbye","id":1}, {"jsonrpc":"2.0","result":"here's your swag","id":2}]"#.to_string();
let response =
Expand All @@ -127,9 +127,9 @@ async fn batch_request_works() {
#[tokio::test]
async fn batch_request_out_of_order_response() {
let batch_request = vec![
("say_hello", JsonRpcParams::NoParams),
("say_goodbye", JsonRpcParams::Array(vec![0_u64.into(), 1.into(), 2.into()])),
("get_swag", JsonRpcParams::NoParams),
("say_hello", ParamsSer::NoParams),
("say_goodbye", ParamsSer::Array(vec![0_u64.into(), 1.into(), 2.into()])),
("get_swag", ParamsSer::NoParams),
];
let server_response = r#"[{"jsonrpc":"2.0","result":"here's your swag","id":2}, {"jsonrpc":"2.0","result":"hello","id":0}, {"jsonrpc":"2.0","result":"goodbye","id":1}]"#.to_string();
let response =
Expand All @@ -138,7 +138,7 @@ async fn batch_request_out_of_order_response() {
}

async fn run_batch_request_with_response<'a>(
batch: Vec<(&'a str, JsonRpcParams<'a>)>,
batch: Vec<(&'a str, ParamsSer<'a>)>,
response: String,
) -> Result<Vec<String>, Error> {
let server_addr = http_server_with_hardcoded_response(response).with_default_timeout().await.unwrap();
Expand All @@ -151,13 +151,13 @@ async fn run_request_with_response(response: String) -> Result<JsonValue, Error>
let server_addr = http_server_with_hardcoded_response(response).with_default_timeout().await.unwrap();
let uri = format!("http://{}", server_addr);
let client = HttpClientBuilder::default().build(&uri).unwrap();
client.request("say_hello", JsonRpcParams::NoParams).with_default_timeout().await.unwrap()
client.request("say_hello", ParamsSer::NoParams).with_default_timeout().await.unwrap()
}

fn assert_jsonrpc_error_response(err: Error, exp: JsonRpcErrorObject) {
fn assert_jsonrpc_error_response(err: Error, exp: ErrorObject) {
match &err {
Error::Request(e) => {
let this: JsonRpcError = serde_json::from_str(e).unwrap();
let this: RpcError = serde_json::from_str(e).unwrap();
assert_eq!(this.error, exp);
}
e => panic!("Expected error: \"{}\", got: {:?}", err, e),
Expand Down
Loading