Skip to main content

sv1_api/
json_rpc.rs

1//! https://www.jsonrpc.org/specification#response_object
2use serde::{Deserialize, Serialize};
3use std::{fmt, fmt::Display};
4
5#[derive(Clone, Serialize, Deserialize, Debug)]
6#[serde(untagged)]
7pub enum Message {
8    StandardRequest(StandardRequest),
9    Notification(Notification),
10    OkResponse(Response),
11    ErrorResponse(Response),
12}
13
14impl Message {
15    // TODO: Remove this. Keeping this in to avoid upgrading the major version of the crate.
16    pub fn is_response(&self) -> bool {
17        match self {
18            Message::StandardRequest(_) => false,
19            Message::Notification(_) => false,
20            Message::OkResponse(_) => true,
21            Message::ErrorResponse(_) => true,
22        }
23    }
24}
25
26impl Display for Message {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Message::StandardRequest(sr) => write!(f, "{}", sr),
30            Message::Notification(n) => write!(f, "{}", n),
31            Message::OkResponse(r) => write!(f, "{}", r),
32            Message::ErrorResponse(r) => write!(f, "{}", r),
33        }
34    }
35}
36
37#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
38pub struct StandardRequest {
39    pub id: u64,
40    pub method: String,
41    pub params: serde_json::Value,
42}
43
44impl fmt::Display for StandardRequest {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        let params =
47            serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string());
48        write!(
49            f,
50            "{{ id: {}, method: {}, params: {} }}",
51            self.id, self.method, params
52        )
53    }
54}
55
56#[derive(Clone, Serialize, Deserialize, Debug)]
57pub struct Notification {
58    pub method: String,
59    pub params: serde_json::Value,
60}
61
62impl fmt::Display for Notification {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        let params =
65            serde_json::to_string_pretty(&self.params).unwrap_or_else(|_| self.params.to_string());
66
67        write!(f, "{{ method: \"{}\", params: {} }}", self.method, params)
68    }
69}
70
71#[derive(Clone, Serialize, Deserialize, Debug)]
72pub struct Response {
73    pub id: u64,
74    pub error: Option<JsonRpcError>,
75    pub result: serde_json::Value,
76}
77
78impl fmt::Display for Response {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        let result =
81            serde_json::to_string_pretty(&self.result).unwrap_or_else(|_| self.result.to_string());
82
83        if let Some(err) = &self.error {
84            write!(
85                f,
86                "{{ id: {}, error: {:?}, result: {} }}",
87                self.id, err, result
88            )
89        } else {
90            write!(f, "{{ id: {}, result: {} }}", self.id, result)
91        }
92    }
93}
94
95#[derive(Clone, Serialize, Deserialize, Debug)]
96pub struct JsonRpcError {
97    pub code: i32, // json do not specify precision which one should be used?
98    pub message: String,
99    pub data: Option<serde_json::Value>,
100}
101
102impl From<Response> for Message {
103    fn from(res: Response) -> Self {
104        if res.error.is_some() {
105            Message::ErrorResponse(res)
106        } else {
107            Message::OkResponse(res)
108        }
109    }
110}
111
112impl From<StandardRequest> for Message {
113    fn from(sr: StandardRequest) -> Self {
114        Message::StandardRequest(sr)
115    }
116}
117
118impl From<Notification> for Message {
119    fn from(n: Notification) -> Self {
120        Message::Notification(n)
121    }
122}