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
use bytes::{BufMut, Bytes};
use serde_derive::{Deserialize, Serialize};
use serde_json::Value;

use crate::parse::generate_response_headers;
use crate::parse::split_bytes;
use crate::types::Params;

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    jsonrpc: String,
    method: String,
    id: String,
    result: Params,
}

impl Response {
    pub fn new(method: String, id: String, result: Params) -> Self {
        let jsonrpc = "2.0".into();

        Response {
            jsonrpc,
            method,
            id,
            result,
        }
    }

    pub fn parse(bytes: Bytes) -> Result<Self, Error> {
        split_bytes(bytes).and_then(|value| Response::parse_from_json(value))
    }

    pub fn parse_from_json_bytes(bytes: Bytes) -> Result<Self, Error> {
        serde_json::from_slice(&bytes[..])
            .or(Err(Error::ParseError(None)))
            .and_then(|value| Response::parse_from_json(value))
    }

    pub fn parse_from_json(value: Value) -> Result<Self, Error> {
        let id = if let Some(id) = value.get("id") {
            id.as_str().unwrap().into()
        } else {
            " ".into()
        };

        if value.get("method").is_none() {
            return Err(Error::MethodNotFound("".into(), id));
        }
        let method = value.get("method").unwrap().as_str().unwrap().into();

        if value.get("result").is_some() {
            let jsonrpc = "2.0".into();
            let result = value.get("result").unwrap().clone();

            return Ok(Response {
                jsonrpc,
                method,
                id,
                result,
            });
        }

        if value.get("error").is_some() {
            let code = value
                .get("error")
                .unwrap()
                .get("code")
                .map_or(-32600, |v| v.as_i64().map_or(-32600, |v| v));

            let message = value
                .get("error")
                .unwrap()
                .get("message")
                .map_or("Invalid Request", |v| {
                    v.as_str().map_or("Invalid Request", |v| v)
                })
                .into();
            return Err(Error::ErrorResponse(method, id, code, message));
        }

        return Err(Error::InvalidResponse(method, id));
    }

    pub fn deparse(&self) -> Bytes {
        let body = serde_json::to_string(&self).unwrap();

        let body_bytes = body.as_bytes();

        let mut headers = generate_response_headers(body_bytes.len());
        headers.put(body_bytes);
        headers.freeze()
    }

    pub fn result(&self) -> &Params {
        &self.result
    }

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

    pub fn id(&self) -> &String {
        &self.id
    }
}

#[derive(Serialize, Deserialize)]
struct ErrorValue {
    code: i64,
    message: String,
}

impl ErrorValue {
    fn new(code: i64, message: String) -> Self {
        ErrorValue { code, message }
    }
}

#[derive(Serialize, Deserialize)]
struct ErrorOnlyResponse {
    jsonrpc: String,
    error: ErrorValue,
}

#[derive(Serialize, Deserialize)]
struct ErrorResponse {
    jsonrpc: String,
    method: String,
    id: String,
    error: ErrorValue,
}

impl ErrorOnlyResponse {
    fn new(error: ErrorValue) -> Self {
        let jsonrpc = "2.0".into();
        ErrorOnlyResponse { jsonrpc, error }
    }
}

impl ErrorResponse {
    fn new(method: String, id: String, error: ErrorValue) -> Self {
        let jsonrpc = "2.0".into();
        ErrorResponse {
            jsonrpc,
            method,
            id,
            error,
        }
    }
}

// (String>, String) => method, id
#[derive(Debug, Clone)]
pub enum Error {
    ParseError(Option<(String, String)>),
    MethodNotFound(String, String),
    InvalidRequest(String, String),
    InvalidResponse(String, String),
    ErrorResponse(String, String, i64, String),
}

impl Error {
    fn error_value(&self) -> ErrorValue {
        match self {
            Error::ParseError(_) => ErrorValue::new(-32700, "Parse error".into()),
            Error::MethodNotFound(_, _) => ErrorValue::new(-32601, "Method not found".into()),
            Error::InvalidRequest(_, _) => ErrorValue::new(-32600, "Invalid Request".into()),
            Error::InvalidResponse(_, _) => ErrorValue::new(-32600, "Invalid Response".into()),
            Error::ErrorResponse(_, _, code, message) => ErrorValue::new(*code, message.clone()),
        }
    }

    pub fn deparse(&self) -> Bytes {
        let body =
            match self {
                Error::ParseError(Some((method, id))) => serde_json::to_string(
                    &ErrorResponse::new(method.clone(), id.clone(), self.error_value()),
                )
                .unwrap(),
                Error::ParseError(None) => {
                    serde_json::to_string(&ErrorOnlyResponse::new(self.error_value()))
                        .map_err(|e| {
                            println!("{:?}", e);
                        })
                        .unwrap()
                }
                Error::MethodNotFound(method, id)
                | Error::InvalidRequest(method, id)
                | Error::InvalidResponse(method, id) => serde_json::to_string(&ErrorResponse::new(
                    method.clone(),
                    id.clone(),
                    self.error_value(),
                ))
                .unwrap(),
                Error::ErrorResponse(method, id, _, _) => serde_json::to_string(
                    &ErrorResponse::new(method.clone(), id.clone(), self.error_value()),
                )
                .unwrap(),
            };

        let body_bytes = body.as_bytes();

        let mut headers = generate_response_headers(body_bytes.len());
        headers.put(body_bytes);
        headers.freeze()
    }
}