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
use std::fmt;
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::atomic;
use serde;
use serde_json;
use serde_json::value::RawValue;
use super::{Request, Response};
use util::HashableValue;
use error::Error;
pub trait Transport: Send + Sync + 'static {
fn send_request(&self, Request) -> Result<Response, Error>;
fn send_batch(&self, &[Request]) -> Result<Vec<Response>, Error>;
fn fmt_target(&self, f: &mut fmt::Formatter) -> fmt::Result;
}
pub struct Client {
pub(crate) transport: Box<dyn Transport>,
nonce: atomic::AtomicUsize,
}
impl Client {
pub fn with_transport<T: Transport>(transport: T) -> Client {
Client {
transport: Box::new(transport),
nonce: atomic::AtomicUsize::new(1),
}
}
pub fn build_request<'a>(
&self,
method: &'a str,
params: &'a [Box<RawValue>],
) -> Request<'a> {
let nonce = self.nonce.fetch_add(1, atomic::Ordering::Relaxed);
Request {
method: method,
params: params,
id: serde_json::Value::from(nonce),
jsonrpc: Some("2.0"),
}
}
pub fn send_request(&self, request: Request) -> Result<Response, Error> {
self.transport.send_request(request)
}
pub fn send_batch(&self, requests: &[Request]) -> Result<Vec<Option<Response>>, Error> {
if requests.is_empty() {
return Err(Error::EmptyBatch);
}
let responses = self.transport.send_batch(requests)?;
if responses.len() > requests.len() {
return Err(Error::WrongBatchResponseSize);
}
let mut by_id = HashMap::with_capacity(requests.len());
for resp in responses.into_iter() {
let id = HashableValue(Cow::Owned(resp.id.clone()));
if let Some(dup) = by_id.insert(id, resp) {
return Err(Error::BatchDuplicateResponseId(dup.id));
}
}
let results = requests.into_iter().map(|r| {
by_id.remove(&HashableValue(Cow::Borrowed(&r.id)))
}).collect();
if let Some((id, _)) = by_id.into_iter().nth(0) {
return Err(Error::WrongBatchResponseId(id.0.into_owned()));
}
Ok(results)
}
pub fn call<R: for<'a> serde::de::Deserialize<'a>>(
&self,
method: &str,
args: &[Box<RawValue>],
) -> Result<R, Error> {
let request = self.build_request(method, args);
let id = request.id.clone();
let response = self.send_request(request)?;
if response.jsonrpc != None && response.jsonrpc != Some(From::from("2.0")) {
return Err(Error::VersionMismatch);
}
if response.id != id {
return Err(Error::NonceMismatch);
}
Ok(response.result()?)
}
}
impl fmt::Debug for ::Client {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "jsonrpc::Client(")?;
self.transport.fmt_target(f)?;
write!(f, ")")
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync;
struct DummyTransport;
impl Transport for DummyTransport {
fn send_request(&self, _: Request) -> Result<Response, Error> { Err(Error::NonceMismatch) }
fn send_batch(&self, _: &[Request]) -> Result<Vec<Response>, Error> { Ok(vec![]) }
fn fmt_target(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
}
#[test]
fn sanity() {
let client = Client::with_transport(DummyTransport);
assert_eq!(client.nonce.load(sync::atomic::Ordering::Relaxed), 1);
let req1 = client.build_request("test", &[]);
assert_eq!(client.nonce.load(sync::atomic::Ordering::Relaxed), 2);
let req2 = client.build_request("test", &[]);
assert_eq!(client.nonce.load(sync::atomic::Ordering::Relaxed), 3);
assert!(req1.id != req2.id);
}
}