Coverage Report

Created: 2024-05-16 12:16

/__w/smoldot/smoldot/repo/lib/src/json_rpc/parse.rs
Line
Count
Source (jump to first uncovered line)
1
// Smoldot
2
// Copyright (C) 2019-2022  Parity Technologies (UK) Ltd.
3
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
5
// This program is free software: you can redistribute it and/or modify
6
// it under the terms of the GNU General Public License as published by
7
// the Free Software Foundation, either version 3 of the License, or
8
// (at your option) any later version.
9
10
// This program is distributed in the hope that it will be useful,
11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
// GNU General Public License for more details.
14
15
// You should have received a copy of the GNU General Public License
16
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18
//! Parse JSON-RPC method calls and notifications, and build responses messages.
19
20
use alloc::{borrow::Cow, string::String};
21
22
/// Parses a JSON-encoded RPC method call or notification.
23
104
pub fn parse_request(request_json: &str) -> Result<Request, ParseError> {
24
104
    let 
serde_request: SerdeRequest102
= serde_json::from_str(request_json).map_err(ParseError)
?2
;
25
26
102
    if let Some(
id101
) = &serde_request.id {
27
        // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
28
        #[allow(dead_code)] // Necessary to silence warnings about unused fields.
29
        #[derive(serde::Deserialize)]
30
        #[serde(deny_unknown_fields)]
31
        #[serde(untagged)]
32
        enum SerdeId<'a> {
33
            Num(u64),
34
            Str(Cow<'a, str>),
35
        }
36
37
101
        if let Err(
err1
) = serde_json::from_str::<SerdeId>(id.get()) {
38
1
            return Err(ParseError(err));
39
100
        }
40
1
    }
41
42
101
    Ok(Request {
43
101
        id_json: serde_request.id.map(|v| 
v.get()100
),
_RNCNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse13parse_request0B7_
Line
Count
Source
43
7
        id_json: serde_request.id.map(|v| v.get()),
_RNCNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse13parse_request0B7_
Line
Count
Source
43
93
        id_json: serde_request.id.map(|v| v.get()),
44
101
        method: serde_request.method,
45
101
        params_json: serde_request.params.map(|p| 
p.get()98
),
_RNCNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse13parse_requests_0B7_
Line
Count
Source
45
5
        params_json: serde_request.params.map(|p| p.get()),
_RNCNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse13parse_requests_0B7_
Line
Count
Source
45
93
        params_json: serde_request.params.map(|p| p.get()),
46
101
    })
47
104
}
_RNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse13parse_request
Line
Count
Source
23
10
pub fn parse_request(request_json: &str) -> Result<Request, ParseError> {
24
10
    let 
serde_request: SerdeRequest9
= serde_json::from_str(request_json).map_err(ParseError)
?1
;
25
26
9
    if let Some(
id8
) = &serde_request.id {
27
        // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
28
        #[allow(dead_code)] // Necessary to silence warnings about unused fields.
29
        #[derive(serde::Deserialize)]
30
        #[serde(deny_unknown_fields)]
31
        #[serde(untagged)]
32
        enum SerdeId<'a> {
33
            Num(u64),
34
            Str(Cow<'a, str>),
35
        }
36
37
8
        if let Err(
err1
) = serde_json::from_str::<SerdeId>(id.get()) {
38
1
            return Err(ParseError(err));
39
7
        }
40
1
    }
41
42
8
    Ok(Request {
43
8
        id_json: serde_request.id.map(|v| v.get()),
44
8
        method: serde_request.method,
45
8
        params_json: serde_request.params.map(|p| p.get()),
46
8
    })
47
10
}
_RNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse13parse_request
Line
Count
Source
23
94
pub fn parse_request(request_json: &str) -> Result<Request, ParseError> {
24
94
    let 
serde_request: SerdeRequest93
= serde_json::from_str(request_json).map_err(ParseError)
?1
;
25
26
93
    if let Some(id) = &serde_request.id {
27
        // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
28
        #[allow(dead_code)] // Necessary to silence warnings about unused fields.
29
        #[derive(serde::Deserialize)]
30
        #[serde(deny_unknown_fields)]
31
        #[serde(untagged)]
32
        enum SerdeId<'a> {
33
            Num(u64),
34
            Str(Cow<'a, str>),
35
        }
36
37
93
        if let Err(
err0
) = serde_json::from_str::<SerdeId>(id.get()) {
38
0
            return Err(ParseError(err));
39
93
        }
40
0
    }
41
42
93
    Ok(Request {
43
93
        id_json: serde_request.id.map(|v| v.get()),
44
93
        method: serde_request.method,
45
93
        params_json: serde_request.params.map(|p| p.get()),
46
93
    })
47
94
}
48
49
/// Parses a JSON-encoded RPC response.
50
33
pub fn parse_response(response_json: &str) -> Result<Response, ParseError> {
51
33
    let 
error9
= match serde_json::from_str::<SerdeSuccess>(response_json) {
52
9
        Err(err) => err,
53
        Ok(SerdeSuccess {
54
            jsonrpc: _,
55
24
            id,
56
24
            result,
57
        }) => {
58
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
59
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
60
            #[derive(serde::Deserialize)]
61
            #[serde(deny_unknown_fields)]
62
            #[serde(untagged)]
63
            enum SerdeId<'a> {
64
                Num(u64),
65
                Str(Cow<'a, str>),
66
            }
67
68
24
            if let Err(
err1
) = serde_json::from_str::<SerdeId>(id.get()) {
69
1
                return Err(ParseError(err));
70
23
            }
71
23
72
23
            return Ok(Response::Success {
73
23
                id_json: id.get(),
74
23
                result_json: result.get(),
75
23
            });
76
        }
77
    };
78
79
9
    match serde_json::from_str::<SerdeFailure>(response_json) {
80
        Ok(SerdeFailure {
81
            jsonrpc: _,
82
5
            id,
83
5
            error:
84
5
                SerdeError {
85
5
                    code,
86
5
                    message,
87
5
                    data,
88
                },
89
7
        }) if id.get() != "null
"5
=> {
90
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
91
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
92
            #[derive(serde::Deserialize)]
93
            #[serde(deny_unknown_fields)]
94
            #[serde(untagged)]
95
            enum SerdeId<'a> {
96
                Num(u64),
97
                Str(Cow<'a, str>),
98
            }
99
100
5
            if let Err(
err1
) = serde_json::from_str::<SerdeId>(id.get()) {
101
1
                return Err(ParseError(err));
102
4
            }
103
4
104
4
            Ok(Response::Error {
105
4
                id_json: id.get(),
106
4
                error_code: code.to_num(),
107
4
                error_message: message,
108
4
                error_data_json: data.map(|d| 
d.get()0
),
Unexecuted instantiation: _RNCNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse14parse_response0B7_
Unexecuted instantiation: _RNCNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse14parse_response0B7_
109
4
            })
110
        }
111
        Ok(SerdeFailure {
112
            jsonrpc: _,
113
            id: _,
114
            error:
115
                SerdeError {
116
2
                    code,
117
2
                    message,
118
2
                    data,
119
2
                },
120
2
        }) => Ok(Response::ParseError {
121
2
            error_code: code.to_num(),
122
2
            error_message: message,
123
2
            error_data_json: data.map(|d| 
d.get()0
),
Unexecuted instantiation: _RNCNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse14parse_responses_0B7_
Unexecuted instantiation: _RNCNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse14parse_responses_0B7_
124
2
        }),
125
2
        Err(_) => Err(ParseError(error)),
126
    }
127
33
}
_RNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse14parse_response
Line
Count
Source
50
8
pub fn parse_response(response_json: &str) -> Result<Response, ParseError> {
51
8
    let 
error5
= match serde_json::from_str::<SerdeSuccess>(response_json) {
52
5
        Err(err) => err,
53
        Ok(SerdeSuccess {
54
            jsonrpc: _,
55
3
            id,
56
3
            result,
57
        }) => {
58
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
59
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
60
            #[derive(serde::Deserialize)]
61
            #[serde(deny_unknown_fields)]
62
            #[serde(untagged)]
63
            enum SerdeId<'a> {
64
                Num(u64),
65
                Str(Cow<'a, str>),
66
            }
67
68
3
            if let Err(
err1
) = serde_json::from_str::<SerdeId>(id.get()) {
69
1
                return Err(ParseError(err));
70
2
            }
71
2
72
2
            return Ok(Response::Success {
73
2
                id_json: id.get(),
74
2
                result_json: result.get(),
75
2
            });
76
        }
77
    };
78
79
5
    match serde_json::from_str::<SerdeFailure>(response_json) {
80
        Ok(SerdeFailure {
81
            jsonrpc: _,
82
2
            id,
83
2
            error:
84
2
                SerdeError {
85
2
                    code,
86
2
                    message,
87
2
                    data,
88
                },
89
3
        }) if id.get() != "null
"2
=> {
90
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
91
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
92
            #[derive(serde::Deserialize)]
93
            #[serde(deny_unknown_fields)]
94
            #[serde(untagged)]
95
            enum SerdeId<'a> {
96
                Num(u64),
97
                Str(Cow<'a, str>),
98
            }
99
100
2
            if let Err(
err1
) = serde_json::from_str::<SerdeId>(id.get()) {
101
1
                return Err(ParseError(err));
102
1
            }
103
1
104
1
            Ok(Response::Error {
105
1
                id_json: id.get(),
106
1
                error_code: code.to_num(),
107
1
                error_message: message,
108
1
                error_data_json: data.map(|d| d.get()),
109
1
            })
110
        }
111
        Ok(SerdeFailure {
112
            jsonrpc: _,
113
            id: _,
114
            error:
115
                SerdeError {
116
1
                    code,
117
1
                    message,
118
1
                    data,
119
1
                },
120
1
        }) => Ok(Response::ParseError {
121
1
            error_code: code.to_num(),
122
1
            error_message: message,
123
1
            error_data_json: data.map(|d| d.get()),
124
1
        }),
125
2
        Err(_) => Err(ParseError(error)),
126
    }
127
8
}
_RNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse14parse_response
Line
Count
Source
50
25
pub fn parse_response(response_json: &str) -> Result<Response, ParseError> {
51
25
    let 
error4
= match serde_json::from_str::<SerdeSuccess>(response_json) {
52
4
        Err(err) => err,
53
        Ok(SerdeSuccess {
54
            jsonrpc: _,
55
21
            id,
56
21
            result,
57
        }) => {
58
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
59
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
60
            #[derive(serde::Deserialize)]
61
            #[serde(deny_unknown_fields)]
62
            #[serde(untagged)]
63
            enum SerdeId<'a> {
64
                Num(u64),
65
                Str(Cow<'a, str>),
66
            }
67
68
21
            if let Err(
err0
) = serde_json::from_str::<SerdeId>(id.get()) {
69
0
                return Err(ParseError(err));
70
21
            }
71
21
72
21
            return Ok(Response::Success {
73
21
                id_json: id.get(),
74
21
                result_json: result.get(),
75
21
            });
76
        }
77
    };
78
79
4
    match serde_json::from_str::<SerdeFailure>(response_json) {
80
        Ok(SerdeFailure {
81
            jsonrpc: _,
82
3
            id,
83
3
            error:
84
3
                SerdeError {
85
3
                    code,
86
3
                    message,
87
3
                    data,
88
                },
89
4
        }) if id.get() != "null
"3
=> {
90
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
91
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
92
            #[derive(serde::Deserialize)]
93
            #[serde(deny_unknown_fields)]
94
            #[serde(untagged)]
95
            enum SerdeId<'a> {
96
                Num(u64),
97
                Str(Cow<'a, str>),
98
            }
99
100
3
            if let Err(
err0
) = serde_json::from_str::<SerdeId>(id.get()) {
101
0
                return Err(ParseError(err));
102
3
            }
103
3
104
3
            Ok(Response::Error {
105
3
                id_json: id.get(),
106
3
                error_code: code.to_num(),
107
3
                error_message: message,
108
3
                error_data_json: data.map(|d| d.get()),
109
3
            })
110
        }
111
        Ok(SerdeFailure {
112
            jsonrpc: _,
113
            id: _,
114
            error:
115
                SerdeError {
116
1
                    code,
117
1
                    message,
118
1
                    data,
119
1
                },
120
1
        }) => Ok(Response::ParseError {
121
1
            error_code: code.to_num(),
122
1
            error_message: message,
123
1
            error_data_json: data.map(|d| d.get()),
124
1
        }),
125
0
        Err(_) => Err(ParseError(error)),
126
    }
127
25
}
128
129
/// Builds a JSON request.
130
///
131
/// `method` must be the name of the method to request. `params_json` must be the JSON-formatted
132
/// object or array containing the parameters of the request.
133
///
134
/// # Panic
135
///
136
/// Panics if the [`Request::id_json`] or [`Request::params_json`] isn't valid JSON.
137
///
138
3
pub fn build_request(request: &Request) -> String {
139
3
    serde_json::to_string(&SerdeRequest {
140
3
        jsonrpc: SerdeVersion::V2,
141
3
        id: request.id_json.map(|id| serde_json::from_str(id).unwrap()),
_RNCNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse13build_request0B7_
Line
Count
Source
141
3
        id: request.id_json.map(|id| serde_json::from_str(id).unwrap()),
Unexecuted instantiation: _RNCNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse13build_request0B7_
142
3
        method: request.method,
143
3
        params: request
144
3
            .params_json
145
3
            .map(|p| 
serde_json::from_str(p).unwrap()2
),
_RNCNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse13build_requests_0B7_
Line
Count
Source
145
2
            .map(|p| serde_json::from_str(p).unwrap()),
Unexecuted instantiation: _RNCNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse13build_requests_0B7_
146
3
    })
147
3
    .unwrap()
148
3
}
_RNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse13build_request
Line
Count
Source
138
3
pub fn build_request(request: &Request) -> String {
139
3
    serde_json::to_string(&SerdeRequest {
140
3
        jsonrpc: SerdeVersion::V2,
141
3
        id: request.id_json.map(|id| serde_json::from_str(id).unwrap()),
142
3
        method: request.method,
143
3
        params: request
144
3
            .params_json
145
3
            .map(|p| serde_json::from_str(p).unwrap()),
146
3
    })
147
3
    .unwrap()
148
3
}
Unexecuted instantiation: _RNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse13build_request
149
150
/// Decoded JSON-RPC request.
151
#[derive(Debug, Clone, PartialEq, Eq)]
152
pub struct Request<'a> {
153
    /// JSON-formatted identifier of the request. `None` for notifications.
154
    pub id_json: Option<&'a str>,
155
    /// Name of the method that is being called.
156
    pub method: &'a str,
157
    /// JSON-formatted list of parameters. `None` iff the `params` field is missing.
158
    pub params_json: Option<&'a str>,
159
}
160
161
/// Decoded JSON-RPC response.
162
#[derive(Debug, Clone, PartialEq, Eq)]
163
pub enum Response<'a> {
164
    /// Successful request.
165
    Success {
166
        /// JSON-formatted identifier of the request the response corresponds to.
167
        id_json: &'a str,
168
        /// JSON-formatted result.
169
        result_json: &'a str,
170
    },
171
172
    /// Request has failed.
173
    Error {
174
        /// JSON-formatted identifier of the request the response corresponds to.
175
        id_json: &'a str,
176
        /// Integer indicating the nature of the error.
177
        ///
178
        /// See [the JSON-RPC specification](https://www.jsonrpc.org/specification#error_object)
179
        /// for reference.
180
        error_code: i64,
181
        /// Short description of the error.
182
        error_message: &'a str,
183
        /// JSON-formatted data associated with the response. `None` if omitted.
184
        error_data_json: Option<&'a str>,
185
    },
186
187
    /// The JSON-RPC server indicates that it couldn't parse a request.
188
    ParseError {
189
        /// Integer indicating the nature of the error.
190
        ///
191
        /// See [the JSON-RPC specification](https://www.jsonrpc.org/specification#error_object)
192
        /// for reference.
193
        error_code: i64,
194
        /// Short description of the error.
195
        error_message: &'a str,
196
        /// JSON-formatted data associated with the response. `None` if omitted.
197
        error_data_json: Option<&'a str>,
198
    },
199
}
200
201
impl<'a> Response<'a> {
202
    /// Utility function that returns `Some` if `self` is [`Response::Success`]. If `Some` is
203
    /// returned, it contains in order the JSON-formatted identifier of the request and the
204
    /// JSON-formatted content of the `result` field.
205
2
    pub fn into_success(self) -> Option<(&'a str, &'a str)> {
206
        if let Response::Success {
207
2
            id_json,
208
2
            result_json,
209
2
        } = self
210
        {
211
2
            Some((id_json, result_json))
212
        } else {
213
0
            None
214
        }
215
2
    }
_RNvMNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB2_8Response12into_success
Line
Count
Source
205
2
    pub fn into_success(self) -> Option<(&'a str, &'a str)> {
206
        if let Response::Success {
207
2
            id_json,
208
2
            result_json,
209
2
        } = self
210
        {
211
2
            Some((id_json, result_json))
212
        } else {
213
0
            None
214
        }
215
2
    }
Unexecuted instantiation: _RNvMNtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB2_8Response12into_success
216
}
217
218
/// Error while parsing a request.
219
0
#[derive(Debug, derive_more::Display)]
Unexecuted instantiation: _RNvXsf_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB5_10ParseErrorNtNtCsaYZPK01V26L_4core3fmt7Display3fmt
Unexecuted instantiation: _RNvXsf_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB5_10ParseErrorNtNtCsaYZPK01V26L_4core3fmt7Display3fmt
220
pub struct ParseError(serde_json::Error);
221
222
/// Builds a JSON response.
223
///
224
/// `id_json` must be the JSON-formatted identifier of the request, found in [`Request::id_json`].
225
/// `result_json` must be the JSON-formatted result of the request.
226
///
227
/// # Example
228
///
229
/// ```
230
/// # use smoldot::json_rpc::parse;
231
/// let result_json = parse::build_success_response("27", r#"[1, 2, {"foo":"bar"}]"#);
232
///
233
/// // Note that the output is guaranteed to be stable.
234
/// assert_eq!(result_json, r#"{"jsonrpc":"2.0","id":27,"result":[1, 2, {"foo":"bar"}]}"#);
235
/// ```
236
///
237
/// # Panic
238
///
239
/// Panics if `id_json` or `result_json` aren't valid JSON.
240
///
241
21
pub fn build_success_response(id_json: &str, result_json: &str) -> String {
242
21
    serde_json::to_string(&SerdeSuccess {
243
21
        jsonrpc: SerdeVersion::V2,
244
21
        id: serde_json::from_str(id_json).expect("invalid id_json"),
245
21
        result: serde_json::from_str(result_json).expect("invalid result_json"),
246
21
    })
247
21
    .unwrap()
248
21
}
Unexecuted instantiation: _RNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse22build_success_response
_RNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse22build_success_response
Line
Count
Source
241
21
pub fn build_success_response(id_json: &str, result_json: &str) -> String {
242
21
    serde_json::to_string(&SerdeSuccess {
243
21
        jsonrpc: SerdeVersion::V2,
244
21
        id: serde_json::from_str(id_json).expect("invalid id_json"),
245
21
        result: serde_json::from_str(result_json).expect("invalid result_json"),
246
21
    })
247
21
    .unwrap()
248
21
}
249
250
/// Builds a JSON response.
251
///
252
/// `id_json` must be the JSON-formatted identifier of the request, found in [`Request::id_json`].
253
///
254
/// # Example
255
///
256
/// ```
257
/// # use smoldot::json_rpc::parse;
258
/// let _result_json = parse::build_error_response("43", parse::ErrorResponse::ParseError, None);
259
/// ```
260
///
261
/// # Panic
262
///
263
/// Panics if `id_json` or `data_json` aren't valid JSON.
264
/// Panics if the code in the [`ErrorResponse`] doesn't respect the rules documented under
265
/// certain variants.
266
///
267
3
pub fn build_error_response(
268
3
    id_json: &str,
269
3
    error: ErrorResponse,
270
3
    data_json: Option<&str>,
271
3
) -> String {
272
3
    let (code, message) = match error {
273
0
        ErrorResponse::ParseError => (
274
0
            SerdeErrorCode::ParseError,
275
0
            "Invalid JSON was received by the server.",
276
0
        ),
277
0
        ErrorResponse::InvalidRequest => (
278
0
            SerdeErrorCode::InvalidRequest,
279
0
            "The JSON sent is not a valid Request object.",
280
0
        ),
281
1
        ErrorResponse::MethodNotFound => (
282
1
            SerdeErrorCode::MethodNotFound,
283
1
            "The method does not exist / is not available.",
284
1
        ),
285
2
        ErrorResponse::InvalidParams => (
286
2
            SerdeErrorCode::InvalidParams,
287
2
            "Invalid method parameter(s).",
288
2
        ),
289
0
        ErrorResponse::InternalError => (SerdeErrorCode::InternalError, "Internal JSON-RPC error."),
290
0
        ErrorResponse::ServerError(n, msg) => {
291
0
            assert!((-32099..=-32000).contains(&n));
292
0
            (SerdeErrorCode::ServerError(n), msg)
293
        }
294
0
        ErrorResponse::ApplicationDefined(n, msg) => {
295
0
            assert!(!(-32768..=-32000).contains(&n));
296
0
            (SerdeErrorCode::MethodError(n), msg)
297
        }
298
    };
299
300
3
    serde_json::to_string(&SerdeFailure {
301
3
        jsonrpc: SerdeVersion::V2,
302
3
        id: serde_json::from_str(id_json).expect("invalid id_json"),
303
3
        error: SerdeError {
304
3
            code,
305
3
            message,
306
3
            data: data_json.map(|d| 
serde_json::from_str(d).expect("invalid result_json")0
),
Unexecuted instantiation: _RNCNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse20build_error_response0B7_
Unexecuted instantiation: _RNCNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse20build_error_response0B7_
307
3
        },
308
3
    })
309
3
    .unwrap()
310
3
}
Unexecuted instantiation: _RNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse20build_error_response
_RNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse20build_error_response
Line
Count
Source
267
3
pub fn build_error_response(
268
3
    id_json: &str,
269
3
    error: ErrorResponse,
270
3
    data_json: Option<&str>,
271
3
) -> String {
272
3
    let (code, message) = match error {
273
0
        ErrorResponse::ParseError => (
274
0
            SerdeErrorCode::ParseError,
275
0
            "Invalid JSON was received by the server.",
276
0
        ),
277
0
        ErrorResponse::InvalidRequest => (
278
0
            SerdeErrorCode::InvalidRequest,
279
0
            "The JSON sent is not a valid Request object.",
280
0
        ),
281
1
        ErrorResponse::MethodNotFound => (
282
1
            SerdeErrorCode::MethodNotFound,
283
1
            "The method does not exist / is not available.",
284
1
        ),
285
2
        ErrorResponse::InvalidParams => (
286
2
            SerdeErrorCode::InvalidParams,
287
2
            "Invalid method parameter(s).",
288
2
        ),
289
0
        ErrorResponse::InternalError => (SerdeErrorCode::InternalError, "Internal JSON-RPC error."),
290
0
        ErrorResponse::ServerError(n, msg) => {
291
0
            assert!((-32099..=-32000).contains(&n));
292
0
            (SerdeErrorCode::ServerError(n), msg)
293
        }
294
0
        ErrorResponse::ApplicationDefined(n, msg) => {
295
0
            assert!(!(-32768..=-32000).contains(&n));
296
0
            (SerdeErrorCode::MethodError(n), msg)
297
        }
298
    };
299
300
3
    serde_json::to_string(&SerdeFailure {
301
3
        jsonrpc: SerdeVersion::V2,
302
3
        id: serde_json::from_str(id_json).expect("invalid id_json"),
303
3
        error: SerdeError {
304
3
            code,
305
3
            message,
306
3
            data: data_json.map(|d| serde_json::from_str(d).expect("invalid result_json")),
307
3
        },
308
3
    })
309
3
    .unwrap()
310
3
}
311
312
/// Error that can be reported to the JSON-RPC client.
313
#[derive(Debug)]
314
pub enum ErrorResponse<'a> {
315
    /// Invalid JSON was received by the server.
316
    ParseError,
317
318
    /// The JSON sent is not a valid Request object.
319
    InvalidRequest,
320
321
    /// The method does not exist / is not available.
322
    MethodNotFound,
323
324
    /// Invalid method parameter(s).
325
    InvalidParams,
326
327
    /// Internal JSON-RPC error.
328
    InternalError,
329
330
    /// Other internal server error.
331
    /// Contains a more precise error code and a custom message.
332
    /// Error code must be in the range -32000 to -32099 included.
333
    ServerError(i64, &'a str),
334
335
    /// Method-specific error.
336
    /// Contains a more precise error code and a custom message.
337
    /// Error code must be outside of the range -32000 to -32700.
338
    ApplicationDefined(i64, &'a str),
339
}
340
341
/// Builds a JSON error response when a request couldn't be decoded.
342
///
343
/// # Example
344
///
345
/// ```
346
/// # use smoldot::json_rpc::parse;
347
/// let _result_json = parse::build_parse_error_response();
348
/// ```
349
///
350
/// # Panic
351
///
352
/// Panics if `id_json` or `data_json` aren't valid JSON.
353
/// Panics if the code in the [`ErrorResponse`] doesn't respect the rules documented under
354
/// certain variants.
355
///
356
2
pub fn build_parse_error_response() -> String {
357
2
    serde_json::to_string(&SerdeFailure {
358
2
        jsonrpc: SerdeVersion::V2,
359
2
        id: serde_json::from_str("null").unwrap(),
360
2
        error: SerdeError {
361
2
            code: SerdeErrorCode::ParseError,
362
2
            message: "Parse error",
363
2
            data: None,
364
2
        },
365
2
    })
366
2
    .unwrap()
367
2
}
_RNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse26build_parse_error_response
Line
Count
Source
356
1
pub fn build_parse_error_response() -> String {
357
1
    serde_json::to_string(&SerdeFailure {
358
1
        jsonrpc: SerdeVersion::V2,
359
1
        id: serde_json::from_str("null").unwrap(),
360
1
        error: SerdeError {
361
1
            code: SerdeErrorCode::ParseError,
362
1
            message: "Parse error",
363
1
            data: None,
364
1
        },
365
1
    })
366
1
    .unwrap()
367
1
}
_RNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse26build_parse_error_response
Line
Count
Source
356
1
pub fn build_parse_error_response() -> String {
357
1
    serde_json::to_string(&SerdeFailure {
358
1
        jsonrpc: SerdeVersion::V2,
359
1
        id: serde_json::from_str("null").unwrap(),
360
1
        error: SerdeError {
361
1
            code: SerdeErrorCode::ParseError,
362
1
            message: "Parse error",
363
1
            data: None,
364
1
        },
365
1
    })
366
1
    .unwrap()
367
1
}
368
369
914
#[derive(Clone, Debug, 
s508
erde::Deserialize, serde::Serialize)]
_RINvXs_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtBa_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1a_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2B_4read7StrReadEEBe_
Line
Count
Source
369
33
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtBb_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1d_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2L_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtBb_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1d_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2L_4read7StrReadEEBf_
Line
Count
Source
369
44
#[derive(Clone, Debug, 
s10
erde::Deserialize, serde::Serialize)]
_RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtB8_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1a_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
369
33
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtBa_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1c_7Visitor9expecting
Unexecuted instantiation: _RNvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtB7_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB19_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtB8_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1a_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parse1__NtB8_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1a_7Visitor11visit_bytespEBc_
Unexecuted instantiation: _RNvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtB7_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB1a_7Visitor9expecting
_RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtB8_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1b_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
369
372
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtBa_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1d_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtB8_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1b_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtB8_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1b_7Visitor11visit_bytespEBc_
_RINvXs_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtBa_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1b_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2C_4read7StrReadEEBe_
Line
Count
Source
369
372
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtBb_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1e_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2M_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parse1__NtBb_12SerdeRequestNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1e_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2M_4read7StrReadEEBf_
Line
Count
Source
369
465
#[derive(Clone, Debug, 
s93
erde::Deserialize, serde::Serialize)]
370
struct SerdeRequest<'a> {
371
    jsonrpc: SerdeVersion,
372
    #[serde(borrow, skip_serializing_if = "Option::is_none")]
373
    id: Option<&'a serde_json::value::RawValue>,
374
    #[serde(borrow)]
375
    method: &'a str,
376
    #[serde(borrow)]
377
    params: Option<&'a serde_json::value::RawValue>,
378
}
379
380
#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq)]
381
enum SerdeVersion {
382
    V2,
383
}
384
385
impl serde::Serialize for SerdeVersion {
386
27
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
387
27
    where
388
27
        S: serde::Serializer,
389
27
    {
390
27
        match *self {
391
27
            SerdeVersion::V2 => "2.0".serialize(serializer),
392
27
        }
393
27
    }
Unexecuted instantiation: _RINvXs_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB5_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeINtNtCscu7pqq74Vb8_10serde_json3ser18RawValueStrEmitterQINtNtCsdZExvAaxgia_5alloc3vec3VechENtB1R_16CompactFormatterEEB9_
_RINvXs_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB5_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeQINtNtCscu7pqq74Vb8_10serde_json3ser10SerializerQINtNtCsdZExvAaxgia_5alloc3vec3VechEEEB9_
Line
Count
Source
386
2
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
387
2
    where
388
2
        S: serde::Serializer,
389
2
    {
390
2
        match *self {
391
2
            SerdeVersion::V2 => "2.0".serialize(serializer),
392
2
        }
393
2
    }
Unexecuted instantiation: _RINvXs_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB5_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeINtNtCscu7pqq74Vb8_10serde_json3ser18RawValueStrEmitterQINtNtCsdZExvAaxgia_5alloc3vec3VechENtB1S_16CompactFormatterEEB9_
_RINvXs_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB5_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeQINtNtCscu7pqq74Vb8_10serde_json3ser10SerializerQINtNtCsdZExvAaxgia_5alloc3vec3VechEEEB9_
Line
Count
Source
386
25
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
387
25
    where
388
25
        S: serde::Serializer,
389
25
    {
390
25
        match *self {
391
25
            SerdeVersion::V2 => "2.0".serialize(serializer),
392
25
        }
393
25
    }
394
}
395
396
impl<'a> serde::Deserialize<'a> for SerdeVersion {
397
145
    fn deserialize<D>(deserializer: D) -> Result<SerdeVersion, D::Error>
398
145
    where
399
145
        D: serde::Deserializer<'a>,
400
145
    {
401
145
        let string = <&str>::deserialize(deserializer)
?0
;
402
145
        if string != "2.0" {
403
3
            return Err(serde::de::Error::custom("unknown version"));
404
142
        }
405
142
        Ok(SerdeVersion::V2)
406
145
    }
Unexecuted instantiation: _RINvXs0_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB6_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeINtNvNtNtB17_9___private2de13missing_field24MissingFieldDeserializerNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEEBa_
_RINvXs0_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB6_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeQINtNtCscu7pqq74Vb8_10serde_json2de12DeserializerNtNtB20_4read7StrReadEEBa_
Line
Count
Source
397
23
    fn deserialize<D>(deserializer: D) -> Result<SerdeVersion, D::Error>
398
23
    where
399
23
        D: serde::Deserializer<'a>,
400
23
    {
401
23
        let string = <&str>::deserialize(deserializer)
?0
;
402
23
        if string != "2.0" {
403
3
            return Err(serde::de::Error::custom("unknown version"));
404
20
        }
405
20
        Ok(SerdeVersion::V2)
406
23
    }
Unexecuted instantiation: _RINvXs0_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB6_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeINtNvNtNtB18_9___private2de13missing_field24MissingFieldDeserializerNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEEBa_
_RINvXs0_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB6_12SerdeVersionNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeQINtNtCscu7pqq74Vb8_10serde_json2de12DeserializerNtNtB21_4read7StrReadEEBa_
Line
Count
Source
397
122
    fn deserialize<D>(deserializer: D) -> Result<SerdeVersion, D::Error>
398
122
    where
399
122
        D: serde::Deserializer<'a>,
400
122
    {
401
122
        let string = <&str>::deserialize(deserializer)
?0
;
402
122
        if string != "2.0" {
403
0
            return Err(serde::de::Error::custom("unknown version"));
404
122
        }
405
122
        Ok(SerdeVersion::V2)
406
122
    }
407
}
408
409
222
#[derive(Debug, Clone, serde::Serialize, 
s127
erde::Deserialize)]
_RINvXs_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtBa_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1d_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2E_4read7StrReadEEBe_
Line
Count
Source
409
19
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtBb_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1g_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2O_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtBb_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1g_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2O_4read7StrReadEEBf_
Line
Count
Source
409
28
#[derive(Debug, Clone, serde::Serialize, 
s8
erde::Deserialize)]
_RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtB8_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1d_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
409
19
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtBa_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1f_7Visitor9expecting
Unexecuted instantiation: _RNvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtB7_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB1c_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtB8_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1d_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses1_1__NtB8_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1d_7Visitor11visit_bytespEBc_
Unexecuted instantiation: _RNvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtB7_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB1d_7Visitor9expecting
_RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtB8_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1e_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
409
75
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtBa_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1g_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtB8_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1e_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtB8_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1e_7Visitor11visit_bytespEBc_
_RINvXs_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtBa_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1e_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2F_4read7StrReadEEBe_
Line
Count
Source
409
75
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtBb_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1h_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2P_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses1_1__NtBb_12SerdeSuccessNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1h_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2P_4read7StrReadEEBf_
Line
Count
Source
409
100
#[derive(Debug, Clone, serde::Serialize, 
s25
erde::Deserialize)]
410
#[serde(deny_unknown_fields)]
411
struct SerdeSuccess<'a> {
412
    jsonrpc: SerdeVersion,
413
    #[serde(borrow)]
414
    id: &'a serde_json::value::RawValue,
415
    #[serde(borrow)]
416
    result: &'a serde_json::value::RawValue,
417
}
418
419
59
#[derive(Debug, Clone, serde::Serialize, 
s33
erde::Deserialize)]
_RINvXs_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtBa_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1d_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2E_4read7StrReadEEBe_
Line
Count
Source
419
12
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtBb_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1g_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2O_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtBb_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1g_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2O_4read7StrReadEEBf_
Line
Count
Source
419
19
#[derive(Debug, Clone, serde::Serialize, 
s5
erde::Deserialize)]
_RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtB8_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1d_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
419
12
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtBa_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1f_7Visitor9expecting
Unexecuted instantiation: _RNvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtB7_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB1c_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtB8_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1d_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses3_1__NtB8_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1d_7Visitor11visit_bytespEBc_
Unexecuted instantiation: _RNvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtB7_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB1d_7Visitor9expecting
_RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtB8_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1e_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
419
12
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtBa_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1g_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtB8_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1e_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtB8_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1e_7Visitor11visit_bytespEBc_
_RINvXs_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtBa_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1e_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2F_4read7StrReadEEBe_
Line
Count
Source
419
12
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtBb_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1h_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2P_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses3_1__NtBb_12SerdeFailureNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1h_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2P_4read7StrReadEEBf_
Line
Count
Source
419
16
#[derive(Debug, Clone, serde::Serialize, 
s4
erde::Deserialize)]
420
#[serde(deny_unknown_fields)]
421
struct SerdeFailure<'a> {
422
    jsonrpc: SerdeVersion,
423
    #[serde(borrow)]
424
    id: &'a serde_json::value::RawValue,
425
    #[serde(borrow)]
426
    error: SerdeError<'a>,
427
}
428
429
40
#[derive(Debug, Clone, serde::Serialize, 
s24
erde::Deserialize)]
_RINvXs_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtBa_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1b_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2C_4read7StrReadEEBe_
Line
Count
Source
429
8
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtBb_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1e_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2M_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtBb_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1e_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2M_4read7StrReadEEBf_
Line
Count
Source
429
12
#[derive(Debug, Clone, serde::Serialize, 
s4
erde::Deserialize)]
_RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtB8_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1b_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
429
8
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtBa_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1d_7Visitor9expecting
Unexecuted instantiation: _RNvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtB7_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB1a_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtB8_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1b_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCsN16ciHI6Qf_7smoldot8json_rpc5parses5_1__NtB8_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1b_7Visitor11visit_bytespEBc_
Unexecuted instantiation: _RNvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtB7_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB2_14___FieldVisitorNtB1b_7Visitor9expecting
_RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtB8_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1c_7Visitor9visit_strNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEBc_
Line
Count
Source
429
8
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RNvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtBa_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_9___VisitorNtB1e_7Visitor9expecting
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtB8_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1c_7Visitor9visit_u64pEBc_
Unexecuted instantiation: _RINvXNvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtB8_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB3_14___FieldVisitorNtB1c_7Visitor11visit_bytespEBc_
_RINvXs_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtBa_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB5_7___FieldB1c_11deserializeINtNtCscu7pqq74Vb8_10serde_json2de6MapKeyNtNtB2D_4read7StrReadEEBe_
Line
Count
Source
429
8
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
Unexecuted instantiation: _RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtBb_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1f_7Visitor9visit_seqINtNtCscu7pqq74Vb8_10serde_json2de9SeqAccessNtNtB2N_4read7StrReadEEBf_
_RINvXs0_NvXNvNtNtCseuYC0Zibziv_7smoldot8json_rpc5parses5_1__NtBb_10SerdeErrorNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeNtB6_9___VisitorNtB1f_7Visitor9visit_mapINtNtCscu7pqq74Vb8_10serde_json2de9MapAccessNtNtB2N_4read7StrReadEEBf_
Line
Count
Source
429
12
#[derive(Debug, Clone, serde::Serialize, 
s4
erde::Deserialize)]
430
#[serde(deny_unknown_fields)]
431
struct SerdeError<'a> {
432
    code: SerdeErrorCode,
433
    #[serde(borrow)]
434
    message: &'a str,
435
    #[serde(skip_serializing_if = "Option::is_none")]
436
    data: Option<&'a serde_json::value::RawValue>,
437
}
438
439
#[derive(Debug, PartialEq, Clone)]
440
enum SerdeErrorCode {
441
    ParseError,
442
    InvalidRequest,
443
    MethodNotFound,
444
    InvalidParams,
445
    InternalError,
446
    ServerError(i64),
447
    MethodError(i64),
448
}
449
450
impl SerdeErrorCode {
451
11
    fn to_num(&self) -> i64 {
452
11
        match *self {
453
3
            SerdeErrorCode::ParseError => -32700,
454
1
            SerdeErrorCode::InvalidRequest => -32600,
455
3
            SerdeErrorCode::MethodNotFound => -32601,
456
4
            SerdeErrorCode::InvalidParams => -32602,
457
0
            SerdeErrorCode::InternalError => -32603,
458
0
            SerdeErrorCode::ServerError(code) => code,
459
0
            SerdeErrorCode::MethodError(code) => code,
460
        }
461
11
    }
_RNvMs1_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB5_14SerdeErrorCode6to_num
Line
Count
Source
451
3
    fn to_num(&self) -> i64 {
452
3
        match *self {
453
1
            SerdeErrorCode::ParseError => -32700,
454
1
            SerdeErrorCode::InvalidRequest => -32600,
455
1
            SerdeErrorCode::MethodNotFound => -32601,
456
0
            SerdeErrorCode::InvalidParams => -32602,
457
0
            SerdeErrorCode::InternalError => -32603,
458
0
            SerdeErrorCode::ServerError(code) => code,
459
0
            SerdeErrorCode::MethodError(code) => code,
460
        }
461
3
    }
_RNvMs1_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB5_14SerdeErrorCode6to_num
Line
Count
Source
451
8
    fn to_num(&self) -> i64 {
452
8
        match *self {
453
2
            SerdeErrorCode::ParseError => -32700,
454
0
            SerdeErrorCode::InvalidRequest => -32600,
455
2
            SerdeErrorCode::MethodNotFound => -32601,
456
4
            SerdeErrorCode::InvalidParams => -32602,
457
0
            SerdeErrorCode::InternalError => -32603,
458
0
            SerdeErrorCode::ServerError(code) => code,
459
0
            SerdeErrorCode::MethodError(code) => code,
460
        }
461
8
    }
462
}
463
464
impl<'a> serde::Deserialize<'a> for SerdeErrorCode {
465
8
    fn deserialize<D>(deserializer: D) -> Result<SerdeErrorCode, D::Error>
466
8
    where
467
8
        D: serde::Deserializer<'a>,
468
8
    {
469
8
        let code: i64 = serde::Deserialize::deserialize(deserializer)
?0
;
470
471
8
        Ok(match code {
472
1
            -32700 => SerdeErrorCode::ParseError,
473
2
            -32600 => SerdeErrorCode::InvalidRequest,
474
3
            -32601 => SerdeErrorCode::MethodNotFound,
475
2
            -32602 => SerdeErrorCode::InvalidParams,
476
0
            -32603 => SerdeErrorCode::InternalError,
477
0
            -32099..=-32000 => SerdeErrorCode::ServerError(code),
478
0
            code => SerdeErrorCode::MethodError(code),
479
        })
480
8
    }
Unexecuted instantiation: _RINvXs2_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeINtNvNtNtB19_9___private2de13missing_field24MissingFieldDeserializerNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEEBa_
_RINvXs2_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeQINtNtCscu7pqq74Vb8_10serde_json2de12DeserializerNtNtB22_4read7StrReadEEBa_
Line
Count
Source
465
4
    fn deserialize<D>(deserializer: D) -> Result<SerdeErrorCode, D::Error>
466
4
    where
467
4
        D: serde::Deserializer<'a>,
468
4
    {
469
4
        let code: i64 = serde::Deserialize::deserialize(deserializer)
?0
;
470
471
4
        Ok(match code {
472
0
            -32700 => SerdeErrorCode::ParseError,
473
2
            -32600 => SerdeErrorCode::InvalidRequest,
474
2
            -32601 => SerdeErrorCode::MethodNotFound,
475
0
            -32602 => SerdeErrorCode::InvalidParams,
476
0
            -32603 => SerdeErrorCode::InternalError,
477
0
            -32099..=-32000 => SerdeErrorCode::ServerError(code),
478
0
            code => SerdeErrorCode::MethodError(code),
479
        })
480
4
    }
Unexecuted instantiation: _RINvXs2_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeINtNvNtNtB1a_9___private2de13missing_field24MissingFieldDeserializerNtNtCscu7pqq74Vb8_10serde_json5error5ErrorEEBa_
_RINvXs2_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde2de11Deserialize11deserializeQINtNtCscu7pqq74Vb8_10serde_json2de12DeserializerNtNtB23_4read7StrReadEEBa_
Line
Count
Source
465
4
    fn deserialize<D>(deserializer: D) -> Result<SerdeErrorCode, D::Error>
466
4
    where
467
4
        D: serde::Deserializer<'a>,
468
4
    {
469
4
        let code: i64 = serde::Deserialize::deserialize(deserializer)
?0
;
470
471
4
        Ok(match code {
472
1
            -32700 => SerdeErrorCode::ParseError,
473
0
            -32600 => SerdeErrorCode::InvalidRequest,
474
1
            -32601 => SerdeErrorCode::MethodNotFound,
475
2
            -32602 => SerdeErrorCode::InvalidParams,
476
0
            -32603 => SerdeErrorCode::InternalError,
477
0
            -32099..=-32000 => SerdeErrorCode::ServerError(code),
478
0
            code => SerdeErrorCode::MethodError(code),
479
        })
480
4
    }
481
}
482
483
impl serde::Serialize for SerdeErrorCode {
484
5
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
485
5
    where
486
5
        S: serde::Serializer,
487
5
    {
488
5
        serializer.serialize_i64(self.to_num())
489
5
    }
Unexecuted instantiation: _RINvXs3_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeINtNtCscu7pqq74Vb8_10serde_json3ser18RawValueStrEmitterQINtNtCsdZExvAaxgia_5alloc3vec3VechENtB1U_16CompactFormatterEEBa_
_RINvXs3_NtNtCsN16ciHI6Qf_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeQINtNtCscu7pqq74Vb8_10serde_json3ser10SerializerQINtNtCsdZExvAaxgia_5alloc3vec3VechEEEBa_
Line
Count
Source
484
1
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
485
1
    where
486
1
        S: serde::Serializer,
487
1
    {
488
1
        serializer.serialize_i64(self.to_num())
489
1
    }
Unexecuted instantiation: _RINvXs3_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeINtNtCscu7pqq74Vb8_10serde_json3ser18RawValueStrEmitterQINtNtCsdZExvAaxgia_5alloc3vec3VechENtB1V_16CompactFormatterEEBa_
_RINvXs3_NtNtCseuYC0Zibziv_7smoldot8json_rpc5parseNtB6_14SerdeErrorCodeNtNtCsf0yC2YK6bpM_5serde3ser9Serialize9serializeQINtNtCscu7pqq74Vb8_10serde_json3ser10SerializerQINtNtCsdZExvAaxgia_5alloc3vec3VechEEEBa_
Line
Count
Source
484
4
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
485
4
    where
486
4
        S: serde::Serializer,
487
4
    {
488
4
        serializer.serialize_i64(self.to_num())
489
4
    }
490
}
491
492
#[cfg(test)]
493
mod tests {
494
    #[test]
495
1
    fn parse_request_basic_works() {
496
1
        let request = super::parse_request(
497
1
            r#"{"jsonrpc":"2.0","id":5,"method":"foo","params":[5,true, "hello"]}"#,
498
1
        )
499
1
        .unwrap();
500
1
        assert_eq!(request.id_json.unwrap(), "5");
501
1
        assert_eq!(request.method, "foo");
502
1
        assert_eq!(request.params_json, Some("[5,true, \"hello\"]"));
503
1
    }
504
505
    #[test]
506
1
    fn parse_response_basic_works() {
507
1
        let (id, result) = super::parse_response(r#"{"jsonrpc":"2.0","id":5,"result":true}"#)
508
1
            .unwrap()
509
1
            .into_success()
510
1
            .unwrap();
511
1
        assert_eq!(id, "5");
512
1
        assert_eq!(result, "true");
513
1
    }
514
515
    #[test]
516
1
    fn parse_error_response() {
517
1
        let response = super::parse_response(r#"{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}"#)
518
1
            .unwrap();
519
520
        let super::Response::Error {
521
1
            id_json,
522
1
            error_code,
523
1
            error_message,
524
1
            error_data_json,
525
1
        } = response
526
        else {
527
0
            panic!()
528
        };
529
1
        assert_eq!(id_json, "\"1\"");
530
1
        assert_eq!(error_code, -32601);
531
1
        assert_eq!(error_message, "Method not found");
532
1
        assert!(error_data_json.is_none());
533
1
    }
534
535
    #[test]
536
1
    fn parse_parse_error_response() {
537
1
        let response = super::parse_response(r#"{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}"#)
538
1
            .unwrap();
539
540
        let super::Response::ParseError {
541
1
            error_code,
542
1
            error_message,
543
1
            error_data_json,
544
1
        } = response
545
        else {
546
0
            panic!()
547
        };
548
1
        assert_eq!(error_code, -32600);
549
1
        assert_eq!(error_message, "Invalid Request");
550
1
        assert!(error_data_json.is_none());
551
1
    }
552
553
    #[test]
554
1
    fn parse_request_missing_id() {
555
1
        let request =
556
1
            super::parse_request(r#"{"jsonrpc":"2.0","method":"foo","params":[]}"#).unwrap();
557
1
        assert!(request.id_json.is_none());
558
1
        assert_eq!(request.method, "foo");
559
1
        assert_eq!(request.params_json, Some("[]"));
560
1
    }
561
562
    #[test]
563
1
    fn parse_request_id_string() {
564
1
        let request =
565
1
            super::parse_request(r#"{"jsonrpc":"2.0","id":"hello","method":"foo","params":[]}"#)
566
1
                .unwrap();
567
1
        assert_eq!(request.id_json.unwrap(), "\"hello\"");
568
1
        assert_eq!(request.method, "foo");
569
1
        assert_eq!(request.params_json, Some("[]"));
570
1
    }
571
572
    #[test]
573
1
    fn parse_request_id_string_escaped() {
574
1
        let request =
575
1
            super::parse_request(r#"{"jsonrpc":"2.0","id":"extern:\"health-checker:0\"","method":"system_health","params":[]}"#)
576
1
                .unwrap();
577
1
        assert_eq!(request.id_json.unwrap(), r#""extern:\"health-checker:0\"""#);
578
1
        assert_eq!(request.method, "system_health");
579
1
        assert_eq!(request.params_json, Some("[]"));
580
1
    }
581
582
    #[test]
583
1
    fn parse_response_id_string_escaped() {
584
1
        let (id, result) = super::parse_response(
585
1
            r#"{"jsonrpc":"2.0","id":"extern:\"health-checker:0\"","result":[]}"#,
586
1
        )
587
1
        .unwrap()
588
1
        .into_success()
589
1
        .unwrap();
590
1
        assert_eq!(id, r#""extern:\"health-checker:0\"""#);
591
1
        assert_eq!(result, "[]");
592
1
    }
593
594
    #[test]
595
1
    fn request_missing_params() {
596
1
        let request = super::parse_request(r#"{"jsonrpc":"2.0","id":2,"method":"foo"}"#).unwrap();
597
1
        assert_eq!(request.id_json.unwrap(), r#"2"#);
598
1
        assert_eq!(request.method, "foo");
599
1
        assert_eq!(request.params_json, None);
600
1
    }
601
602
    #[test]
603
1
    fn parse_request_wrong_jsonrpc() {
604
1
        assert!(
605
1
            super::parse_request(r#"{"jsonrpc":"2.1","id":5,"method":"foo","params":[]}"#).is_err()
606
1
        );
607
1
    }
608
609
    #[test]
610
1
    fn parse_response_wrong_jsonrpc() {
611
1
        assert!(super::parse_response(r#"{"jsonrpc":"2.1","id":5,"result":null}"#).is_err());
612
1
    }
613
614
    #[test]
615
1
    fn parse_request_bad_id() {
616
1
        assert!(
617
1
            super::parse_request(r#"{"jsonrpc":"2.0","id":{},"method":"foo","params":[]}"#)
618
1
                .is_err()
619
1
        );
620
1
    }
621
622
    #[test]
623
1
    fn parse_response_missing_id() {
624
1
        assert!(super::parse_response(
625
1
            r#"{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"} }"#
626
1
        )
627
1
        .is_err());
628
1
    }
629
630
    #[test]
631
1
    fn parse_response_bad_id_success() {
632
1
        assert!(super::parse_response(r#"{"jsonrpc":"2.0","id":{},"result":5}"#).is_err());
633
1
    }
634
635
    #[test]
636
1
    fn parse_response_bad_id_error() {
637
1
        assert!(super::parse_response(
638
1
            r#"{"jsonrpc":"2.0","id":{},"error": {"code": -32601, "message": "Method not found"}}"#
639
1
        )
640
1
        .is_err());
641
1
    }
642
643
    #[test]
644
1
    fn build_request() {
645
1
        let request = super::Request {
646
1
            id_json: Some("5"),
647
1
            method: "test",
648
1
            params_json: Some("{}"),
649
1
        };
650
1
651
1
        let encoded = super::build_request(&request);
652
1
        assert_eq!(super::parse_request(&encoded).unwrap(), request);
653
1
    }
654
655
    #[test]
656
    #[should_panic]
657
1
    fn build_request_panics_invalid_id() {
658
1
        super::build_request(&super::Request {
659
1
            id_json: Some("test"),
660
1
            method: "test",
661
1
            params_json: None,
662
1
        });
663
1
    }
664
665
    #[test]
666
    #[should_panic]
667
1
    fn build_request_panics_invalid_params() {
668
1
        super::build_request(&super::Request {
669
1
            id_json: Some("5"),
670
1
            method: "test",
671
1
            params_json: Some("invalid"),
672
1
        });
673
1
    }
674
675
    #[test]
676
1
    fn build_parse_error() {
677
1
        let response = super::build_parse_error_response();
678
1
        assert_eq!(response, "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32700,\"message\":\"Parse error\"}}");
679
1
    }
680
}