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

Omit params field from requests instead of sending null value #640

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions core/src/types/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ impl Params {
p => Err(Error::invalid_params_with_details("No parameters were expected", p)),
}
}

/// Check for None
pub fn is_none(&self) -> bool {
matches!(*self, Params::None)
}
}

impl From<Params> for Value {
Expand Down Expand Up @@ -110,4 +115,12 @@ mod tests {
let params: (u64,) = Params::Array(vec![Value::from(1)]).parse().unwrap();
assert_eq!(params, (1,));
}

#[test]
fn detect_none() {
let none = Params::None;
assert!(none.is_none());
let some = Params::Array(vec![]);
assert!(!some.is_none());
}
}
17 changes: 16 additions & 1 deletion core/src/types/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct MethodCall {
pub method: String,
/// A Structured value that holds the parameter values to be used
/// during the invocation of the method. This member MAY be omitted.
#[serde(default = "default_params")]
#[serde(default = "default_params", skip_serializing_if = "Params::is_none")]
pub params: Params,
/// An identifier established by the Client that MUST contain a String,
/// Number, or NULL value if included. If it is not included it is assumed
Expand Down Expand Up @@ -105,6 +105,21 @@ mod tests {
);
}

#[test]
fn call_serialize_without_params() {
use serde_json;

let m = MethodCall {
jsonrpc: Some(Version::V2),
method: "status".to_owned(),
params: Params::None,
id: Id::Num(1),
};

let serialized = serde_json::to_string(&m).unwrap();
assert_eq!(serialized, r#"{"jsonrpc":"2.0","method":"status","id":1}"#);
}

#[test]
fn notification_serialize() {
use serde_json;
Expand Down
52 changes: 52 additions & 0 deletions derive/tests/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ pub trait Rpc {
#[rpc(name = "raw", params = "raw")]
fn raw(&self, params: Params) -> Result<String>;

/// Squares a number, default value is 1.
#[rpc(name = "sqr")]
fn sqr(&self, a: Option<u64>) -> Result<u64>;

/// Handles a notification.
#[rpc(name = "notify")]
fn notify(&self, a: u64);
Expand All @@ -55,6 +59,11 @@ impl Rpc for RpcImpl {
Ok("OK".into())
}

fn sqr(&self, a: Option<u64>) -> Result<u64> {
let a = a.unwrap_or(1);
Ok(a * a)
}

fn notify(&self, a: u64) {
println!("Received `notify` with value: {}", a);
}
Expand Down Expand Up @@ -222,6 +231,49 @@ fn should_accept_any_raw_params() {
assert_eq!(expected, result4);
}

#[test]
fn should_accept_optional_param() {
let mut io = IoHandler::new();
let rpc = RpcImpl::default();
io.extend_with(rpc.to_delegate());

// when
let req1 = r#"{"jsonrpc":"2.0","id":1,"method":"sqr","params":[2]}"#;
Copy link
Member

@niklasad1 niklasad1 Oct 6, 2021

Choose a reason for hiding this comment

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

I would like to add requests with "params":[] and "params":null here otherwise looks great

Copy link
Author

Choose a reason for hiding this comment

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

Added those variations to the test case.

let req2 = r#"{"jsonrpc":"2.0","id":1,"method":"sqr","params":[]}"#;
let req3 = r#"{"jsonrpc":"2.0","id":1,"method":"sqr","params":null}"#;
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't this be rejected as invalid?

Copy link
Author

Choose a reason for hiding this comment

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

It's a good question, I know only KODI jsonrpc server, that rejects only "params":null variation, but accepts both "params":[] and "params":{} as an empty parameter.

Copy link
Contributor

Choose a reason for hiding this comment

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

I'd distinguish 3 different cases:

  1. Method expects positional arguments (either 0 or some being optional)
  2. Method expects named arguments (either 0 or some being optional)
  3. Method expects raw arguments

In case (1) IMHO only params: [] should be accepted, similarly in case (2) only params: {} should be accepted. In both cases omitting params should be rejected.
In the 3rd case we can accept any combination, since it's up to the method to handle the raw parameters being passed.

Regarding params: null I'm wondering if that should be forbidden completely, since it's not really part of the spec.

Copy link
Member

@niklasad1 niklasad1 Oct 7, 2021

Choose a reason for hiding this comment

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

In both cases omitting params should be rejected.

hrm, really? In the client code Params::None would rejected then?

Regarding params: null I'm wondering if that should be forbidden completely, since it's not really part of the spec.

I'm fine with that and it might better to be explicit, mainly because it might be possible that a request contains the wrong type/format and the default value is then used without that the caller gets informed by that....

Copy link
Contributor

Choose a reason for hiding this comment

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

hrm, really? In the client code Params::None would rejected then?

I was checking the code and it might not be what we do now. AFAICT in case of optional parameters we parse None correctly as well. Anyways, I think this discussion is a bit tangential to that particular PR, so let's open an issue and discuss there.

The code in PR is an improvement for the client side for sure, we might want to follow up on how we want the server to behave separately.

let req4 = r#"{"jsonrpc":"2.0","id":1,"method":"sqr"}"#;

let res1 = io.handle_request_sync(req1);
let res2 = io.handle_request_sync(req2);
let res3 = io.handle_request_sync(req3);
let res4 = io.handle_request_sync(req4);
let expected1 = r#"{
"jsonrpc": "2.0",
"result": 4,
"id": 1
}"#;
let expected1: Response = serde_json::from_str(expected1).unwrap();
let expected2 = r#"{
"jsonrpc": "2.0",
"result": 1,
"id": 1
}"#;
let expected2: Response = serde_json::from_str(expected2).unwrap();

// then
let result1: Response = serde_json::from_str(&res1.unwrap()).unwrap();
assert_eq!(expected1, result1);

let result2: Response = serde_json::from_str(&res2.unwrap()).unwrap();
assert_eq!(expected2, result2);

let result3: Response = serde_json::from_str(&res3.unwrap()).unwrap();
assert_eq!(expected2, result3);

let result4: Response = serde_json::from_str(&res4.unwrap()).unwrap();
assert_eq!(expected2, result4);
}

#[test]
fn should_accept_only_notifications() {
let mut io = IoHandler::new();
Expand Down