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
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use std::sync::Arc;

/*
 * =======
 * Request
 * =======
 */
/// Represents each JSON RPC request.
// Deserializing structs containing flattened RawValue always fails.
// https://github.com/serde-rs/json/issues/599
//
// So currently we wrap `method` and `params` by `Arc` separately.
#[derive(Debug, Clone, Deserialize)]
pub struct Request {
    jsonrpc: Version,
    id: Id,
    method: Arc<String>,
    params: Arc<Option<Box<RawValue>>>,
}

#[derive(PartialEq, Debug, Clone, Deserialize, Serialize)]
pub enum Version {
    #[serde(rename = "2.0")]
    V2,
}

#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Id {
    String(Arc<String>),
    Number(i64),
    Null,
}

impl From<&str> for Id {
    fn from(id: &str) -> Self {
        Id::String(Arc::new(id.to_string()))
    }
}

impl From<String> for Id {
    fn from(id: String) -> Self {
        Id::String(Arc::new(id))
    }
}

impl From<i64> for Id {
    fn from(id: i64) -> Self {
        Id::Number(id)
    }
}

impl Request {
    pub fn id(&self) -> Id {
        self.id.clone()
    }

    pub fn method(&self) -> &str {
        self.method.as_str()
    }

    pub fn deserialize_param<'de, T>(&'de self) -> Result<T, anyhow::Error>
    where
        T: Deserialize<'de>,
    {
        match self.params.as_ref() {
            Some(params) => Ok(serde_json::from_str(params.get())?),
            None => Err(anyhow::anyhow!("No parameter is presented")),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn deserialize_by_name_request() {
        let req_str = r#"{
            "jsonrpc": "2.0",
            "method": "op",
            "params": { "lhs": 24, "rhs": 12, "op": "+"},
            "id": 42
        }"#;
        let req = serde_json::from_str::<Request>(req_str).unwrap();
        assert_eq!(req.id(), Id::Number(42));
        assert_eq!(req.method(), "op");

        #[derive(PartialEq, Eq, Debug, Deserialize)]
        struct Param {
            lhs: i32,
            rhs: i32,
            op: String,
        }

        let param = req.deserialize_param::<Param>().unwrap();
        assert_eq!(
            param,
            Param {
                lhs: 24,
                rhs: 12,
                op: "+".to_string()
            }
        );
    }

    #[test]
    fn deserialize_by_pos_request() {
        let req_str = r#"{
            "jsonrpc": "2.0",
            "method": "op",
            "params": [24, 12, "+"],
            "id": 42
        }"#;
        let req = serde_json::from_str::<Request>(req_str).unwrap();
        assert_eq!(req.id(), Id::Number(42));
        assert_eq!(req.method(), "op");

        let (lhs, rhs, op) = req.deserialize_param::<(i32, i32, String)>().unwrap();
        assert_eq!(lhs, 24);
        assert_eq!(rhs, 12);
        assert_eq!(op, "+".to_string());
    }

    #[test]
    fn deserialize_string_id() {
        let req_str = r#"{
            "jsonrpc": "2.0",
            "method": "op",
            "id": "string identifier"
        }"#;
        let req = serde_json::from_str::<Request>(req_str).unwrap();
        assert_eq!(req.id(), Id::from("string identifier"));
        assert_eq!(req.id(), Id::from(String::from("string identifier")));
    }

    #[test]
    fn deserialize_number_id() {
        let req_str = r#"{
            "jsonrpc": "2.0",
            "method": "op",
            "id": -1234
        }"#;
        let req = serde_json::from_str::<Request>(req_str).unwrap();
        assert_eq!(req.id(), Id::from(-1234));
    }

    #[test]
    fn deserialize_null_id() {
        let req_str = r#"{
            "jsonrpc": "2.0",
            "method": "op",
            "id": null
        }"#;
        let req = serde_json::from_str::<Request>(req_str).unwrap();
        assert_eq!(req.id(), Id::Null);
    }

    #[test]
    fn deserialize_no_id_should_fail() {
        let req_str = r#"{
            "jsonrpc": "2.0",
            "method": "op"
        }"#;
        assert!(serde_json::from_str::<Request>(req_str).is_err());
    }

    #[test]
    fn deserialize_bad_id() {
        let req_str = r#"{
            "jsonrpc": "2.0",
            "method": "op",
            "id": 1.0
        }"#;
        assert!(serde_json::from_str::<Request>(req_str).is_err());
    }
}