cuprate_json_rpc/response.rs
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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
//! JSON-RPC 2.0 response object.
//---------------------------------------------------------------------------------------------------- Use
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
use crate::{error::ErrorObject, id::Id, version::Version};
//---------------------------------------------------------------------------------------------------- Response
/// [The response object](https://www.jsonrpc.org/specification#response_object).
///
/// The generic `T` is the response payload, i.e. it is the
/// type that holds both the `method` and `params`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Response<T> {
/// JSON-RPC protocol version; always `2.0`.
pub jsonrpc: Version,
/// This field must always be present in serialized JSON.
///
/// ### JSON-RPC 2.0 rules
/// - The [`Response`]'s ID must be the same as the [`Request`](crate::Request)
/// - If the `Request` omitted the `id` field, there should be no `Response`
/// - If there was an error in detecting the `Request`'s ID, the `Response` must contain an [`Id::Null`]
pub id: Id,
/// The response payload.
///
/// ### JSON-RPC 2.0 rules
/// - This must be [`Ok`] upon success
/// - This must be [`Err`] upon error
/// - This can be any (de)serializable data `T` on success
/// - This must be [`ErrorObject`] on errors
pub payload: Result<T, ErrorObject>,
}
impl<T> Response<T> {
/// Creates a successful response.
///
/// ```rust
/// use cuprate_json_rpc::{Id, Response};
///
/// let ok = Response::ok(Id::Num(123), "OK");
/// let json = serde_json::to_string(&ok).unwrap();
/// assert_eq!(json, r#"{"jsonrpc":"2.0","id":123,"result":"OK"}"#);
/// ```
pub const fn ok(id: Id, result: T) -> Self {
Self {
jsonrpc: Version,
id,
payload: Ok(result),
}
}
/// Creates an error response.
///
/// ```rust
/// use cuprate_json_rpc::{Id, Response, error::{ErrorObject, ErrorCode}};
///
/// let err = ErrorObject {
/// code: 0.into(),
/// message: "m".into(),
/// data: Some("d".into()),
/// };
///
/// let ok = Response::<()>::err(Id::Num(123), err);
/// let json = serde_json::to_string(&ok).unwrap();
/// assert_eq!(json, r#"{"jsonrpc":"2.0","id":123,"error":{"code":0,"message":"m","data":"d"}}"#);
/// ```
pub const fn err(id: Id, error: ErrorObject) -> Self {
Self {
jsonrpc: Version,
id,
payload: Err(error),
}
}
/// Creates an error response using [`ErrorObject::parse_error`].
///
/// ```rust
/// use cuprate_json_rpc::{Id, Response, error::{ErrorObject, ErrorCode}};
///
/// let ok = Response::<()>::parse_error(Id::Num(0));
/// let json = serde_json::to_string(&ok).unwrap();
/// assert_eq!(json, r#"{"jsonrpc":"2.0","id":0,"error":{"code":-32700,"message":"Parse error"}}"#);
/// ```
pub const fn parse_error(id: Id) -> Self {
Self {
jsonrpc: Version,
payload: Err(ErrorObject::parse_error()),
id,
}
}
/// Creates an error response using [`ErrorObject::invalid_request`].
///
/// ```rust
/// use cuprate_json_rpc::{Id, Response, error::{ErrorObject, ErrorCode}};
///
/// let ok = Response::<()>::invalid_request(Id::Num(0));
/// let json = serde_json::to_string(&ok).unwrap();
/// assert_eq!(json, r#"{"jsonrpc":"2.0","id":0,"error":{"code":-32600,"message":"Invalid Request"}}"#);
/// ```
pub const fn invalid_request(id: Id) -> Self {
Self {
jsonrpc: Version,
payload: Err(ErrorObject::invalid_request()),
id,
}
}
/// Creates an error response using [`ErrorObject::method_not_found`].
///
/// ```rust
/// use cuprate_json_rpc::{Id, Response, error::{ErrorObject, ErrorCode}};
///
/// let ok = Response::<()>::method_not_found(Id::Num(0));
/// let json = serde_json::to_string(&ok).unwrap();
/// assert_eq!(json, r#"{"jsonrpc":"2.0","id":0,"error":{"code":-32601,"message":"Method not found"}}"#);
/// ```
pub const fn method_not_found(id: Id) -> Self {
Self {
jsonrpc: Version,
payload: Err(ErrorObject::method_not_found()),
id,
}
}
/// Creates an error response using [`ErrorObject::invalid_params`].
///
/// ```rust
/// use cuprate_json_rpc::{Id, Response, error::{ErrorObject, ErrorCode}};
///
/// let ok = Response::<()>::invalid_params(Id::Num(0));
/// let json = serde_json::to_string(&ok).unwrap();
/// assert_eq!(json, r#"{"jsonrpc":"2.0","id":0,"error":{"code":-32602,"message":"Invalid params"}}"#);
/// ```
pub const fn invalid_params(id: Id) -> Self {
Self {
jsonrpc: Version,
payload: Err(ErrorObject::invalid_params()),
id,
}
}
/// Creates an error response using [`ErrorObject::internal_error`].
///
/// ```rust
/// use cuprate_json_rpc::{Id, Response, error::{ErrorObject, ErrorCode}};
///
/// let ok = Response::<()>::internal_error(Id::Num(0));
/// let json = serde_json::to_string(&ok).unwrap();
/// assert_eq!(json, r#"{"jsonrpc":"2.0","id":0,"error":{"code":-32603,"message":"Internal error"}}"#);
/// ```
pub const fn internal_error(id: Id) -> Self {
Self {
jsonrpc: Version,
payload: Err(ErrorObject::internal_error()),
id,
}
}
}
//---------------------------------------------------------------------------------------------------- Trait impl
impl<T> std::fmt::Display for Response<T>
where
T: Serialize,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match serde_json::to_string_pretty(self) {
Ok(json) => write!(f, "{json}"),
Err(_) => Err(std::fmt::Error),
}
}
}
//---------------------------------------------------------------------------------------------------- Serde impl
impl<T> Serialize for Response<T>
where
T: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("Response", 3)?;
s.serialize_field("jsonrpc", &self.jsonrpc)?;
// This member is required.
//
// Even if `null`, or the client `Request` didn't include one.
s.serialize_field("id", &self.id)?;
match &self.payload {
Ok(r) => s.serialize_field("result", r)?,
Err(e) => s.serialize_field("error", e)?,
}
s.end()
}
}
// [`Response`] has a manual deserialization implementation because
// we need to confirm `result` and `error` don't both exist:
//
// > Either the result member or error member MUST be included, but both members MUST NOT be included.
//
// <https://www.jsonrpc.org/specification#error_object>
impl<'de, T> Deserialize<'de> for Response<T>
where
T: Deserialize<'de> + 'de,
{
fn deserialize<D: Deserializer<'de>>(der: D) -> Result<Self, D::Error> {
use std::marker::PhantomData;
use serde::de::{Error, MapAccess, Visitor};
/// This type represents the key values within [`Response`].
enum Key {
/// "jsonrpc" field.
JsonRpc,
/// "result" field.
Result,
/// "error" field.
Error,
/// "id" field.
Id,
/// Any other unknown field (ignored).
Unknown,
}
// Deserialization for [`Response`]'s key fields.
//
// This ignores unknown keys.
impl<'de> Deserialize<'de> for Key {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
/// Serde visitor for [`Response`]'s key fields.
struct KeyVisitor;
impl Visitor<'_> for KeyVisitor {
type Value = Key;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("`jsonrpc`, `id`, `result`, `error`")
}
fn visit_str<E>(self, string: &str) -> Result<Key, E>
where
E: Error,
{
// PERF: this match is in order of how this library serializes fields.
match string {
"jsonrpc" => Ok(Key::JsonRpc),
"id" => Ok(Key::Id),
"result" => Ok(Key::Result),
"error" => Ok(Key::Error),
// Ignore any other keys that appear
// and continue deserialization.
_ => Ok(Key::Unknown),
}
}
}
deserializer.deserialize_identifier(KeyVisitor)
}
}
/// Serde visitor for the key-value map of [`Response`].
struct MapVisit<T>(PhantomData<T>);
// Deserialization for [`Response`]'s key and values (the JSON map).
impl<'de, T> Visitor<'de> for MapVisit<T>
where
T: Deserialize<'de> + 'de,
{
type Value = Response<T>;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str("JSON-RPC 2.0 Response")
}
/// This is a loop that goes over every key-value pair
/// and fills out the necessary fields.
///
/// If both `result/error` appear then this
/// deserialization will error, as to
/// follow the JSON-RPC 2.0 specification.
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
// Initialize values.
let mut jsonrpc = None;
let mut payload = None;
let mut id = None;
// Loop over map, filling values.
while let Some(key) = map.next_key::<Key>()? {
// PERF: this match is in order of how this library serializes fields.
match key {
Key::JsonRpc => jsonrpc = Some(map.next_value::<Version>()?),
Key::Id => id = Some(map.next_value::<Id>()?),
Key::Result => {
if payload.is_none() {
payload = Some(Ok(map.next_value::<T>()?));
} else {
return Err(Error::duplicate_field("result/error"));
}
}
Key::Error => {
if payload.is_none() {
payload = Some(Err(map.next_value::<ErrorObject>()?));
} else {
return Err(Error::duplicate_field("result/error"));
}
}
Key::Unknown => {
map.next_value::<serde::de::IgnoredAny>()?;
}
}
}
// Make sure all our key-value pairs are set and correct.
match (jsonrpc, id, payload) {
// Response with a single `result` or `error`.
(Some(jsonrpc), Some(id), Some(payload)) => Ok(Response {
jsonrpc,
id,
payload,
}),
// No fields existed.
(None, None, None) => Err(Error::missing_field("jsonrpc + id + result/error")),
// Some field was missing.
(None, _, _) => Err(Error::missing_field("jsonrpc")),
(_, None, _) => Err(Error::missing_field("id")),
(_, _, None) => Err(Error::missing_field("result/error")),
}
}
}
/// All expected fields of the [`Response`] type.
const FIELDS: &[&str; 4] = &["jsonrpc", "id", "result", "error"];
der.deserialize_struct("Response", FIELDS, MapVisit(PhantomData))
}
}
//---------------------------------------------------------------------------------------------------- TESTS
#[cfg(test)]
mod test {
use serde_json::json;
use super::*;
use crate::id::Id;
/// Basic serde test on OK results.
#[test]
fn serde_result() {
let result = String::from("result_ok");
let id = Id::Num(123);
let req = Response::ok(id.clone(), result.clone());
let ser: String = serde_json::to_string(&req).unwrap();
let de: Response<String> = serde_json::from_str(&ser).unwrap();
assert_eq!(de.payload.unwrap(), result);
assert_eq!(de.id, id);
}
/// Basic serde test on errors.
#[test]
fn serde_error() {
let error = ErrorObject::internal_error();
let id = Id::Num(123);
let req: Response<String> = Response::err(id.clone(), error.clone());
let ser: String = serde_json::to_string(&req).unwrap();
let de: Response<String> = serde_json::from_str(&ser).unwrap();
assert_eq!(de.payload.unwrap_err(), error);
assert_eq!(de.id, id);
}
/// Test that the `result` and `error` fields are mutually exclusive.
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: Error(\"duplicate field `result/error`\", line: 0, column: 0)"
)]
fn result_error_mutually_exclusive() {
let e = ErrorObject::internal_error();
let j = json!({
"jsonrpc": "2.0",
"id": 0,
"result": "",
"error": e
});
serde_json::from_value::<Response<String>>(j).unwrap();
}
/// Test that the `result` and `error` fields can repeat (and get overwritten).
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: Error(\"duplicate field `result/error`\", line: 1, column: 45)"
)]
fn result_repeat() {
// `result`
let json = r#"{"jsonrpc":"2.0","id":0,"result":"a","result":"b"}"#;
serde_json::from_str::<Response<String>>(json).unwrap();
}
/// Test that the `error` field cannot repeat.
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: Error(\"duplicate field `result/error`\", line: 1, column: 83)"
)]
fn error_repeat() {
let e = ErrorObject::invalid_request();
let e = serde_json::to_string(&e).unwrap();
let json = format!(r#"{{"jsonrpc":"2.0","id":0,"error":{e},"error":{e}}}"#);
serde_json::from_str::<Response<String>>(&json).unwrap();
}
/// Test that the `id` field must exist.
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: Error(\"missing field `id`\", line: 0, column: 0)"
)]
fn id_must_exist() {
let j = json!({
"jsonrpc": "2.0",
"result": "",
});
serde_json::from_value::<Response<String>>(j).unwrap();
}
/// Tests that non-ordered fields still deserialize okay.
#[test]
fn deserialize_out_of_order_keys() {
let e = ErrorObject::internal_error();
let j = json!({
"error": e,
"id": 0,
"jsonrpc": "2.0"
});
let resp = serde_json::from_value::<Response<String>>(j).unwrap();
assert_eq!(resp, Response::internal_error(Id::Num(0)));
let ok = Response::ok(Id::Num(0), "OK".to_string());
let j = json!({
"result": "OK",
"id": 0,
"jsonrpc": "2.0"
});
let resp = serde_json::from_value::<Response<String>>(j).unwrap();
assert_eq!(resp, ok);
}
/// Asserts that fields must be `lowercase`.
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: Error(\"missing field `jsonrpc`\", line: 1, column: 40)"
)]
fn lowercase() {
let mixed_case = r#"{"jSoNRPC":"2.0","id":123,"result":"OK"}"#;
serde_json::from_str::<Response<String>>(mixed_case).unwrap();
}
/// Tests that unknown fields are ignored, and deserialize continues.
/// Also that unicode and backslashes work.
#[test]
fn unknown_fields_and_unicode() {
let e = ErrorObject::internal_error();
let j = json!({
"error": e,
"\u{00f8}": 123,
"id": 0,
"unknown_field": 123,
"jsonrpc": "2.0",
"unknown_field": 123
});
let resp = serde_json::from_value::<Response<String>>(j).unwrap();
assert_eq!(resp, Response::internal_error(Id::Num(0)));
}
}