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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
use serde::{de::DeserializeOwned, Deserialize,Serialize};

#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestId {
    Number(isize),
    String(String),
}

impl Default for RequestId {
    fn default() -> Self {
        Self::Number(0)
    }
}

const JSON_RPC_VER: &'static str = "2.0";

#[derive(Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Message {
    #[serde(skip_deserializing)]
    #[serde(default = "json_ver")]
    pub jsonrpc: &'static str,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<RequestId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<Error>,
}

impl Message {
    pub fn is_notification(&self) -> bool {
        self.method.is_some() && self.id.is_none()
    }

    pub fn is_response(&self) -> bool {
        self.method.is_none()
    }

    pub fn into_request(self) -> Request<serde_json::Value> {
        Request {
            jsonrpc: JSON_RPC_VER,
            method: self.method.unwrap(),
            id: self.id,
            params: self.params,
        }
    }

    pub fn into_response(self) -> Response<serde_json::Value> {
        Response {
            jsonrpc: self.jsonrpc,
            id: self.id.unwrap(),
            error: self.error,
            result: self.result,
        }
    }
}

#[derive(Default, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Request<T = ()> {
    #[serde(skip_deserializing)]
    #[serde(default = "json_ver")]
    pub jsonrpc: &'static str,
    pub method: String,

    pub id: Option<RequestId>,
    pub params: Option<T>,
}

impl<T: Serialize + DeserializeOwned> Request<T> {
    pub fn new() -> Self {
        Self {
            jsonrpc: JSON_RPC_VER,
            method: "".into(),
            id: None,
            params: None,
        }
    }

    pub fn with_method(self, method: &str) -> Self {
        Self {
            method: method.into(),
            ..self
        }
    }

    pub fn with_id(self, id: Option<RequestId>) -> Self {
        Self { id, ..self }
    }

    pub fn with_params(self, params: Option<T>) -> Self {
        Self { params, ..self }
    }

    pub fn into_message(self) -> Message {
        Message {
            jsonrpc: JSON_RPC_VER,
            method: Some(self.method),
            id: self.id,
            params: match self.params {
                None => None,
                Some(p) => Some(serde_json::to_value(p).unwrap()),
            },
            result: None,
            error: None,
        }
    }
}

impl Request<serde_json::Value> {
    pub fn into_params<P: DeserializeOwned>(self) -> Result<Request<P>, serde_json::Error> {
        match self.params {
            None => Ok(Request {
                id: self.id,
                jsonrpc: JSON_RPC_VER,
                method: self.method,
                params: None,
            }),
            Some(v) => match serde_json::from_value(v) {
                Ok(params) => Ok(Request {
                    id: self.id,
                    jsonrpc: JSON_RPC_VER,
                    method: self.method,
                    params: Some(params),
                }),
                Err(e) => Err(e),
            },
        }
    }
}

#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Response<R = ()> {
    #[serde(skip_deserializing)]
    #[serde(default = "json_ver")]
    pub jsonrpc: &'static str,

    pub id: RequestId,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<R>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<Error>,
}

impl<R> Response<R> {
    pub fn with_request_id(self, id: RequestId) -> Self {
        Response { id, ..self }
    }
}

impl<R: Serialize + DeserializeOwned> Response<R> {
    pub fn success(data: R) -> Self {
        Response {
            jsonrpc: JSON_RPC_VER,
            id: RequestId::default(),
            result: Some(data),
            error: None,
        }
    }

    pub fn into_result(self) -> Result<R, Error> {
        if let Some(r) = self.result {
            Ok(r)
        } else {
            Err(self.error.unwrap())
        }
    }

    pub fn into_message(self) -> Message {
        Message {
            jsonrpc: JSON_RPC_VER,
            method: None,
            id: Some(self.id),
            params: None,
            result: match self.result {
                None => None,
                Some(p) => Some(serde_json::to_value(p).unwrap()),
            },
            error: self.error,
        }
    }
}

impl Response<serde_json::Value> {
    pub fn into_params<P: DeserializeOwned>(self) -> Response<P> {
        Response {
            jsonrpc: self.jsonrpc,
            id: self.id,
            result: match self.result {
                None => None,
                Some(v) => Some(serde_json::from_value(v).unwrap()),
            },
            error: self.error,
        }
    }
}

impl Response<()> {
    pub fn error(err: Error) -> Self {
        Response {
            jsonrpc: JSON_RPC_VER,
            id: RequestId::default(),
            result: None,
            error: Some(err),
        }
    }
}

impl<E, R> From<Result<R, E>> for Response<R>
where
    R: Serialize + for<'r> Deserialize<'r>,
    E: Into<Error>,
{
    fn from(res: Result<R, E>) -> Self {
        match res {
            Ok(r) => Response {
                jsonrpc: JSON_RPC_VER,
                id: RequestId::default(),
                result: Some(r),
                error: None,
            },
            Err(err) => Response {
                jsonrpc: JSON_RPC_VER,
                id: RequestId::default(),
                result: None,
                error: Some(err.into()),
            },
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Error {
    pub code: i32,
    pub message: String,
    pub data: Option<serde_json::Value>,
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RPC error ({}): {}", self.code, self.message)
    }
}

impl Error {
    pub fn new(message: &str) -> Self {
        Error {
            code: 0,
            message: message.into(),
            data: None,
        }
    }

    pub fn with_code(mut self, code: i32) -> Self {
        self.code = code;
        self
    }

    pub fn with_data(mut self, data: impl Serialize) -> Self {
        self.data = Some(serde_json::to_value(data).unwrap());
        self
    }

    pub fn parse() -> Error {
        Error {
            code: -32700,
            message: "Parse error".into(),
            data: None,
        }
    }

    pub fn invalid_request() -> Error {
        Error {
            code: -32600,
            message: "Invalid request".into(),
            data: None,
        }
    }

    pub fn method_not_found() -> Error {
        Error {
            code: -32601,
            message: "Method not found".into(),
            data: None,
        }
    }

    pub fn invalid_params() -> Error {
        Error {
            code: -32602,
            message: "Invalid params".into(),
            data: None,
        }
    }

    pub fn internal_error() -> Error {
        Error {
            code: -32603,
            message: "Internal error".into(),
            data: None,
        }
    }

    pub fn server_not_initialized() -> Error {
        Error {
            code: -32002,
            message: "Server not initialized".into(),
            data: None,
        }
    }

    pub fn request_cancelled() -> Error {
        Error {
            code: -32800,
            message: "Request cancelled".into(),
            data: None,
        }
    }

    pub fn content_modified() -> Error {
        Error {
            code: -32801,
            message: "Content modified".into(),
            data: None,
        }
    }

    pub fn server(code: i32) -> Error {
        if code < -32000 || code > -32099 {
            panic!("code must be between -32000 and -32099")
        }

        Error {
            code: -32603,
            message: "Server error".into(),
            data: None,
        }
    }
}

impl std::error::Error for Error {}

fn json_ver() -> &'static str {
    JSON_RPC_VER
}