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

types: make jsonrpc field optional #1385

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
10 changes: 2 additions & 8 deletions client/http-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use std::borrow::Cow as StdCow;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
Expand All @@ -41,7 +40,7 @@ use jsonrpsee_core::client::{
use jsonrpsee_core::params::BatchRequestBuilder;
use jsonrpsee_core::traits::ToRpcParams;
use jsonrpsee_core::{BoxError, JsonRawValue, TEN_MB_SIZE_BYTES};
use jsonrpsee_types::{ErrorObject, InvalidRequestId, ResponseSuccess, TwoPointZero};
use jsonrpsee_types::{ErrorObject, InvalidRequestId, ResponseSuccess};
use serde::de::DeserializeOwned;
use tower::layer::util::Identity;
use tower::{Layer, Service};
Expand Down Expand Up @@ -385,12 +384,7 @@ where
let mut batch_request = Vec::with_capacity(batch.len());
for ((method, params), id) in batch.into_iter().zip(id_range.clone()) {
let id = self.id_manager.as_id_kind().into_id(id);
batch_request.push(RequestSer {
jsonrpc: TwoPointZero,
id,
method: method.into(),
params: params.map(StdCow::Owned),
});
batch_request.push(RequestSer::owned(id, method, params));
}

let fut = self.transport.send_and_read_body(serde_json::to_string(&batch_request).map_err(Error::ParseError)?);
Expand Down
10 changes: 2 additions & 8 deletions core/src/client/async_client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,13 @@ use crate::params::{BatchRequestBuilder, EmptyBatchRequest};
use crate::tracing::client::{rx_log_from_json, tx_log_from_str};
use crate::traits::ToRpcParams;
use crate::JsonRawValue;
use std::borrow::Cow as StdCow;

use core::time::Duration;
use helpers::{
build_unsubscribe_message, call_with_timeout, process_batch_response, process_notification,
process_single_response, process_subscription_response, stop_subscription,
};
use jsonrpsee_types::{InvalidRequestId, ResponseSuccess, TwoPointZero};
use jsonrpsee_types::{InvalidRequestId, ResponseSuccess};
use manager::RequestManager;
use std::sync::Arc;

Expand Down Expand Up @@ -545,12 +544,7 @@ impl ClientT for Client {
let mut batches = Vec::with_capacity(batch.len());
for ((method, params), id) in batch.into_iter().zip(id_range.clone()) {
let id = self.id_manager.as_id_kind().into_id(id);
batches.push(RequestSer {
jsonrpc: TwoPointZero,
id,
method: method.into(),
params: params.map(StdCow::Owned),
});
batches.push(RequestSer::owned(id, method, params));
}

let (send_back_tx, send_back_rx) = oneshot::channel();
Expand Down
2 changes: 1 addition & 1 deletion server/src/tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ async fn invalid_request_object() {
let (addr, _handle) = server().with_default_timeout().await.unwrap();
let uri = to_http_uri(addr);

let req = r#"{"method":"bar","id":1}"#;
let req = r#"{"nethod":"bar","id":1}"#;
let response = http_request(req.into(), uri).with_default_timeout().await.unwrap().unwrap();
assert_eq!(response.status, StatusCode::OK);
assert_eq!(response.body, invalid_request(Id::Num(1)));
Expand Down
4 changes: 2 additions & 2 deletions server/src/tests/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ async fn invalid_request_object() {
let addr = server().await;
let mut client = WebSocketTestClient::new(addr).with_default_timeout().await.unwrap().unwrap();

let req = r#"{"method":"bar","id":1}"#;
let req = r#"{"nethod":"bar","id":1}"#;
let response = client.send_request_text(req).with_default_timeout().await.unwrap().unwrap();
assert_eq!(response, invalid_request(Id::Num(1)));
}
Expand Down Expand Up @@ -465,7 +465,7 @@ async fn invalid_request_should_not_close_connection() {
let addr = server().await;
let mut client = WebSocketTestClient::new(addr).with_default_timeout().await.unwrap().unwrap();

let req = r#"{"method":"bar","id":1}"#;
let req = r#"{"nethod":"bar","id":1}"#;
let response = client.send_request_text(req).with_default_timeout().await.unwrap().unwrap();
assert_eq!(response, invalid_request(Id::Num(1)));
let request = r#"{"jsonrpc":"2.0","method":"say_hello","id":33}"#;
Expand Down
92 changes: 61 additions & 31 deletions types/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use serde_json::value::RawValue;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Request<'a> {
/// JSON-RPC version.
pub jsonrpc: TwoPointZero,
pub jsonrpc: Option<TwoPointZero>,
/// Request ID
#[serde(borrow)]
pub id: Id<'a>,
Expand All @@ -60,7 +60,13 @@ pub struct Request<'a> {
impl<'a> Request<'a> {
/// Create a new [`Request`].
pub fn new(method: Cow<'a, str>, params: Option<&'a RawValue>, id: Id<'a>) -> Self {
Self { jsonrpc: TwoPointZero, id, method, params: params.map(StdCow::Borrowed), extensions: Extensions::new() }
Self {
jsonrpc: Some(TwoPointZero),
id,
method,
params: params.map(StdCow::Borrowed),
extensions: Extensions::new(),
}
}

/// Get the ID of the request.
Expand Down Expand Up @@ -102,7 +108,7 @@ pub struct InvalidRequest<'a> {
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Notification<'a, T> {
/// JSON-RPC version.
pub jsonrpc: TwoPointZero,
pub jsonrpc: Option<TwoPointZero>,
/// Name of the method to be invoked.
#[serde(borrow)]
pub method: Cow<'a, str>,
Expand All @@ -113,30 +119,30 @@ pub struct Notification<'a, T> {
impl<'a, T> Notification<'a, T> {
/// Create a new [`Notification`].
pub fn new(method: Cow<'a, str>, params: T) -> Self {
Self { jsonrpc: TwoPointZero, method, params }
Self { jsonrpc: Some(TwoPointZero), method, params }
}
}

/// Serializable [JSON-RPC object](https://www.jsonrpc.org/specification#request-object).
#[derive(Serialize, Debug, Clone)]
pub struct RequestSer<'a> {
/// JSON-RPC version.
pub jsonrpc: TwoPointZero,
jsonrpc: Option<TwoPointZero>,
/// Request ID
pub id: Id<'a>,
id: Id<'a>,
/// Name of the method to be invoked.
// NOTE: as this type only implements serialize `#[serde(borrow)]` is not needed.
pub method: Cow<'a, str>,
method: Cow<'a, str>,
/// Parameter values of the request.
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<StdCow<'a, RawValue>>,
params: Option<StdCow<'a, RawValue>>,
}

impl<'a> RequestSer<'a> {
/// Create a borrowed serializable JSON-RPC method call.
pub fn borrowed(id: &'a Id<'a>, method: &'a impl AsRef<str>, params: Option<&'a RawValue>) -> Self {
Self {
jsonrpc: TwoPointZero,
jsonrpc: Some(TwoPointZero),
id: id.clone(),
method: method.as_ref().into(),
params: params.map(StdCow::Borrowed),
Expand All @@ -145,32 +151,32 @@ impl<'a> RequestSer<'a> {

/// Create a owned serializable JSON-RPC method call.
pub fn owned(id: Id<'a>, method: impl Into<String>, params: Option<Box<RawValue>>) -> Self {
Self { jsonrpc: TwoPointZero, id, method: method.into().into(), params: params.map(StdCow::Owned) }
Self { jsonrpc: Some(TwoPointZero), id, method: method.into().into(), params: params.map(StdCow::Owned) }
}
}

/// Serializable [JSON-RPC notification object](https://www.jsonrpc.org/specification#request-object).
#[derive(Serialize, Debug, Clone)]
pub struct NotificationSer<'a> {
/// JSON-RPC version.
pub jsonrpc: TwoPointZero,
jsonrpc: Option<TwoPointZero>,
/// Name of the method to be invoked.
// NOTE: as this type only implements serialize `#[serde(borrow)]` is not needed.
pub method: Cow<'a, str>,
method: Cow<'a, str>,
/// Parameter values of the request.
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<StdCow<'a, RawValue>>,
params: Option<StdCow<'a, RawValue>>,
}

impl<'a> NotificationSer<'a> {
/// Create a borrowed serializable JSON-RPC notification.
pub fn borrowed(method: &'a impl AsRef<str>, params: Option<&'a RawValue>) -> Self {
Self { jsonrpc: TwoPointZero, method: method.as_ref().into(), params: params.map(StdCow::Borrowed) }
Self { jsonrpc: Some(TwoPointZero), method: method.as_ref().into(), params: params.map(StdCow::Borrowed) }
}

/// Create an owned serializable JSON-RPC notification.
pub fn owned(method: impl Into<String>, params: Option<Box<RawValue>>) -> Self {
Self { jsonrpc: TwoPointZero, method: method.into().into(), params: params.map(StdCow::Owned) }
Self { jsonrpc: Some(TwoPointZero), method: method.into().into(), params: params.map(StdCow::Owned) }
}
}

Expand All @@ -179,8 +185,14 @@ mod test {
use super::{Id, InvalidRequest, Notification, NotificationSer, Request, RequestSer, StdCow, TwoPointZero};
use serde_json::value::RawValue;

fn assert_request<'a>(request: Request<'a>, id: Id<'a>, method: &str, params: Option<&str>) {
assert_eq!(request.jsonrpc, TwoPointZero);
fn assert_request<'a>(
request: Request<'a>,
id: Id<'a>,
method: &str,
params: Option<&str>,
version: Option<TwoPointZero>,
) {
assert_eq!(request.jsonrpc, version);
assert_eq!(request.id, id);
assert_eq!(request.method, method);
assert_eq!(request.params.as_ref().map(|p| RawValue::get(p)), params);
Expand All @@ -199,40 +211,51 @@ mod test {
Id::Number(1),
Some(params),
method,
Some(TwoPointZero),
),
// Without params field
(r#"{"jsonrpc":"2.0", "method":"subtract", "id":null}"#, Id::Null, None, method),
(r#"{"jsonrpc":"2.0", "method":"subtract", "id":null}"#, Id::Null, None, method, Some(TwoPointZero)),
// Escaped method name.
(r#"{"jsonrpc":"2.0", "method":"\"m", "id":null}"#, Id::Null, None, "\"m"),
(r#"{"jsonrpc":"2.0", "method":"\"m", "id":null}"#, Id::Null, None, "\"m", Some(TwoPointZero)),
// Without jsonrpc field
(r#"{"method":"m", "id":null}"#, Id::Null, None, "m", None),
];

for (ser, id, params, method) in test_vector.into_iter() {
for (ser, id, params, method, version) in test_vector.into_iter() {
let request = serde_json::from_str(ser).unwrap();
assert_request(request, id, method, params);
assert_request(request, id, method, params, version);
}
}

#[test]
fn deserialize_call_escaped_method_name() {
let ser = r#"{"jsonrpc":"2.0","id":1,"method":"\"m\""}"#;
let req: Request = serde_json::from_str(ser).unwrap();
assert_request(req, Id::Number(1), "\"m\"", None);
assert_request(req, Id::Number(1), "\"m\"", None, Some(TwoPointZero));
}

#[test]
fn deserialize_valid_notif_works() {
let ser = r#"{"jsonrpc":"2.0","method":"say_hello","params":[]}"#;
let dsr: Notification<&RawValue> = serde_json::from_str(ser).unwrap();
assert_eq!(dsr.method, "say_hello");
assert_eq!(dsr.jsonrpc, TwoPointZero);
assert_eq!(dsr.jsonrpc, Some(TwoPointZero));
}

#[test]
fn deserialize_notif_without_version() {
let ser = r#"{"method":"say_hello","params":[]}"#;
let dsr: Notification<&RawValue> = serde_json::from_str(ser).unwrap();
assert_eq!(dsr.method, "say_hello");
assert_eq!(dsr.jsonrpc, None);
}

#[test]
fn deserialize_valid_notif_escaped_method() {
let ser = r#"{"jsonrpc":"2.0","method":"\"m\"","params":[]}"#;
let dsr: Notification<&RawValue> = serde_json::from_str(ser).unwrap();
assert_eq!(dsr.method, "\"m\"");
assert_eq!(dsr.jsonrpc, TwoPointZero);
assert_eq!(dsr.jsonrpc, Some(TwoPointZero));
}

#[test]
Expand All @@ -255,27 +278,34 @@ mod test {
let id = Id::Number(1); // It's enough to check one variant, since the type itself also has tests.
let params = Some(RawValue::from_string("[42,23]".into()).unwrap());

let test_vector: &[(&'static str, Option<_>, Option<_>, &'static str)] = &[
let test_vector: &[(&'static str, Option<_>, Option<_>, &'static str, Option<TwoPointZero>)] = &[
// With all fields set.
(
r#"{"jsonrpc":"2.0","id":1,"method":"subtract","params":[42,23]}"#,
Some(id.clone()),
params.clone(),
method,
Some(TwoPointZero),
),
// Escaped method name.
(r#"{"jsonrpc":"2.0","id":1,"method":"\"m"}"#, Some(id.clone()), None, "\"m"),
(r#"{"jsonrpc":"2.0","id":1,"method":"\"m"}"#, Some(id.clone()), None, "\"m", Some(TwoPointZero)),
// Without ID field.
(r#"{"jsonrpc":"2.0","id":null,"method":"subtract","params":[42,23]}"#, None, params, method),
(
r#"{"jsonrpc":"2.0","id":null,"method":"subtract","params":[42,23]}"#,
None,
params,
method,
Some(TwoPointZero),
),
// Without params field
(r#"{"jsonrpc":"2.0","id":1,"method":"subtract"}"#, Some(id), None, method),
(r#"{"jsonrpc":"2.0","id":1,"method":"subtract"}"#, Some(id), None, method, Some(TwoPointZero)),
// Without params and ID.
(r#"{"jsonrpc":"2.0","id":null,"method":"subtract"}"#, None, None, method),
(r#"{"jsonrpc":"2.0","id":null,"method":"subtract"}"#, None, None, method, Some(TwoPointZero)),
Copy link
Collaborator

@jsdw jsdw May 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the idea of giving the version too so that you'd add a test which didn't have the "jsonrpc" field? :)

niklasad1 marked this conversation as resolved.
Show resolved Hide resolved
];

for (ser, id, params, method) in test_vector.iter().cloned() {
for (ser, id, params, method, version) in test_vector.iter().cloned() {
let request = serde_json::to_string(&RequestSer {
jsonrpc: TwoPointZero,
jsonrpc: version,
method: method.into(),
id: id.unwrap_or(Id::Null),
params: params.map(StdCow::Owned),
Expand Down
Loading