Skip to main content

jsonrpsee_types/
params.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! Types to handle JSON-RPC request parameters according to the [spec](https://www.jsonrpc.org/specification#parameter_structures).
28//! Some types come with a "*Ser" variant that implements [`serde::Serialize`]; these are used in
29//! the client.
30
31use std::{borrow::Cow, fmt};
32
33use serde::{
34    de::{self, Deserializer, Unexpected, Visitor},
35    ser::Serializer,
36    Deserialize, Serialize,
37};
38use serde_json::Value as JsonValue;
39
40use crate::{error::ErrorCode, ErrorObject, ErrorObjectOwned};
41
42/// JSON-RPC v2 marker type.
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub struct TwoPointZero;
45
46struct TwoPointZeroVisitor;
47
48impl Visitor<'_> for TwoPointZeroVisitor {
49    type Value = TwoPointZero;
50
51    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
52        formatter.write_str(r#"a string "2.0""#)
53    }
54
55    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
56    where
57        E: de::Error,
58    {
59        match s {
60            "2.0" => Ok(TwoPointZero),
61            _ => Err(de::Error::invalid_value(Unexpected::Other("string"), &self)),
62        }
63    }
64}
65
66impl<'de> Deserialize<'de> for TwoPointZero {
67    fn deserialize<D>(deserializer: D) -> Result<TwoPointZero, D::Error>
68    where
69        D: Deserializer<'de>,
70    {
71        deserializer.deserialize_str(TwoPointZeroVisitor)
72    }
73}
74
75impl Serialize for TwoPointZero {
76    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
77    where
78        S: Serializer,
79    {
80        serializer.serialize_str("2.0")
81    }
82}
83
84/// Parameters sent with an incoming JSON-RPC request.
85///
86/// The data containing the params is a `Cow<&str>` and can either be a borrowed `&str` of JSON from
87/// an incoming [`super::request::Request`] (which in turn borrows it from the input buffer that is
88/// shared between requests); or, it can be an owned [`String`].
89#[derive(Clone, Debug)]
90pub struct Params<'a>(Option<Cow<'a, str>>);
91
92impl<'a> Params<'a> {
93    /// Create params
94    pub fn new(raw: Option<&'a str>) -> Self {
95        Self(raw.map(|r| r.trim().into()))
96    }
97
98    /// Obtain a sequence parser, [`ParamsSequence`].
99    ///
100    /// This allows sequential parsing of the incoming params, using an `Iterator`-style API and is
101    /// useful when the RPC request has optional parameters at the tail that may or may not be
102    /// present.
103    pub fn sequence(&self) -> ParamsSequence<'_> {
104        let json = match self.0.as_ref() {
105            // It's assumed that params is `[a,b,c]`, if empty regard as no params.
106            Some(json) if json == "[]" => "",
107            Some(json) => json,
108            None => "",
109        };
110        ParamsSequence(json)
111    }
112
113    /// Attempt to parse all parameters as an array or map into type `T`.
114    pub fn parse<T>(&'a self) -> Result<T, ErrorObjectOwned>
115    where
116        T: Deserialize<'a>,
117    {
118        // NOTE(niklasad1): Option::None is serialized as `null` so we provide that here.
119        let params = self.0.as_ref().map(AsRef::as_ref).unwrap_or("null");
120        serde_json::from_str(params).map_err(invalid_params)
121    }
122
123    /// Attempt to parse parameters as an array of a single value of type `T`, and returns that
124    /// value.
125    pub fn one<T>(&'a self) -> Result<T, ErrorObjectOwned>
126    where
127        T: Deserialize<'a>,
128    {
129        self.parse::<[T; 1]>().map(|[res]| res)
130    }
131
132    /// Convert `Params<'a>` to `Params<'static>` so that it can be moved across threads.
133    ///
134    /// This will cause an allocation if the params internally are using a borrowed JSON slice.
135    pub fn into_owned(self) -> Params<'static> {
136        Params(self.0.map(|s| Cow::Owned(s.into_owned())))
137    }
138
139    /// Return the length of underlying JSON string in number of bytes.
140    pub fn len_bytes(&self) -> usize {
141        match self.0 {
142            Some(ref cow) => cow.len(),
143            None => 0,
144        }
145    }
146
147    /// Return the underlying JSON string as a `&str`.
148    pub fn as_str(&self) -> Option<&str> {
149        match self.0 {
150            Some(ref cow) => Some(cow.as_ref()),
151            None => None,
152        }
153    }
154}
155
156/// An `Iterator`-like parser for a sequence of [`Params`].
157///
158/// This will parse the params one at a time, and allows for graceful handling of optional
159/// parameters at the tail; other use cases are likely better served by [`Params::parse`]. The
160/// reason this is not an actual [`Iterator`] is that params parsing (often) yields values of
161/// different types.
162///
163/// Regards empty array `[]` as no parameters provided.
164#[derive(Debug, Copy, Clone)]
165pub struct ParamsSequence<'a>(&'a str);
166
167impl<'a> ParamsSequence<'a> {
168    fn next_inner<T>(&mut self) -> Option<Result<T, ErrorObjectOwned>>
169    where
170        T: Deserialize<'a>,
171    {
172        let mut json = self.0;
173        match json.chars().next()? {
174            ']' => {
175                self.0 = "";
176                return None;
177            }
178            '[' | ',' => json = &json[1..],
179            found => {
180                let errmsg =
181                    format!("Invalid params. Expected one of '[', ']' or ',' but found {found:?}");
182                return Some(Err(invalid_params(errmsg)));
183            }
184        }
185
186        let mut iter = serde_json::Deserializer::from_str(json).into_iter::<T>();
187
188        match iter.next()? {
189            Ok(value) => {
190                self.0 = json[iter.byte_offset()..].trim_start();
191
192                Some(Ok(value))
193            }
194            Err(e) => {
195                self.0 = "";
196                Some(Err(invalid_params(e)))
197            }
198        }
199    }
200
201    /// Parse the next parameter to type `T`
202    ///
203    /// ```
204    /// # use jsonrpsee_types::params::Params;
205    /// let params = Params::new(Some(r#"[true, 10, "foo"]"#));
206    /// let mut seq = params.sequence();
207    ///
208    /// let a: bool = seq.next().unwrap();
209    /// let b: i32 = seq.next().unwrap();
210    /// let c: &str = seq.next().unwrap();
211    ///
212    /// assert_eq!(a, true);
213    /// assert_eq!(b, 10);
214    /// assert_eq!(c, "foo");
215    /// ```
216    #[allow(clippy::should_implement_trait)]
217    pub fn next<T>(&mut self) -> Result<T, ErrorObjectOwned>
218    where
219        T: Deserialize<'a>,
220    {
221        match self.next_inner() {
222            Some(result) => result,
223            None => Err(invalid_params("No more params")),
224        }
225    }
226
227    /// Parse the next optional parameter to type `Option<T>`.
228    ///
229    /// The result will be `None` for `null`, and for missing values in the supplied JSON array.
230    ///
231    /// ```
232    /// # use jsonrpsee_types::params::Params;
233    /// let params = Params::new(Some(r#"[1, 2, null]"#));
234    /// let mut seq = params.sequence();
235    ///
236    /// let params: [Option<u32>; 4] = [
237    ///     seq.optional_next().unwrap(),
238    ///     seq.optional_next().unwrap(),
239    ///     seq.optional_next().unwrap(),
240    ///     seq.optional_next().unwrap(),
241    /// ];
242    ///
243    /// assert_eq!(params, [Some(1), Some(2), None, None]);
244    /// ```
245    pub fn optional_next<T>(&mut self) -> Result<Option<T>, ErrorObjectOwned>
246    where
247        T: Deserialize<'a>,
248    {
249        match self.next_inner::<Option<T>>() {
250            Some(result) => result,
251            None => Ok(None),
252        }
253    }
254}
255
256/// Id of a subscription, communicated by the server.
257#[derive(Debug, PartialEq, Clone, Hash, Eq, Serialize)]
258#[serde(untagged)]
259pub enum SubscriptionId<'a> {
260    /// Numeric id
261    Num(u64),
262    /// String id
263    Str(Cow<'a, str>),
264}
265
266impl From<SubscriptionId<'_>> for JsonValue {
267    fn from(sub_id: SubscriptionId) -> Self {
268        match sub_id {
269            SubscriptionId::Num(n) => n.into(),
270            SubscriptionId::Str(s) => s.into_owned().into(),
271        }
272    }
273}
274
275impl From<u64> for SubscriptionId<'_> {
276    fn from(sub_id: u64) -> Self {
277        Self::Num(sub_id)
278    }
279}
280
281impl From<String> for SubscriptionId<'_> {
282    fn from(sub_id: String) -> Self {
283        Self::Str(sub_id.into())
284    }
285}
286
287impl<'a> TryFrom<JsonValue> for SubscriptionId<'a> {
288    type Error = ();
289
290    fn try_from(json: JsonValue) -> Result<SubscriptionId<'a>, ()> {
291        match json {
292            JsonValue::String(s) => Ok(SubscriptionId::Str(s.into())),
293            JsonValue::Number(n) => {
294                if let Some(n) = n.as_u64() {
295                    Ok(SubscriptionId::Num(n))
296                } else {
297                    Err(())
298                }
299            }
300            _ => Err(()),
301        }
302    }
303}
304
305impl SubscriptionId<'_> {
306    /// Convert `SubscriptionId<'a>` to `SubscriptionId<'static>` so that it can be moved across
307    /// threads.
308    ///
309    /// This can cause an allocation if the id is a string.
310    pub fn into_owned(self) -> SubscriptionId<'static> {
311        match self {
312            SubscriptionId::Num(num) => SubscriptionId::Num(num),
313            SubscriptionId::Str(s) => SubscriptionId::Str(Cow::Owned(s.into_owned())),
314        }
315    }
316}
317
318struct SubscriptionIdVisitor;
319
320impl<'de> Visitor<'de> for SubscriptionIdVisitor {
321    type Value = SubscriptionId<'de>;
322
323    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
324        formatter.write_str("an unsigned integer or a string")
325    }
326
327    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> {
328        Ok(SubscriptionId::Num(v))
329    }
330
331    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
332    where
333        E: de::Error,
334    {
335        u64::try_from(v)
336            .map(SubscriptionId::Num)
337            .map_err(|_| de::Error::invalid_value(Unexpected::Signed(v), &self))
338    }
339
340    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
341        Ok(SubscriptionId::Str(Cow::Owned(v.to_owned())))
342    }
343
344    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> {
345        Ok(SubscriptionId::Str(Cow::Borrowed(v)))
346    }
347
348    fn visit_string<E>(self, v: String) -> Result<Self::Value, E> {
349        Ok(SubscriptionId::Str(Cow::Owned(v)))
350    }
351}
352
353/// Parses the id without buffering it: the untagged derive would first copy a peer-supplied array
354/// or object into an intermediate tree before rejecting it.
355impl<'de: 'a, 'a> Deserialize<'de> for SubscriptionId<'a> {
356    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
357    where
358        D: Deserializer<'de>,
359    {
360        deserializer.deserialize_any(SubscriptionIdVisitor)
361    }
362}
363
364/// Request Id
365#[derive(Debug, PartialEq, Clone, Hash, Eq, Serialize, PartialOrd, Ord)]
366#[serde(untagged)]
367pub enum Id<'a> {
368    /// Null
369    Null,
370    /// Numeric id
371    Number(u64),
372    /// String id
373    Str(Cow<'a, str>),
374}
375
376impl Id<'_> {
377    /// If the Id is a number, returns the associated number. Returns None otherwise.
378    pub fn as_number(&self) -> Option<&u64> {
379        match self {
380            Self::Number(n) => Some(n),
381            _ => None,
382        }
383    }
384
385    /// If the Id is a String, returns the associated str. Returns None otherwise.
386    pub fn as_str(&self) -> Option<&str> {
387        match self {
388            Self::Str(s) => Some(s.as_ref()),
389            _ => None,
390        }
391    }
392
393    /// Convert `Id<'a>` to `Id<'static>` so that it can be moved across threads.
394    ///
395    /// This can cause an allocation if the id is a string.
396    pub fn into_owned(self) -> Id<'static> {
397        match self {
398            Id::Null => Id::Null,
399            Id::Number(num) => Id::Number(num),
400            Id::Str(s) => Id::Str(Cow::Owned(s.into_owned())),
401        }
402    }
403}
404
405impl std::fmt::Display for Id<'_> {
406    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407        match self {
408            Id::Null => f.write_str("null"),
409            Id::Number(n) => f.write_str(&n.to_string()),
410            Id::Str(s) => f.write_str(s),
411        }
412    }
413}
414
415struct IdVisitor;
416
417impl<'de> Visitor<'de> for IdVisitor {
418    type Value = Id<'de>;
419
420    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
421        formatter.write_str("null, an unsigned integer or a string")
422    }
423
424    fn visit_unit<E>(self) -> Result<Self::Value, E> {
425        Ok(Id::Null)
426    }
427
428    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> {
429        Ok(Id::Number(v))
430    }
431
432    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
433    where
434        E: de::Error,
435    {
436        u64::try_from(v)
437            .map(Id::Number)
438            .map_err(|_| de::Error::invalid_value(Unexpected::Signed(v), &self))
439    }
440
441    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
442        Ok(Id::Str(Cow::Owned(v.to_owned())))
443    }
444
445    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> {
446        Ok(Id::Str(Cow::Borrowed(v)))
447    }
448
449    fn visit_string<E>(self, v: String) -> Result<Self::Value, E> {
450        Ok(Id::Str(Cow::Owned(v)))
451    }
452}
453
454/// Parses the id without buffering it: the untagged derive would first copy a peer-supplied array
455/// or object into an intermediate tree before rejecting it.
456impl<'de: 'a, 'a> Deserialize<'de> for Id<'a> {
457    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
458    where
459        D: Deserializer<'de>,
460    {
461        deserializer.deserialize_any(IdVisitor)
462    }
463}
464
465/// Maximum message length of an invalid-params error, which can quote request input.
466const MAX_INVALID_PARAMS_MESSAGE: usize = 1024;
467
468fn invalid_params(e: impl ToString) -> ErrorObjectOwned {
469    let mut message = e.to_string();
470    message.truncate(message.floor_char_boundary(MAX_INVALID_PARAMS_MESSAGE));
471    ErrorObject::owned(ErrorCode::InvalidParams.code(), message, None::<()>)
472}
473
474#[cfg(test)]
475mod test {
476    use super::*;
477    use crate::response::SubscriptionPayload;
478
479    #[test]
480    fn id_deserialization() {
481        let s = r#""2""#;
482        let deserialized: Id = serde_json::from_str(s).unwrap();
483        match deserialized {
484            Id::Str(ref cow) => {
485                assert!(matches!(cow, Cow::Borrowed(_)));
486                assert_eq!(cow, "2");
487            }
488            _ => panic!("Expected Id::Str"),
489        }
490
491        let s = r#"2"#;
492        let deserialized: Id = serde_json::from_str(s).unwrap();
493        assert_eq!(deserialized, Id::Number(2));
494
495        let s = r#""2x""#;
496        let deserialized: Id = serde_json::from_str(s).unwrap();
497        assert_eq!(deserialized, Id::Str(Cow::Borrowed("2x")));
498
499        let s = r#"[1337]"#;
500        assert!(serde_json::from_str::<Id>(s).is_err());
501
502        let s = r#"[null, 0, 2, "\"3"]"#;
503        let deserialized: Vec<Id> = serde_json::from_str(s).unwrap();
504        assert_eq!(
505            deserialized,
506            vec![Id::Null, Id::Number(0), Id::Number(2), Id::Str("\"3".into())]
507        );
508    }
509
510    #[test]
511    fn id_deserialization_accepts_scalars() {
512        let test_vector = [
513            ("null", Id::Null),
514            ("0", Id::Number(0)),
515            ("18446744073709551615", Id::Number(u64::MAX)),
516            (r#""""#, Id::Str("".into())),
517            (r#""abc""#, Id::Str("abc".into())),
518        ];
519
520        for (ser, expected) in test_vector {
521            let id: Id = serde_json::from_str(ser).unwrap();
522            assert_eq!(id, expected);
523            assert_eq!(serde_json::to_string(&id).unwrap(), ser);
524        }
525    }
526
527    #[test]
528    fn id_deserialization_borrows_only_when_possible() {
529        let id: Id = serde_json::from_str(r#""abc""#).unwrap();
530        assert!(matches!(id, Id::Str(Cow::Borrowed("abc"))));
531
532        // Escapes can't be borrowed from the input.
533        let id: Id = serde_json::from_str(r#""a\nc""#).unwrap();
534        assert!(matches!(id, Id::Str(Cow::Owned(_))));
535        assert_eq!(id, Id::Str("a\nc".into()));
536
537        let id = Id::deserialize(JsonValue::from("abc")).unwrap();
538        assert!(matches!(id, Id::Str(Cow::Owned(_))));
539    }
540
541    #[test]
542    fn id_deserialization_rejects_non_scalars() {
543        let test_vector = [
544            ("-1", "invalid value: integer `-1`, expected null, an unsigned integer or a string at line 1 column 2"),
545            ("1.5", "invalid type: floating point `1.5`, expected null, an unsigned integer or a string at line 1 column 3"),
546            ("true", "invalid type: boolean `true`, expected null, an unsigned integer or a string at line 1 column 4"),
547            ("[1]", "invalid type: sequence, expected null, an unsigned integer or a string at line 1 column 1"),
548            (r#"{"a":1}"#, "invalid type: map, expected null, an unsigned integer or a string at line 1 column 1"),
549        ];
550
551        for (ser, expected) in test_vector {
552            let err = serde_json::from_str::<Id>(ser).unwrap_err();
553            assert_eq!(err.to_string(), expected);
554        }
555    }
556
557    #[test]
558    fn id_serialization() {
559        let d = vec![
560            Id::Null,
561            Id::Number(0),
562            Id::Number(2),
563            Id::Number(3),
564            Id::Str("\"3".into()),
565            Id::Str("test".into()),
566        ];
567        let serialized = serde_json::to_string(&d).unwrap();
568        assert_eq!(serialized, r#"[null,0,2,3,"\"3","test"]"#);
569    }
570
571    #[test]
572    fn params_parse() {
573        let none = Params::new(None);
574        assert!(none.sequence().next::<u64>().is_err());
575        assert!(none.parse::<Option<u64>>().is_ok());
576        assert_eq!(none.len_bytes(), 0);
577
578        let array_params = Params::new(Some("[1, 2, 3]"));
579        assert_eq!(array_params.len_bytes(), 9);
580        let arr: Result<[u64; 3], _> = array_params.parse();
581        assert!(arr.is_ok());
582
583        let mut seq = array_params.sequence();
584
585        assert_eq!(seq.next::<u64>().unwrap(), 1);
586        assert_eq!(seq.next::<u64>().unwrap(), 2);
587        assert_eq!(seq.next::<u64>().unwrap(), 3);
588        assert!(seq.next::<u64>().is_err());
589
590        let array_one = Params::new(Some("[1]"));
591        assert_eq!(array_one.len_bytes(), 3);
592        let one: Result<u64, _> = array_one.one();
593        assert!(one.is_ok());
594
595        let object_params = Params::new(Some(r#"{"beef":99,"dinner":0}"#));
596        assert_eq!(object_params.len_bytes(), 22);
597        let obj: Result<JsonValue, _> = object_params.parse();
598        assert!(obj.is_ok());
599    }
600
601    #[test]
602    fn params_parse_empty_json() {
603        let array_params = Params::new(Some("[]"));
604        let arr: Result<Vec<u64>, _> = array_params.parse();
605        assert!(arr.is_ok());
606
607        let obj_params = Params::new(Some("{}"));
608        let obj: Result<JsonValue, _> = obj_params.parse();
609        assert!(obj.is_ok());
610    }
611
612    #[test]
613    fn params_sequence_borrows() {
614        let params = Params::new(Some(r#"["foo", "bar"]"#));
615        let mut seq = params.sequence();
616
617        assert_eq!(seq.next::<&str>().unwrap(), "foo");
618        assert_eq!(seq.next::<&str>().unwrap(), "bar");
619        assert!(seq.next::<&str>().is_err());
620
621        // It's ok to parse the params again.
622        let params: (&str, &str) = params.parse().unwrap();
623        assert_eq!(params, ("foo", "bar"));
624    }
625
626    #[test]
627    fn two_point_zero_serde_works() {
628        let initial_ser = r#""2.0""#;
629        // The fact that it was deserialized is enough.
630        let two_point_zero: TwoPointZero = serde_json::from_str(initial_ser).unwrap();
631        let serialized = serde_json::to_string(&two_point_zero).unwrap();
632        assert_eq!(serialized, initial_ser);
633    }
634
635    #[test]
636    fn subscription_id_serde_works() {
637        let test_vector =
638            &[("42", SubscriptionId::Num(42)), (r#""one""#, SubscriptionId::Str("one".into()))];
639
640        for (initial_ser, expected) in test_vector {
641            let id: SubscriptionId = serde_json::from_str(initial_ser).unwrap();
642            assert_eq!(&id, expected);
643            let serialized = serde_json::to_string(&id).unwrap();
644            assert_eq!(&serialized, initial_ser);
645        }
646    }
647
648    #[test]
649    fn subscription_id_deserialization_borrows_only_when_possible() {
650        let id: SubscriptionId = serde_json::from_str(r#""abc""#).unwrap();
651        assert!(matches!(id, SubscriptionId::Str(Cow::Borrowed("abc"))));
652
653        // Escapes can't be borrowed from the input.
654        let id: SubscriptionId = serde_json::from_str(r#""a\nc""#).unwrap();
655        assert!(matches!(id, SubscriptionId::Str(Cow::Owned(_))));
656        assert_eq!(id, SubscriptionId::Str("a\nc".into()));
657
658        let id = SubscriptionId::deserialize(JsonValue::from("abc")).unwrap();
659        assert!(matches!(id, SubscriptionId::Str(Cow::Owned(_))));
660
661        let id: SubscriptionId = serde_json::from_str("18446744073709551615").unwrap();
662        assert_eq!(id, SubscriptionId::Num(u64::MAX));
663    }
664
665    #[test]
666    fn subscription_id_deserialization_rejects_non_scalars() {
667        let test_vector = [
668            ("null", "invalid type: null, expected an unsigned integer or a string at line 1 column 4"),
669            ("-1", "invalid value: integer `-1`, expected an unsigned integer or a string at line 1 column 2"),
670            ("1.5", "invalid type: floating point `1.5`, expected an unsigned integer or a string at line 1 column 3"),
671            ("true", "invalid type: boolean `true`, expected an unsigned integer or a string at line 1 column 4"),
672            ("[1]", "invalid type: sequence, expected an unsigned integer or a string at line 1 column 1"),
673            (r#"{"a":1}"#, "invalid type: map, expected an unsigned integer or a string at line 1 column 1"),
674        ];
675
676        for (ser, expected) in test_vector {
677            let err = serde_json::from_str::<SubscriptionId>(ser).unwrap_err();
678            assert_eq!(err.to_string(), expected);
679        }
680
681        // The unsubscribe path parses the id out of the params.
682        let params = Params::new(Some("[[0,0,0]]"));
683        assert!(params.one::<SubscriptionId>().is_err());
684    }
685
686    #[test]
687    fn subscription_params_serialize_work() {
688        let ser = serde_json::to_string(&SubscriptionPayload {
689            subscription: SubscriptionId::Num(12),
690            result: "goal",
691        })
692        .unwrap();
693        let exp = r#"{"subscription":12,"result":"goal"}"#;
694        assert_eq!(ser, exp);
695    }
696
697    #[test]
698    fn subscription_params_deserialize_work() {
699        let ser = r#"{"subscription":"9","result":"offside"}"#;
700        assert!(
701            serde_json::from_str::<SubscriptionPayload<()>>(ser).is_err(),
702            "invalid type should not be deserializable"
703        );
704        let dsr: SubscriptionPayload<JsonValue> = serde_json::from_str(ser).unwrap();
705        assert_eq!(dsr.subscription, SubscriptionId::Str("9".into()));
706        assert_eq!(dsr.result, serde_json::json!("offside"));
707    }
708
709    #[test]
710    fn params_sequence_optional_ignore_empty() {
711        let params = Params::new(Some(r#"["foo", "bar"]"#));
712        let mut seq = params.sequence();
713
714        assert_eq!(seq.optional_next::<&str>().unwrap(), Some("foo"));
715        assert_eq!(seq.optional_next::<&str>().unwrap(), Some("bar"));
716
717        let params = Params::new(Some(r#"[]"#));
718        let mut seq = params.sequence();
719        assert!(seq.optional_next::<&str>().unwrap().is_none());
720
721        let params = Params::new(Some(r#"   []		"#));
722        let mut seq = params.sequence();
723        assert!(seq.optional_next::<&str>().unwrap().is_none());
724
725        let params = Params::new(Some(r#"{}"#));
726        let mut seq = params.sequence();
727        assert!(seq.optional_next::<&str>().is_err(), "JSON object not supported by RpcSequence");
728
729        let params = Params::new(Some(r#"[12, "[]", [], {}]"#));
730        let mut seq = params.sequence();
731        assert_eq!(seq.optional_next::<u64>().unwrap(), Some(12));
732        assert_eq!(seq.optional_next::<&str>().unwrap(), Some("[]"));
733        assert_eq!(seq.optional_next::<Vec<u8>>().unwrap(), Some(vec![]));
734        assert_eq!(seq.optional_next::<serde_json::Value>().unwrap(), Some(serde_json::json!({})));
735    }
736
737    #[test]
738    fn params_sequence_optional_nesting_works() {
739        let nested = Params::new(Some(r#"[1, [2], [3, 4], [[5], [6,7], []], {"named":7}]"#));
740        let mut seq = nested.sequence();
741        assert_eq!(seq.optional_next::<i8>().unwrap(), Some(1));
742        assert_eq!(seq.optional_next::<[i8; 1]>().unwrap(), Some([2]));
743        assert_eq!(seq.optional_next::<Vec<u16>>().unwrap(), Some(vec![3, 4]));
744        assert_eq!(
745            seq.optional_next::<Vec<Vec<u32>>>().unwrap(),
746            Some(vec![vec![5], vec![6, 7], vec![]])
747        );
748        assert_eq!(
749            seq.optional_next::<serde_json::Value>().unwrap(),
750            Some(serde_json::json!({"named":7}))
751        );
752    }
753
754    #[test]
755    fn invalid_params_message_is_truncated_at_a_char_boundary() {
756        // serde quotes the whole mismatched string in its error.
757        let params = format!(r#"["{}"]"#, "🦀".repeat(MAX_INVALID_PARAMS_MESSAGE));
758        let err = Params::new(Some(&params)).sequence().next::<u64>().unwrap_err();
759        assert!(err.data().is_none());
760        assert_eq!(err.message(), format!("invalid type: string \"{}", "🦀".repeat(250)));
761    }
762}