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
use std::io;
use std::io::Read;
use std::sync::{Arc, Mutex};
use hyper::client::Client as HyperClient;
use hyper::header::{Headers, Authorization, Basic};
use hyper;
use strason::{self, Json};
use super::{Request, Response};
use error::Error;
pub struct Client {
url: String,
user: Option<String>,
pass: Option<String>,
client: HyperClient,
nonce: Arc<Mutex<u64>>
}
impl Client {
pub fn new(url: String, user: Option<String>, pass: Option<String>) -> Client {
debug_assert!(pass.is_none() || user.is_some());
Client {
url: url,
user: user,
pass: pass,
client: HyperClient::new(),
nonce: Arc::new(Mutex::new(0))
}
}
pub fn send_request(&self, request: &Request) -> Result<Response, Error> {
let request_json = try!(strason::from_serialize(request));
let request_raw = request_json.to_bytes();
let mut headers = Headers::new();
if let Some(ref user) = self.user {
headers.set(Authorization(Basic {
username: user.clone(),
password: self.pass.clone()
}));
}
let retry_headers = headers.clone();
let hyper_request = self.client.post(&self.url).headers(headers).body(&request_raw[..]);
let mut stream = match hyper_request.send() {
Ok(s) => s,
Err(hyper::error::Error::Io(e)) => {
if e.kind() == io::ErrorKind::ConnectionAborted {
try!(self.client.post(&self.url).headers(retry_headers)
.body(&request_raw[..])
.send().map_err(Error::Hyper))
} else {
return Err(Error::Hyper(hyper::error::Error::Io(e)));
}
}
Err(e) => { return Err(Error::Hyper(e)); }
};
let response_json = try!(Json::from_reader(&mut stream));
stream.bytes().count();
let response: Response = try!(response_json.into_deserialize());
if response.jsonrpc != None &&
response.jsonrpc != Some(From::from("2.0")) {
return Err(Error::VersionMismatch);
}
if response.id != request.id {
return Err(Error::NonceMismatch);
}
Ok(response)
}
pub fn build_request(&self, name: String, params: Vec<Json>) -> Request {
let mut nonce = self.nonce.lock().unwrap();
*nonce += 1;
Request {
method: name,
params: params,
id: From::from(*nonce),
jsonrpc: Some(String::from("2.0"))
}
}
pub fn last_nonce(&self) -> u64 {
*self.nonce.lock().unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanity() {
let client = Client::new("localhost".to_owned(), None, None);
assert_eq!(client.last_nonce(), 0);
let req1 = client.build_request("test".to_owned(), vec![]);
assert_eq!(client.last_nonce(), 1);
let req2 = client.build_request("test".to_owned(), vec![]);
assert_eq!(client.last_nonce(), 2);
assert!(req1 != req2);
}
}