1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//! jsonrpc request

use super::{Id, Params, Version};

/// Represents jsonrpc request which is a method call.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MethodCall {
	/// A String specifying the version of the JSON-RPC protocol.
	pub jsonrpc: Option<Version>,
	/// A String containing the name of the method to be invoked.
	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")]
	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
	/// to be a notification.
	pub id: Id,
}

/// Represents jsonrpc request which is a notification.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Notification {
	/// A String specifying the version of the JSON-RPC protocol.
	pub jsonrpc: Option<Version>,
	/// A String containing the name of the method to be invoked.
	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")]
	pub params: Params,
}

/// Represents single jsonrpc call.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Call {
	/// Call method
	MethodCall(MethodCall),
	/// Fire notification
	Notification(Notification),
	/// Invalid call
	Invalid {
		/// Call id (if known)
		#[serde(default = "default_id")]
		id: Id,
	},
}

fn default_params() -> Params {
	Params::None
}

fn default_id() -> Id {
	Id::Null
}

impl From<MethodCall> for Call {
	fn from(mc: MethodCall) -> Self {
		Call::MethodCall(mc)
	}
}

impl From<Notification> for Call {
	fn from(n: Notification) -> Self {
		Call::Notification(n)
	}
}

/// Represents jsonrpc request.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum Request {
	/// Single request (call)
	Single(Call),
	/// Batch of requests (calls)
	Batch(Vec<Call>),
}

#[cfg(test)]
mod tests {
	use super::*;
	use serde_json::Value;

	#[test]
	fn method_call_serialize() {
		use serde_json;
		use serde_json::Value;

		let m = MethodCall {
			jsonrpc: Some(Version::V2),
			method: "update".to_owned(),
			params: Params::Array(vec![Value::from(1), Value::from(2)]),
			id: Id::Num(1),
		};

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

	#[test]
	fn notification_serialize() {
		use serde_json;
		use serde_json::Value;

		let n = Notification {
			jsonrpc: Some(Version::V2),
			method: "update".to_owned(),
			params: Params::Array(vec![Value::from(1), Value::from(2)]),
		};

		let serialized = serde_json::to_string(&n).unwrap();
		assert_eq!(serialized, r#"{"jsonrpc":"2.0","method":"update","params":[1,2]}"#);
	}

	#[test]
	fn call_serialize() {
		use serde_json;
		use serde_json::Value;

		let n = Call::Notification(Notification {
			jsonrpc: Some(Version::V2),
			method: "update".to_owned(),
			params: Params::Array(vec![Value::from(1)]),
		});

		let serialized = serde_json::to_string(&n).unwrap();
		assert_eq!(serialized, r#"{"jsonrpc":"2.0","method":"update","params":[1]}"#);
	}

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

		let batch = Request::Batch(vec![
			Call::MethodCall(MethodCall {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::Array(vec![Value::from(1), Value::from(2)]),
				id: Id::Num(1),
			}),
			Call::Notification(Notification {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::Array(vec![Value::from(1)]),
			}),
		]);

		let serialized = serde_json::to_string(&batch).unwrap();
		assert_eq!(
			serialized,
			r#"[{"jsonrpc":"2.0","method":"update","params":[1,2],"id":1},{"jsonrpc":"2.0","method":"update","params":[1]}]"#
		);
	}

	#[test]
	fn notification_deserialize() {
		use serde_json;
		use serde_json::Value;

		let s = r#"{"jsonrpc": "2.0", "method": "update", "params": [1,2]}"#;
		let deserialized: Notification = serde_json::from_str(s).unwrap();

		assert_eq!(
			deserialized,
			Notification {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::Array(vec![Value::from(1), Value::from(2)])
			}
		);

		let s = r#"{"jsonrpc": "2.0", "method": "foobar"}"#;
		let deserialized: Notification = serde_json::from_str(s).unwrap();

		assert_eq!(
			deserialized,
			Notification {
				jsonrpc: Some(Version::V2),
				method: "foobar".to_owned(),
				params: Params::None,
			}
		);

		let s = r#"{"jsonrpc": "2.0", "method": "update", "params": [1,2], "id": 1}"#;
		let deserialized: Result<Notification, _> = serde_json::from_str(s);
		assert!(deserialized.is_err());
	}

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

		let s = r#"{"jsonrpc": "2.0", "method": "update", "params": [1]}"#;
		let deserialized: Call = serde_json::from_str(s).unwrap();
		assert_eq!(
			deserialized,
			Call::Notification(Notification {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::Array(vec![Value::from(1)])
			})
		);

		let s = r#"{"jsonrpc": "2.0", "method": "update", "params": [1], "id": 1}"#;
		let deserialized: Call = serde_json::from_str(s).unwrap();
		assert_eq!(
			deserialized,
			Call::MethodCall(MethodCall {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::Array(vec![Value::from(1)]),
				id: Id::Num(1)
			})
		);

		let s = r#"{"jsonrpc": "2.0", "method": "update", "params": [], "id": 1}"#;
		let deserialized: Call = serde_json::from_str(s).unwrap();
		assert_eq!(
			deserialized,
			Call::MethodCall(MethodCall {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::Array(vec![]),
				id: Id::Num(1)
			})
		);

		let s = r#"{"jsonrpc": "2.0", "method": "update", "params": null, "id": 1}"#;
		let deserialized: Call = serde_json::from_str(s).unwrap();
		assert_eq!(
			deserialized,
			Call::MethodCall(MethodCall {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::None,
				id: Id::Num(1)
			})
		);

		let s = r#"{"jsonrpc": "2.0", "method": "update", "id": 1}"#;
		let deserialized: Call = serde_json::from_str(s).unwrap();
		assert_eq!(
			deserialized,
			Call::MethodCall(MethodCall {
				jsonrpc: Some(Version::V2),
				method: "update".to_owned(),
				params: Params::None,
				id: Id::Num(1)
			})
		);
	}

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

		let s = r#"[{}, {"jsonrpc": "2.0", "method": "update", "params": [1,2], "id": 1},{"jsonrpc": "2.0", "method": "update", "params": [1]}]"#;
		let deserialized: Request = serde_json::from_str(s).unwrap();
		assert_eq!(
			deserialized,
			Request::Batch(vec![
				Call::Invalid { id: Id::Null },
				Call::MethodCall(MethodCall {
					jsonrpc: Some(Version::V2),
					method: "update".to_owned(),
					params: Params::Array(vec![Value::from(1), Value::from(2)]),
					id: Id::Num(1)
				}),
				Call::Notification(Notification {
					jsonrpc: Some(Version::V2),
					method: "update".to_owned(),
					params: Params::Array(vec![Value::from(1)])
				})
			])
		)
	}

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

		let s = r#"{"id":120,"method":"my_method","params":["foo", "bar"],"extra_field":[]}"#;
		let deserialized: Request = serde_json::from_str(s).unwrap();

		match deserialized {
			Request::Single(Call::Invalid { id: Id::Num(120) }) => {}
			_ => panic!("Request wrongly deserialized: {:?}", deserialized),
		}
	}
}