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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// 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 pertaining to JSON-RPC responses.

use std::borrow::Cow as StdCow;
use std::fmt;
use std::marker::PhantomData;

use crate::error::ErrorCode;
use crate::params::{Id, SubscriptionId, TwoPointZero};
use crate::request::Notification;
use crate::{ErrorObject, ErrorObjectOwned};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// JSON-RPC response object as defined in the [spec](https://www.jsonrpc.org/specification#response_object).
pub struct Response<'a, T: Clone> {
	/// JSON-RPC version.
	pub jsonrpc: Option<TwoPointZero>,
	/// Payload which can be result or error.
	pub payload: ResponsePayload<'a, T>,
	/// Request ID
	pub id: Id<'a>,
}

impl<'a, T: Clone> Response<'a, T> {
	/// Create a new [`Response`].
	pub fn new(payload: ResponsePayload<'a, T>, id: Id<'a>) -> Response<'a, T> {
		Response { jsonrpc: Some(TwoPointZero), payload, id }
	}

	/// Create an owned [`Response`].
	pub fn into_owned(self) -> Response<'static, T> {
		Response { jsonrpc: self.jsonrpc, payload: self.payload.into_owned(), id: self.id.into_owned() }
	}
}

impl<'a, T> fmt::Display for Response<'a, T>
where
	T: Serialize + Clone,
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str(&serde_json::to_string(&self).expect("valid JSON; qed"))
	}
}

impl<'a, T> fmt::Debug for Response<'a, T>
where
	T: Serialize + Clone,
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str(&serde_json::to_string(&self).expect("valid JSON; qed"))
	}
}

/// JSON-RPC response object as defined in the [spec](https://www.jsonrpc.org/specification#response_object)
/// but differs from [`Response`] as it only represent a successful response.
#[derive(Debug)]
pub struct Success<'a, T> {
	/// JSON-RPC version.
	pub jsonrpc: Option<TwoPointZero>,
	/// Result.
	pub result: T,
	/// Request ID
	pub id: Id<'a>,
}

impl<'a, T: Clone> TryFrom<Response<'a, T>> for Success<'a, T> {
	type Error = ErrorObjectOwned;

	fn try_from(rp: Response<'a, T>) -> Result<Self, Self::Error> {
		match rp.payload {
			ResponsePayload::Error(e) => Err(e.into_owned()),
			ResponsePayload::Success(r) => Ok(Success { jsonrpc: rp.jsonrpc, result: r.into_owned(), id: rp.id }),
		}
	}
}

/// Return value for subscriptions.
#[derive(Serialize, Deserialize, Debug)]
pub struct SubscriptionPayload<'a, T> {
	/// Subscription ID
	#[serde(borrow)]
	pub subscription: SubscriptionId<'a>,
	/// Result.
	pub result: T,
}

/// Subscription response object, embedding a [`SubscriptionPayload`] in the `params` member along with `result` field.
pub type SubscriptionResponse<'a, T> = Notification<'a, SubscriptionPayload<'a, T>>;
/// Subscription response object, embedding a [`SubscriptionPayload`] in the `params` member along with `error` field.
pub type SubscriptionError<'a, T> = Notification<'a, SubscriptionPayloadError<'a, T>>;

/// Error value for subscriptions.
#[derive(Serialize, Deserialize, Debug)]
pub struct SubscriptionPayloadError<'a, T> {
	/// Subscription ID
	#[serde(borrow)]
	pub subscription: SubscriptionId<'a>,
	/// Result.
	pub error: T,
}

/// Represent the payload of the JSON-RPC response object
///
/// It can be:
///
/// ```json
/// "result":<value>
/// "error":{"code":<code>,"message":<msg>,"data":<data>}
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum ResponsePayload<'a, T>
where
	T: Clone,
{
	/// Corresponds to successful JSON-RPC response with the field `result`.
	Success(StdCow<'a, T>),
	/// Corresponds to failed JSON-RPC response with a error object with the field `error.
	Error(ErrorObject<'a>),
}

impl<'a, T: Clone> ResponsePayload<'a, T> {
	/// Create a successful owned response payload.
	pub fn success(t: T) -> Self {
		Self::Success(StdCow::Owned(t))
	}

	/// Create a successful borrowed response payload.
	pub fn success_borrowed(t: &'a T) -> Self {
		Self::Success(StdCow::Borrowed(t))
	}

	/// Convert the response payload into owned.
	pub fn into_owned(self) -> ResponsePayload<'static, T> {
		match self {
			Self::Error(e) => ResponsePayload::Error(e.into_owned()),
			Self::Success(r) => ResponsePayload::Success(StdCow::Owned(r.into_owned())),
		}
	}

	/// Create an error response payload.
	pub fn error(e: impl Into<ErrorObjectOwned>) -> Self {
		Self::Error(e.into())
	}

	/// Create a borrowed error response payload.
	pub fn error_borrowed(e: impl Into<ErrorObject<'a>>) -> Self {
		Self::Error(e.into())
	}
}

impl<'a, T: Clone> From<ErrorCode> for ResponsePayload<'a, T> {
	fn from(code: ErrorCode) -> ResponsePayload<'a, T> {
		Self::Error(code.into())
	}
}

impl<'de, T> Deserialize<'de> for Response<'de, T>
where
	T: Deserialize<'de> + Clone,
{
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
		T: Deserialize<'de> + Clone,
	{
		#[derive(Debug)]
		enum Field {
			Jsonrpc,
			Result,
			Error,
			Id,
			Ignore,
		}

		impl<'de> Deserialize<'de> for Field {
			fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
			where
				D: Deserializer<'de>,
			{
				struct FieldVisitor;

				impl<'de> serde::de::Visitor<'de> for FieldVisitor {
					type Value = Field;

					fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
						formatter.write_str("`jsonrpc`, `result`, `error` and `id`")
					}

					fn visit_str<E>(self, value: &str) -> Result<Field, E>
					where
						E: serde::de::Error,
					{
						match value {
							"jsonrpc" => Ok(Field::Jsonrpc),
							"result" => Ok(Field::Result),
							"error" => Ok(Field::Error),
							"id" => Ok(Field::Id),
							_ => Ok(Field::Ignore),
						}
					}
				}
				deserializer.deserialize_identifier(FieldVisitor)
			}
		}

		struct Visitor<T>(PhantomData<T>);

		impl<T> Visitor<T> {
			fn new() -> Visitor<T> {
				Visitor(PhantomData)
			}
		}

		impl<'de, T> serde::de::Visitor<'de> for Visitor<T>
		where
			T: Deserialize<'de> + Clone + 'de,
		{
			type Value = Response<'de, T>;

			fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
				formatter.write_str("struct Response")
			}

			fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
			where
				V: serde::de::MapAccess<'de>,
			{
				let mut jsonrpc = None;
				let mut result = None;
				let mut error = None;
				let mut id = None;
				while let Some(key) = map.next_key()? {
					match key {
						Field::Result => {
							if result.is_some() {
								return Err(serde::de::Error::duplicate_field("result"));
							}
							result = Some(map.next_value()?);
						}
						Field::Error => {
							if error.is_some() {
								return Err(serde::de::Error::duplicate_field("error"));
							}
							error = Some(map.next_value()?);
						}
						Field::Id => {
							if id.is_some() {
								return Err(serde::de::Error::duplicate_field("id"));
							}
							id = Some(map.next_value()?);
						}
						Field::Jsonrpc => {
							if jsonrpc.is_some() {
								return Err(serde::de::Error::duplicate_field("jsonrpc"));
							}
							jsonrpc = Some(map.next_value()?);
						}
						Field::Ignore => {
							let _ = map.next_value::<serde::de::IgnoredAny>()?;
						}
					}
				}

				let id = id.ok_or_else(|| serde::de::Error::missing_field("id"))?;

				let response = match (jsonrpc, result, error) {
					(_, Some(_), Some(_)) => {
						return Err(serde::de::Error::duplicate_field("result and error are mutually exclusive"))
					}
					(Some(jsonrpc), Some(result), None) => {
						Response { jsonrpc, payload: ResponsePayload::Success(result), id }
					}
					(Some(jsonrpc), None, Some(err)) => Response { jsonrpc, payload: ResponsePayload::Error(err), id },
					(None, Some(result), _) => {
						Response { jsonrpc: None, payload: ResponsePayload::Success(result), id }
					}
					(None, _, Some(err)) => Response { jsonrpc: None, payload: ResponsePayload::Error(err), id },
					(_, None, None) => return Err(serde::de::Error::missing_field("result/error")),
				};

				Ok(response)
			}
		}

		const FIELDS: &[&str] = &["jsonrpc", "result", "error", "id"];
		deserializer.deserialize_struct("Response", FIELDS, Visitor::new())
	}
}

impl<'a, T> Serialize for Response<'a, T>
where
	T: Serialize + Clone,
{
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		let mut s = serializer.serialize_struct("Response", 3)?;

		if let Some(field) = &self.jsonrpc {
			s.serialize_field("jsonrpc", field)?;
		}

		s.serialize_field("id", &self.id)?;

		match &self.payload {
			ResponsePayload::Error(err) => s.serialize_field("error", err)?,
			ResponsePayload::Success(r) => s.serialize_field("result", r)?,
		};

		s.end()
	}
}

#[cfg(test)]
mod tests {
	use super::{Id, Response, TwoPointZero};
	use crate::{response::ResponsePayload, ErrorObjectOwned};

	#[test]
	fn serialize_call_ok_response() {
		let ser = serde_json::to_string(&Response {
			jsonrpc: Some(TwoPointZero),
			payload: ResponsePayload::success("ok"),
			id: Id::Number(1),
		})
		.unwrap();
		let exp = r#"{"jsonrpc":"2.0","id":1,"result":"ok"}"#;
		assert_eq!(ser, exp);
	}

	#[test]
	fn serialize_call_err_response() {
		let ser = serde_json::to_string(&Response {
			jsonrpc: Some(TwoPointZero),
			payload: ResponsePayload::<()>::error(ErrorObjectOwned::owned(1, "lo", None::<()>)),
			id: Id::Number(1),
		})
		.unwrap();
		let exp = r#"{"jsonrpc":"2.0","id":1,"error":{"code":1,"message":"lo"}}"#;
		assert_eq!(ser, exp);
	}

	#[test]
	fn serialize_call_response_missing_version_field() {
		let ser = serde_json::to_string(&Response {
			jsonrpc: None,
			payload: ResponsePayload::success("ok"),
			id: Id::Number(1),
		})
		.unwrap();
		let exp = r#"{"id":1,"result":"ok"}"#;
		assert_eq!(ser, exp);
	}

	#[test]
	fn deserialize_success_call() {
		let exp =
			Response { jsonrpc: Some(TwoPointZero), payload: ResponsePayload::success(99_u64), id: Id::Number(11) };
		let dsr: Response<u64> = serde_json::from_str(r#"{"jsonrpc":"2.0", "result":99, "id":11}"#).unwrap();
		assert_eq!(dsr.jsonrpc, exp.jsonrpc);
		assert_eq!(dsr.payload, exp.payload);
		assert_eq!(dsr.id, exp.id);
	}

	#[test]
	fn deserialize_err_call() {
		let exp = Response {
			jsonrpc: Some(TwoPointZero),
			payload: ResponsePayload::error(ErrorObjectOwned::owned(1, "lo", None::<()>)),
			id: Id::Number(11),
		};
		let dsr: Response<()> =
			serde_json::from_str(r#"{"jsonrpc":"2.0","error":{"code":1,"message":"lo"},"id":11}"#).unwrap();
		assert_eq!(dsr.jsonrpc, exp.jsonrpc);
		assert_eq!(dsr.payload, exp.payload);
		assert_eq!(dsr.id, exp.id);
	}

	#[test]
	fn deserialize_call_missing_version_field() {
		let exp = Response { jsonrpc: None, payload: ResponsePayload::success(99_u64), id: Id::Number(11) };
		let dsr: Response<u64> = serde_json::from_str(r#"{"jsonrpc":null, "result":99, "id":11}"#).unwrap();
		assert_eq!(dsr.jsonrpc, exp.jsonrpc);
		assert_eq!(dsr.payload, exp.payload);
		assert_eq!(dsr.id, exp.id);
	}

	#[test]
	fn deserialize_with_unknown_field() {
		let exp = Response { jsonrpc: None, payload: ResponsePayload::success(99_u64), id: Id::Number(11) };
		let dsr: Response<u64> =
			serde_json::from_str(r#"{"jsonrpc":null, "result":99, "id":11, "unknown":11}"#).unwrap();
		assert_eq!(dsr.jsonrpc, exp.jsonrpc);
		assert_eq!(dsr.payload, exp.payload);
		assert_eq!(dsr.id, exp.id);
	}
}