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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::fmt;
use crate::params::{Id, TwoPointZero};
use serde::de::Deserializer;
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use std::borrow::Borrow;
use std::borrow::Cow as StdCow;
use thiserror::Error;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct ErrorResponse<'a> {
jsonrpc: TwoPointZero,
#[serde(borrow)]
error: ErrorObject<'a>,
id: Id<'a>,
}
impl<'a> ErrorResponse<'a> {
pub fn borrowed(error: ErrorObject<'a>, id: Id<'a>) -> Self {
Self { jsonrpc: TwoPointZero, error, id }
}
pub fn owned(error: ErrorObject<'static>, id: Id<'static>) -> Self {
Self { jsonrpc: TwoPointZero, error, id }
}
pub fn into_owned(self) -> ErrorResponse<'static> {
ErrorResponse { jsonrpc: self.jsonrpc, error: self.error.into_owned(), id: self.id.into_owned() }
}
pub fn error_object(&self) -> &ErrorObject {
&self.error
}
pub fn id(&self) -> &Id {
&self.id
}
}
impl<'a> fmt::Display for ErrorResponse<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", serde_json::to_string(&self).expect("infallible; qed"))
}
}
pub type SubscriptionResult = Result<(), SubscriptionEmptyError>;
#[derive(Debug)]
pub struct SubscriptionEmptyError;
impl From<anyhow::Error> for SubscriptionEmptyError {
fn from(_: anyhow::Error) -> Self {
SubscriptionEmptyError
}
}
impl From<CallError> for SubscriptionEmptyError {
fn from(_: CallError) -> Self {
SubscriptionEmptyError
}
}
impl<'a> From<ErrorObject<'a>> for SubscriptionEmptyError {
fn from(_: ErrorObject<'a>) -> Self {
SubscriptionEmptyError
}
}
impl From<SubscriptionAcceptRejectError> for SubscriptionEmptyError {
fn from(_: SubscriptionAcceptRejectError) -> Self {
SubscriptionEmptyError
}
}
#[derive(Debug)]
pub enum SubscriptionAcceptRejectError {
AlreadyCalled,
RemotePeerAborted,
}
pub type ErrorObjectOwned = ErrorObject<'static>;
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct ErrorObject<'a> {
code: ErrorCode,
message: StdCow<'a, str>,
#[serde(skip_serializing_if = "Option::is_none")]
data: Option<StdCow<'a, RawValue>>,
}
impl<'a> ErrorObject<'a> {
pub fn code(&self) -> i32 {
self.code.code()
}
pub fn message(&self) -> &str {
self.message.borrow()
}
pub fn data(&self) -> Option<&RawValue> {
self.data.as_ref().map(|d| d.borrow())
}
pub fn owned<S: Serialize>(code: i32, message: impl Into<String>, data: Option<S>) -> ErrorObject<'static> {
let data = data.and_then(|d| serde_json::value::to_raw_value(&d).ok());
ErrorObject { code: code.into(), message: message.into().into(), data: data.map(StdCow::Owned) }
}
pub fn borrowed(code: i32, message: &'a impl AsRef<str>, data: Option<&'a RawValue>) -> ErrorObject<'a> {
ErrorObject { code: code.into(), message: StdCow::Borrowed(message.as_ref()), data: data.map(StdCow::Borrowed) }
}
pub fn into_owned(self) -> ErrorObject<'static> {
ErrorObject {
code: self.code,
message: StdCow::Owned(self.message.into_owned()),
data: self.data.map(|d| StdCow::Owned(d.into_owned())),
}
}
pub fn borrow(&'a self) -> ErrorObject<'a> {
ErrorObject {
code: self.code,
message: StdCow::Borrowed(self.message.borrow()),
data: self.data.as_ref().map(|d| StdCow::Borrowed(d.borrow())),
}
}
}
impl<'a> PartialEq for ErrorObject<'a> {
fn eq(&self, other: &Self) -> bool {
let this_raw = self.data.as_ref().map(|r| r.get());
let other_raw = other.data.as_ref().map(|r| r.get());
self.code == other.code && self.message == other.message && this_raw == other_raw
}
}
impl<'a> From<ErrorCode> for ErrorObject<'a> {
fn from(code: ErrorCode) -> Self {
Self { code, message: code.message().into(), data: None }
}
}
impl<'a> From<CallError> for ErrorObject<'a> {
fn from(error: CallError) -> Self {
match error {
CallError::InvalidParams(e) => ErrorObject::owned(INVALID_PARAMS_CODE, e.to_string(), None::<()>),
CallError::Failed(e) => ErrorObject::owned(CALL_EXECUTION_FAILED_CODE, e.to_string(), None::<()>),
CallError::Custom(err) => err,
}
}
}
pub const PARSE_ERROR_CODE: i32 = -32700;
pub const OVERSIZED_REQUEST_CODE: i32 = -32701;
pub const OVERSIZED_RESPONSE_CODE: i32 = -32702;
pub const INTERNAL_ERROR_CODE: i32 = -32603;
pub const INVALID_PARAMS_CODE: i32 = -32602;
pub const INVALID_REQUEST_CODE: i32 = -32600;
pub const METHOD_NOT_FOUND_CODE: i32 = -32601;
pub const SERVER_IS_BUSY_CODE: i32 = -32604;
pub const CALL_EXECUTION_FAILED_CODE: i32 = -32000;
pub const UNKNOWN_ERROR_CODE: i32 = -32001;
pub const SUBSCRIPTION_CLOSED: i32 = -32003;
pub const SUBSCRIPTION_CLOSED_WITH_ERROR: i32 = -32004;
pub const BATCHES_NOT_SUPPORTED_CODE: i32 = -32005;
pub const TOO_MANY_SUBSCRIPTIONS_CODE: i32 = -32006;
pub const PARSE_ERROR_MSG: &str = "Parse error";
pub const OVERSIZED_REQUEST_MSG: &str = "Request is too big";
pub const OVERSIZED_RESPONSE_MSG: &str = "Response is too big";
pub const INTERNAL_ERROR_MSG: &str = "Internal error";
pub const INVALID_PARAMS_MSG: &str = "Invalid params";
pub const INVALID_REQUEST_MSG: &str = "Invalid request";
pub const METHOD_NOT_FOUND_MSG: &str = "Method not found";
pub const SERVER_IS_BUSY_MSG: &str = "Server is busy, try again later";
pub const SERVER_ERROR_MSG: &str = "Server error";
pub const BATCHES_NOT_SUPPORTED_MSG: &str = "Batched requests are not supported by this server";
pub const TOO_MANY_SUBSCRIPTIONS_MSG: &str = "Too many subscriptions on the connection";
#[derive(Error, Debug, PartialEq, Copy, Clone)]
pub enum ErrorCode {
ParseError,
OversizedRequest,
InvalidRequest,
MethodNotFound,
ServerIsBusy,
InvalidParams,
InternalError,
ServerError(i32),
}
impl ErrorCode {
pub const fn code(&self) -> i32 {
use ErrorCode::*;
match *self {
ParseError => PARSE_ERROR_CODE,
OversizedRequest => OVERSIZED_REQUEST_CODE,
InvalidRequest => INVALID_REQUEST_CODE,
MethodNotFound => METHOD_NOT_FOUND_CODE,
ServerIsBusy => SERVER_IS_BUSY_CODE,
InvalidParams => INVALID_PARAMS_CODE,
InternalError => INTERNAL_ERROR_CODE,
ServerError(code) => code,
}
}
pub const fn message(&self) -> &'static str {
use ErrorCode::*;
match self {
ParseError => PARSE_ERROR_MSG,
OversizedRequest => OVERSIZED_REQUEST_MSG,
InvalidRequest => INVALID_REQUEST_MSG,
MethodNotFound => METHOD_NOT_FOUND_MSG,
ServerIsBusy => SERVER_IS_BUSY_MSG,
InvalidParams => INVALID_PARAMS_MSG,
InternalError => INTERNAL_ERROR_MSG,
ServerError(_) => SERVER_ERROR_MSG,
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.code(), self.message())
}
}
impl From<i32> for ErrorCode {
fn from(code: i32) -> Self {
use ErrorCode::*;
match code {
PARSE_ERROR_CODE => ParseError,
OVERSIZED_REQUEST_CODE => OversizedRequest,
INVALID_REQUEST_CODE => InvalidRequest,
METHOD_NOT_FOUND_CODE => MethodNotFound,
INVALID_PARAMS_CODE => InvalidParams,
INTERNAL_ERROR_CODE => InternalError,
code => ServerError(code),
}
}
}
impl<'a> serde::Deserialize<'a> for ErrorCode {
fn deserialize<D>(deserializer: D) -> Result<ErrorCode, D::Error>
where
D: Deserializer<'a>,
{
let code: i32 = Deserialize::deserialize(deserializer)?;
Ok(ErrorCode::from(code))
}
}
impl serde::Serialize for ErrorCode {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i32(self.code())
}
}
#[derive(Debug, thiserror::Error)]
pub enum CallError {
#[error("Invalid params in the call: {0}")]
InvalidParams(#[source] anyhow::Error),
#[error("RPC call failed: {0}")]
Failed(#[from] anyhow::Error),
#[error("RPC call failed: {0:?}")]
Custom(ErrorObject<'static>),
}
impl CallError {
pub fn from_std_error<E>(err: E) -> Self
where
E: std::error::Error + Send + Sync + 'static,
{
CallError::Failed(err.into())
}
}
pub fn reject_too_many_subscriptions(limit: u32) -> ErrorObject<'static> {
ErrorObjectOwned::owned(
TOO_MANY_SUBSCRIPTIONS_CODE,
TOO_MANY_SUBSCRIPTIONS_MSG,
Some(format!("Exceeded max limit of {}", limit)),
)
}
pub fn reject_too_big_request(limit: u32) -> ErrorObject<'static> {
ErrorObjectOwned::owned(
OVERSIZED_REQUEST_CODE,
OVERSIZED_REQUEST_MSG,
Some(format!("Exceeded max limit of {}", limit)),
)
}
#[cfg(test)]
mod tests {
use super::{ErrorCode, ErrorObject, ErrorResponse, Id, TwoPointZero};
#[test]
fn deserialize_works() {
let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}"#;
let exp = ErrorResponse {
jsonrpc: TwoPointZero,
error: ErrorObject { code: ErrorCode::ParseError, message: "Parse error".into(), data: None },
id: Id::Null,
};
let err: ErrorResponse = serde_json::from_str(ser).unwrap();
assert_eq!(exp, err);
}
#[test]
fn deserialize_with_optional_data() {
let ser = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error", "data":"vegan"},"id":null}"#;
let data = serde_json::value::to_raw_value(&"vegan").unwrap();
let exp = ErrorResponse {
jsonrpc: TwoPointZero,
error: ErrorObject::owned(ErrorCode::ParseError.code(), "Parse error", Some(data)),
id: Id::Null,
};
let err: ErrorResponse = serde_json::from_str(ser).unwrap();
assert_eq!(exp, err);
}
#[test]
fn deserialized_error_with_quoted_str() {
let raw = r#"{
"error": {
"code": 1002,
"message": "desc: \"Could not decode `ChargeAssetTxPayment::asset_id`\" } })",
"data": "\\\"validate_transaction\\\""
},
"id": 7,
"jsonrpc": "2.0"
}"#;
let err: ErrorResponse = serde_json::from_str(raw).unwrap();
let data = serde_json::value::to_raw_value(&"\\\"validate_transaction\\\"").unwrap();
assert_eq!(
err,
ErrorResponse {
error: ErrorObject::borrowed(
1002,
&"desc: \"Could not decode `ChargeAssetTxPayment::asset_id`\" } })",
Some(&*data)
),
id: Id::Number(7),
jsonrpc: TwoPointZero,
}
);
}
#[test]
fn serialize_works() {
let exp = r#"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":1337}"#;
let err = ErrorResponse {
jsonrpc: TwoPointZero,
error: ErrorObject { code: ErrorCode::InternalError, message: "Internal error".into(), data: None },
id: Id::Number(1337),
};
let ser = serde_json::to_string(&err).unwrap();
assert_eq!(exp, ser);
}
}