cuprate_json_rpc/
request.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
//! JSON-RPC 2.0 request object.

//---------------------------------------------------------------------------------------------------- Use
use serde::{Deserialize, Serialize};

use crate::{id::Id, version::Version};

//---------------------------------------------------------------------------------------------------- Request
/// [The request object](https://www.jsonrpc.org/specification#request_object).
///
/// The generic `T` is the body type of the request, i.e. it is the
/// type that holds both the `method` and `params`.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Request<T> {
    /// JSON-RPC protocol version; always `2.0`.
    pub jsonrpc: Version,

    /// An identifier established by the Client.
    ///
    /// If it is not included it is assumed to be a
    /// [notification](https://www.jsonrpc.org/specification#notification).
    ///
    /// ### `None` vs `Some(Id::Null)`
    /// This field will be completely omitted during serialization if [`None`],
    /// however if it is `Some(Id::Null)`, it will be serialized as `"id": null`.
    ///
    /// Note that the JSON-RPC 2.0 specification discourages the use of `Id::NUll`,
    /// so if there is no ID needed, consider using `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,

    #[serde(flatten)]
    /// The `method` and `params` fields.
    ///
    /// - `method`: A type that serializes as the name of the method to be invoked.
    /// - `params`: A structured value that holds the parameter values to be used during the invocation of the method.
    ///
    /// As mentioned in the library documentation, there are no `method/params` fields in [`Request`],
    /// they are both merged in this `body` field which is `#[serde(flatten)]`ed.
    ///
    /// ### Invariant
    /// Your `T` must serialize as `method` and `params` to comply with the specification.
    pub body: T,
}

impl<T> Request<T> {
    /// Create a new [`Self`] with no [`Id`].
    ///
    /// ```rust
    /// use cuprate_json_rpc::Request;
    ///
    /// assert_eq!(Request::new("").id, None);
    /// ```
    pub const fn new(body: T) -> Self {
        Self {
            jsonrpc: Version,
            id: None,
            body,
        }
    }

    /// Create a new [`Self`] with an [`Id`].
    ///
    /// ```rust
    /// use cuprate_json_rpc::{Id, Request};
    ///
    /// assert_eq!(Request::new_with_id(Id::Num(0), "").id, Some(Id::Num(0)));
    /// ```
    pub const fn new_with_id(id: Id, body: T) -> Self {
        Self {
            jsonrpc: Version,
            id: Some(id),
            body,
        }
    }

    /// Returns `true` if the request is [notification](https://www.jsonrpc.org/specification#notification).
    ///
    /// In other words, if `id` is [`None`], this returns `true`.
    ///
    /// ```rust
    /// use cuprate_json_rpc::{Id, Request};
    ///
    /// assert!(Request::new("").is_notification());
    /// assert!(!Request::new_with_id(Id::Null, "").is_notification());
    /// ```
    pub const fn is_notification(&self) -> bool {
        self.id.is_none()
    }
}

//---------------------------------------------------------------------------------------------------- Trait impl
impl<T> std::fmt::Display for Request<T>
where
    T: std::fmt::Display + 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),
        }
    }
}

//---------------------------------------------------------------------------------------------------- TESTS
#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        id::Id,
        tests::{assert_ser, Body},
    };

    use pretty_assertions::assert_eq;
    use serde_json::{json, Value};

    /// Basic serde tests.
    #[test]
    fn serde() {
        let id = Id::Num(123);
        let body = Body {
            method: "a_method".into(),
            params: [0, 1, 2],
        };

        let req = Request::new_with_id(id, body);

        assert!(!req.is_notification());

        let ser: String = serde_json::to_string(&req).unwrap();
        let de: Request<Body<[u8; 3]>> = serde_json::from_str(&ser).unwrap();

        assert_eq!(req, de);
    }

    /// Asserts that fields must be `lowercase`.
    #[test]
    #[should_panic(
        expected = "called `Result::unwrap()` on an `Err` value: Error(\"missing field `jsonrpc`\", line: 1, column: 63)"
    )]
    fn lowercase() {
        let id = Id::Num(123);
        let body = Body {
            method: "a_method".into(),
            params: [0, 1, 2],
        };

        let req = Request::new_with_id(id, body);

        let ser: String = serde_json::to_string(&req).unwrap();
        assert_eq!(
            ser,
            r#"{"jsonrpc":"2.0","id":123,"method":"a_method","params":[0,1,2]}"#,
        );

        let mixed_case = r#"{"jSoNRPC":"2.0","ID":123,"method":"a_method","params":[0,1,2]}"#;
        let de: Request<Body<[u8; 3]>> = serde_json::from_str(mixed_case).unwrap();
        assert_eq!(de, req);
    }

    /// Tests that null `id` shows when serializing.
    #[test]
    fn request_null_id() {
        let req = Request::new_with_id(
            Id::Null,
            Body {
                method: "m".into(),
                params: "p".to_string(),
            },
        );
        let json = json!({
            "jsonrpc": "2.0",
            "id": null,
            "method": "m",
            "params": "p",
        });

        assert_ser(&req, &json);
    }

    /// Tests that a `None` `id` omits the field when serializing.
    #[test]
    fn request_none_id() {
        let req = Request::new(Body {
            method: "a".into(),
            params: "b".to_string(),
        });
        let json = json!({
            "jsonrpc": "2.0",
            "method": "a",
            "params": "b",
        });

        assert_ser(&req, &json);
    }

    /// Tests that omitting `params` omits the field when serializing.
    #[test]
    fn request_no_params() {
        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
        struct NoParamMethod {
            method: String,
        }

        let req = Request::new_with_id(
            Id::Num(123),
            NoParamMethod {
                method: "asdf".to_string(),
            },
        );
        let json = json!({
            "jsonrpc": "2.0",
            "id": 123,
            "method": "asdf",
        });

        assert_ser(&req, &json);
    }

    /// Tests that tagged enums serialize correctly.
    #[test]
    fn request_tagged_enums() {
        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
        struct GetHeight {
            height: u64,
        }

        #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
        #[serde(tag = "method", content = "params")]
        #[serde(rename_all = "snake_case")]
        enum Methods {
            GetHeight(/* param: */ GetHeight),
        }

        let req = Request::new_with_id(Id::Num(123), Methods::GetHeight(GetHeight { height: 0 }));
        let json = json!({
            "jsonrpc": "2.0",
            "id": 123,
            "method": "get_height",
            "params": {
                "height": 0,
            },
        });

        assert_ser(&req, &json);
    }

    /// Tests that requests serialize into the expected JSON value.
    #[test]
    fn request_is_expected_value() {
        // Test values: (request, expected_value)
        let array: [(Request<Body<[u8; 3]>>, Value); 3] = [
            (
                Request::new_with_id(
                    Id::Num(123),
                    Body {
                        method: "method_1".into(),
                        params: [0, 1, 2],
                    },
                ),
                json!({
                    "jsonrpc": "2.0",
                    "id": 123,
                    "method": "method_1",
                    "params": [0, 1, 2],
                }),
            ),
            (
                Request::new_with_id(
                    Id::Null,
                    Body {
                        method: "method_2".into(),
                        params: [3, 4, 5],
                    },
                ),
                json!({
                    "jsonrpc": "2.0",
                    "id": null,
                    "method": "method_2",
                    "params": [3, 4, 5],
                }),
            ),
            (
                Request::new_with_id(
                    Id::Str("string_id".into()),
                    Body {
                        method: "method_3".into(),
                        params: [6, 7, 8],
                    },
                ),
                json!({
                    "jsonrpc": "2.0",
                    "method": "method_3",
                    "id": "string_id",
                    "params": [6, 7, 8],
                }),
            ),
        ];

        for (request, expected_value) in array {
            assert_ser(&request, &expected_value);
        }
    }

    /// Tests that non-ordered fields still deserialize okay.
    #[test]
    fn deserialize_out_of_order_keys() {
        let expected = Request::new_with_id(
            Id::Str("id".into()),
            Body {
                method: "method".into(),
                params: [0, 1, 2],
            },
        );

        let json = json!({
            "method": "method",
            "id": "id",
            "params": [0, 1, 2],
            "jsonrpc": "2.0",
        });

        let resp = serde_json::from_value::<Request<Body<[u8; 3]>>>(json).unwrap();
        assert_eq!(resp, expected);
    }

    /// Tests that unknown fields are ignored, and deserialize continues.
    /// Also that unicode and backslashes work.
    #[test]
    fn unknown_fields_and_unicode() {
        let expected = Request::new_with_id(
            Id::Str("id".into()),
            Body {
                method: "method".into(),
                params: [0, 1, 2],
            },
        );

        let json = json!({
            "unknown_field": 123,
            "method": "method",
            "unknown_field": 123,
            "id": "id",
            "\nhello": 123,
            "params": [0, 1, 2],
            "\u{00f8}": 123,
            "jsonrpc": "2.0",
            "unknown_field": 123,
        });

        let resp = serde_json::from_value::<Request<Body<[u8; 3]>>>(json).unwrap();
        assert_eq!(resp, expected);
    }
}