request.rs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. //! Request Message
  2. //!
  3. //! All messages that clients can send to relayers are abstracted in this mod
  4. use crate::{client, common::SerializeDeserialize, types};
  5. use serde::{
  6. de::{self, Deserializer},
  7. ser::{self, SerializeSeq, Serializer},
  8. Deserialize,
  9. };
  10. use std::collections::VecDeque;
  11. custom_derive! {
  12. #[derive(Debug, Clone, EnumFromInner)]
  13. /// Request Messages
  14. ///
  15. /// All requests from clients to relayer are abstracted in this struct
  16. pub enum Request {
  17. /// Close a subscription
  18. Close(client::Close),
  19. /// An Event from a client. This is when a client wants to publish an
  20. /// event. The event must be signed.
  21. Event(client::Event),
  22. /// Creates a subscription. Client tells the relayer which kind of events
  23. /// they'd like to hear about
  24. Request(client::Subscribe),
  25. }
  26. }
  27. impl Request {
  28. /// Returns the current message as a Request, if possible
  29. pub fn as_request(&self) -> Option<&client::Subscribe> {
  30. match self {
  31. Self::Request(x) => Some(x),
  32. _ => None,
  33. }
  34. }
  35. /// Returns the current message as a close if possible
  36. pub fn as_close(&self) -> Option<&client::Close> {
  37. match self {
  38. Self::Close(t) => Some(t),
  39. _ => None,
  40. }
  41. }
  42. /// Returns the current message as an event from the client, if possible
  43. pub fn as_event(&self) -> Option<&types::Event> {
  44. match self {
  45. Self::Event(event) => Some(&**event),
  46. _ => None,
  47. }
  48. }
  49. }
  50. impl ser::Serialize for Request {
  51. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  52. where
  53. S: Serializer,
  54. {
  55. let values = match self {
  56. Self::Close(t) => t.serialize(),
  57. Self::Event(t) => t.serialize(),
  58. Self::Request(t) => t.serialize(),
  59. }
  60. .map_err(ser::Error::custom)?;
  61. let mut seq = serializer.serialize_seq(Some(values.len()))?;
  62. for value in values.iter() {
  63. seq.serialize_element(value)?;
  64. }
  65. seq.end()
  66. }
  67. }
  68. impl<'de> de::Deserialize<'de> for Request {
  69. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  70. where
  71. D: Deserializer<'de>,
  72. {
  73. let mut array: VecDeque<serde_json::Value> = Deserialize::deserialize(deserializer)?;
  74. if array.is_empty() {
  75. return Err(de::Error::custom(
  76. "Invalid array length, expecting at least one",
  77. ));
  78. }
  79. let tag = array
  80. .remove(0)
  81. .ok_or_else(|| de::Error::custom("Invalid array length, expecting at least one"))?;
  82. let tag = tag
  83. .as_str()
  84. .ok_or_else(|| de::Error::custom("Invalid type for element 0 of the array"))?;
  85. match tag {
  86. "EVENT" => Ok(client::Event::deserialize(array)
  87. .map_err(de::Error::custom)?
  88. .into()),
  89. "CLOSE" => Ok(client::Close::deserialize(array)
  90. .map_err(de::Error::custom)?
  91. .into()),
  92. "REQ" => Ok(client::Subscribe::deserialize(array)
  93. .map_err(de::Error::custom)?
  94. .into()),
  95. tag => Err(de::Error::custom(format!("{} is not a support tag", tag))),
  96. }
  97. }
  98. }
  99. #[cfg(test)]
  100. mod test {
  101. use super::*;
  102. #[test]
  103. fn unsupported() {
  104. let json = "[\"CLOSEX\", \"foo\"]";
  105. let message: Result<Request, _> = serde_json::from_str(json);
  106. assert!(message.is_err());
  107. }
  108. #[test]
  109. fn close() {
  110. let json = "[\"CLOSE\", \"foo\"]";
  111. let message: Request = serde_json::from_str(json).expect("valid message");
  112. let subscription_id = message.as_close().expect("valid subscription_id");
  113. assert_eq!("foo".to_owned(), subscription_id.to_string());
  114. }
  115. }