1use 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#[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#[derive(Clone, Debug)]
90pub struct Params<'a>(Option<Cow<'a, str>>);
91
92impl<'a> Params<'a> {
93 pub fn new(raw: Option<&'a str>) -> Self {
95 Self(raw.map(|r| r.trim().into()))
96 }
97
98 pub fn sequence(&self) -> ParamsSequence<'_> {
104 let json = match self.0.as_ref() {
105 Some(json) if json == "[]" => "",
107 Some(json) => json,
108 None => "",
109 };
110 ParamsSequence(json)
111 }
112
113 pub fn parse<T>(&'a self) -> Result<T, ErrorObjectOwned>
115 where
116 T: Deserialize<'a>,
117 {
118 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 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 pub fn into_owned(self) -> Params<'static> {
136 Params(self.0.map(|s| Cow::Owned(s.into_owned())))
137 }
138
139 pub fn len_bytes(&self) -> usize {
141 match self.0 {
142 Some(ref cow) => cow.len(),
143 None => 0,
144 }
145 }
146
147 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#[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 #[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 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#[derive(Debug, PartialEq, Clone, Hash, Eq, Serialize)]
258#[serde(untagged)]
259pub enum SubscriptionId<'a> {
260 Num(u64),
262 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 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
353impl<'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#[derive(Debug, PartialEq, Clone, Hash, Eq, Serialize, PartialOrd, Ord)]
366#[serde(untagged)]
367pub enum Id<'a> {
368 Null,
370 Number(u64),
372 Str(Cow<'a, str>),
374}
375
376impl Id<'_> {
377 pub fn as_number(&self) -> Option<&u64> {
379 match self {
380 Self::Number(n) => Some(n),
381 _ => None,
382 }
383 }
384
385 pub fn as_str(&self) -> Option<&str> {
387 match self {
388 Self::Str(s) => Some(s.as_ref()),
389 _ => None,
390 }
391 }
392
393 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
454impl<'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
465const 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 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 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 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 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 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 let params = format!(r#"["{}"]"#, "🦀".repeat(MAX_INVALID_PARAMS_MESSAGE));
758 let err = Params::new(Some(¶ms)).sequence().next::<u64>().unwrap_err();
759 assert!(err.data().is_none());
760 assert_eq!(err.message(), format!("invalid type: string \"{}", "🦀".repeat(250)));
761 }
762}