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
use crate::req::Version;
use hyper::Body;
use serde::Serialize;
use serde_json::Value;
use std::borrow::Cow;

/*
 * ========
 * Response
 * ========
 */
#[derive(Serialize)]
struct Response {
    jsonrpc: Version,
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<u64>,
    #[serde(flatten)]
    content: ResponseContent,
}

impl Response {
    fn new(id: Option<u64>, content: ResponseContent) -> Response {
        Response {
            jsonrpc: Version::V2,
            id,
            content,
        }
    }

    /// Currently `warp` does not expose `Reply` trait (it is guarded).
    /// So we need to convert this into something that implements `Reply`.
    fn into_reply(self) -> anyhow::Result<impl warp::Reply> {
        let body = Body::from(serde_json::to_vec(&self)?);
        Ok(http::Response::builder()
            .status(200)
            .header("Content-Type", "application/json")
            .body(body)
            .unwrap())
    }
}

pub struct Builder {
    id: Option<u64>,
}

impl Builder {
    pub(crate) fn new(id: Option<u64>) -> Builder {
        Builder { id }
    }

    pub fn success<S>(self, content: S) -> anyhow::Result<impl warp::Reply>
    where
        S: Serialize + 'static,
    {
        Response::new(self.id, ResponseContent::Success(Box::new(content))).into_reply()
    }

    pub fn error(self, error: Error) -> anyhow::Result<impl warp::Reply> {
        Response::new(self.id, ResponseContent::Error(error)).into_reply()
    }
}

#[derive(Serialize)]
enum ResponseContent {
    #[serde(rename = "result")]
    Success(Box<dyn erased_serde::Serialize>),
    #[serde(rename = "error")]
    Error(Error),
}

#[derive(PartialEq, Debug, Serialize)]
pub struct Error {
    pub code: i64,
    pub message: Cow<'static, str>,
    pub data: Option<Value>,
}

impl Error {
    pub const PARSE_ERROR: Error = Error {
        code: -32700,
        message: Cow::Borrowed("Parse error"),
        data: None,
    };

    pub const INVALID_REQUEST: Error = Error {
        code: -32600,
        message: Cow::Borrowed("Invalid Request"),
        data: None,
    };

    pub const METHOD_NOT_FOUND: Error = Error {
        code: -32601,
        message: Cow::Borrowed("Method not found"),
        data: None,
    };

    pub const INVALID_PARAMS: Error = Error {
        code: -32602,
        message: Cow::Borrowed("Invalid params"),
        data: None,
    };

    pub const INTERNAL_ERROR: Error = Error {
        code: -32603,
        message: Cow::Borrowed("Internal error"),
        data: None,
    };

    pub fn custom<S>(code: i64, message: S, data: Option<impl Serialize>) -> Error
    where
        Cow<'static, str>: From<S>,
    {
        Error {
            code,
            message: message.into(),
            data: data.map(|s| serde_json::to_value(s).unwrap()),
        }
    }
}

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

    #[test]
    fn serialize_response() {
        #[derive(Deserialize, PartialEq, Eq, Debug)]
        struct Expected {
            jsonrpc: String,
            result: String,
            id: usize,
        }

        let res = Response::new(Some(42), ResponseContent::Success(Box::new("The answer")));
        let res_str = serde_json::to_string(&res).unwrap();
        let deserialized = serde_json::from_str::<Expected>(res_str.as_str()).unwrap();

        let expected = Expected {
            jsonrpc: "2.0".to_string(),
            result: "The answer".to_string(),
            id: 42,
        };

        assert_eq!(deserialized, expected);
    }

    #[test]
    fn serialize_err_response() {
        #[derive(Deserialize, PartialEq, Eq, Debug)]
        struct Expected {
            jsonrpc: String,
            error: ExpectedError,
            id: usize,
        }
        #[derive(Deserialize, PartialEq, Eq, Debug)]
        struct ExpectedError {
            code: isize,
            message: String,
        }

        let res = Response::new(Some(42), ResponseContent::Error(Error::INVALID_PARAMS));
        let res_str = serde_json::to_string(&res).unwrap();
        let deserialized = serde_json::from_str::<Expected>(res_str.as_str()).unwrap();

        let expected = Expected {
            jsonrpc: "2.0".to_string(),
            error: ExpectedError {
                code: -32602,
                message: "Invalid params".to_string(),
            },
            id: 42,
        };

        assert_eq!(deserialized, expected);
    }

    #[test]
    fn serialize_no_id_response_shoud_not_contain_id_field() {
        let res = Response::new(None, ResponseContent::Success(Box::new(42)));
        let res_str = serde_json::to_string(&res).unwrap();

        assert!(!res_str.contains("id"));
    }
}