2016-10-17 14:59:41 +02:00
|
|
|
extern crate jsonrpc_core;
|
|
|
|
|
2016-09-20 12:19:07 +02:00
|
|
|
use std::fmt::{Debug, Formatter, Error as FmtError};
|
|
|
|
use std::io::{BufReader, BufRead};
|
2016-10-17 15:06:45 +02:00
|
|
|
use std::sync::Arc;
|
2016-09-20 12:19:07 +02:00
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
use std::collections::BTreeMap;
|
|
|
|
use std::thread;
|
|
|
|
use std::time;
|
|
|
|
|
|
|
|
use std::path::PathBuf;
|
2016-10-17 15:06:45 +02:00
|
|
|
use util::{Hashable, Mutex};
|
2016-09-20 12:19:07 +02:00
|
|
|
use url::Url;
|
|
|
|
use std::fs::File;
|
|
|
|
|
2016-11-02 17:14:05 +01:00
|
|
|
use ws::{
|
|
|
|
self,
|
|
|
|
Request,
|
|
|
|
Handler,
|
|
|
|
Sender,
|
|
|
|
Handshake,
|
|
|
|
Error as WsError,
|
|
|
|
ErrorKind as WsErrorKind,
|
|
|
|
Message,
|
2016-12-13 12:17:01 +01:00
|
|
|
Result as WsResult,
|
2016-11-02 17:14:05 +01:00
|
|
|
};
|
2016-09-20 12:19:07 +02:00
|
|
|
|
|
|
|
use serde::Deserialize;
|
2016-12-13 12:17:01 +01:00
|
|
|
use serde_json::{
|
|
|
|
self as json,
|
|
|
|
Value as JsonValue,
|
|
|
|
Error as JsonError,
|
|
|
|
};
|
2016-09-20 12:19:07 +02:00
|
|
|
|
|
|
|
use futures::{BoxFuture, Canceled, Complete, Future, oneshot, done};
|
|
|
|
|
2016-10-17 14:59:41 +02:00
|
|
|
use jsonrpc_core::{Id, Version, Params, Error as JsonRpcError};
|
|
|
|
use jsonrpc_core::request::MethodCall;
|
2016-12-15 19:31:26 +01:00
|
|
|
use jsonrpc_core::response::{Output, Success, Failure};
|
2016-10-17 14:59:41 +02:00
|
|
|
|
2016-09-20 12:19:07 +02:00
|
|
|
/// The actual websocket connection handler, passed into the
|
|
|
|
/// event loop of ws-rs
|
|
|
|
struct RpcHandler {
|
|
|
|
pending: Pending,
|
2016-10-17 14:59:41 +02:00
|
|
|
// Option is used here as temporary storage until connection
|
|
|
|
// is setup and the values are moved into the new `Rpc`
|
2016-09-20 12:19:07 +02:00
|
|
|
complete: Option<Complete<Result<Rpc, RpcError>>>,
|
|
|
|
auth_code: String,
|
|
|
|
out: Option<Sender>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RpcHandler {
|
2016-11-02 15:55:03 +01:00
|
|
|
fn new(
|
|
|
|
out: Sender,
|
|
|
|
auth_code: String,
|
|
|
|
complete: Complete<Result<Rpc, RpcError>>
|
|
|
|
) -> Self {
|
2016-09-20 12:19:07 +02:00
|
|
|
RpcHandler {
|
|
|
|
out: Some(out),
|
|
|
|
auth_code: auth_code,
|
|
|
|
pending: Pending::new(),
|
|
|
|
complete: Some(complete),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Handler for RpcHandler {
|
2016-12-15 15:03:34 +01:00
|
|
|
fn build_request(&mut self, url: &Url) -> WsResult<Request> {
|
2016-09-20 12:19:07 +02:00
|
|
|
match Request::from_url(url) {
|
|
|
|
Ok(mut r) => {
|
2016-12-27 12:53:56 +01:00
|
|
|
let timestamp = time::UNIX_EPOCH.elapsed().map_err(|err| {
|
2016-09-30 15:30:17 +02:00
|
|
|
WsError::new(WsErrorKind::Internal, format!("{}", err))
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-09-30 15:30:17 +02:00
|
|
|
let secs = timestamp.as_secs();
|
|
|
|
let hashed = format!("{}:{}", self.auth_code, secs).sha3();
|
|
|
|
let proto = format!("{:?}_{}", hashed, secs);
|
2016-09-20 12:19:07 +02:00
|
|
|
r.add_protocol(&proto);
|
|
|
|
Ok(r)
|
|
|
|
},
|
2016-11-02 17:14:05 +01:00
|
|
|
Err(e) =>
|
|
|
|
Err(WsError::new(WsErrorKind::Internal, format!("{}", e))),
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-15 15:03:34 +01:00
|
|
|
}
|
|
|
|
fn on_error(&mut self, err: WsError) {
|
2016-09-30 15:30:17 +02:00
|
|
|
match self.complete.take() {
|
2016-09-20 12:19:07 +02:00
|
|
|
Some(c) => c.complete(Err(RpcError::WsError(err))),
|
2016-09-30 15:30:17 +02:00
|
|
|
None => println!("unexpected error: {}", err),
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-15 15:03:34 +01:00
|
|
|
}
|
|
|
|
fn on_open(&mut self, _: Handshake) -> WsResult<()> {
|
2016-09-30 15:30:17 +02:00
|
|
|
match (self.complete.take(), self.out.take()) {
|
|
|
|
(Some(c), Some(out)) => {
|
|
|
|
c.complete(Ok(Rpc {
|
|
|
|
out: out,
|
|
|
|
counter: AtomicUsize::new(0),
|
|
|
|
pending: self.pending.clone(),
|
|
|
|
}));
|
|
|
|
Ok(())
|
|
|
|
},
|
|
|
|
_ => {
|
2016-11-02 17:14:05 +01:00
|
|
|
let msg = format!("on_open called twice");
|
|
|
|
Err(WsError::new(WsErrorKind::Internal, msg))
|
2016-09-30 15:30:17 +02:00
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
}
|
2016-12-15 15:03:34 +01:00
|
|
|
fn on_message(&mut self, msg: Message) -> WsResult<()> {
|
2016-10-17 14:59:41 +02:00
|
|
|
let ret: Result<JsonValue, JsonRpcError>;
|
|
|
|
let response_id;
|
|
|
|
let string = &msg.to_string();
|
2016-12-15 19:31:26 +01:00
|
|
|
match json::from_str::<Output>(&string) {
|
|
|
|
Ok(Output::Success(Success { result, id: Id::Num(id), .. })) =>
|
2016-11-02 17:14:05 +01:00
|
|
|
{
|
2016-10-17 14:59:41 +02:00
|
|
|
ret = Ok(result);
|
|
|
|
response_id = id as usize;
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-15 19:31:26 +01:00
|
|
|
Ok(Output::Failure(Failure { error, id: Id::Num(id), .. })) => {
|
2016-10-17 14:59:41 +02:00
|
|
|
ret = Err(error);
|
|
|
|
response_id = id as usize;
|
|
|
|
}
|
|
|
|
Err(e) => {
|
2016-11-02 17:14:05 +01:00
|
|
|
warn!(
|
|
|
|
target: "rpc-client",
|
|
|
|
"recieved invalid message: {}\n {:?}",
|
|
|
|
string,
|
|
|
|
e
|
|
|
|
);
|
2016-10-17 14:59:41 +02:00
|
|
|
return Ok(())
|
|
|
|
},
|
|
|
|
_ => {
|
2016-11-02 17:14:05 +01:00
|
|
|
warn!(
|
|
|
|
target: "rpc-client",
|
|
|
|
"recieved invalid message: {}",
|
|
|
|
string
|
|
|
|
);
|
2016-10-17 14:59:41 +02:00
|
|
|
return Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
match self.pending.remove(response_id) {
|
|
|
|
Some(c) => c.complete(ret.map_err(|err| {
|
|
|
|
RpcError::JsonRpc(err)
|
|
|
|
})),
|
2016-11-02 17:14:05 +01:00
|
|
|
None => warn!(
|
|
|
|
target: "rpc-client",
|
|
|
|
"warning: unexpected id: {}",
|
|
|
|
response_id
|
|
|
|
),
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
Ok(())
|
2016-12-15 15:03:34 +01:00
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Keeping track of issued requests to be matched up with responses
|
|
|
|
#[derive(Clone)]
|
2016-11-02 17:14:05 +01:00
|
|
|
struct Pending(
|
|
|
|
Arc<Mutex<BTreeMap<usize, Complete<Result<JsonValue, RpcError>>>>>
|
|
|
|
);
|
2016-09-20 12:19:07 +02:00
|
|
|
|
|
|
|
impl Pending {
|
|
|
|
fn new() -> Self {
|
|
|
|
Pending(Arc::new(Mutex::new(BTreeMap::new())))
|
|
|
|
}
|
|
|
|
fn insert(&mut self, k: usize, v: Complete<Result<JsonValue, RpcError>>) {
|
2016-10-17 15:06:45 +02:00
|
|
|
self.0.lock().insert(k, v);
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-11-02 17:14:05 +01:00
|
|
|
fn remove(
|
|
|
|
&mut self,
|
|
|
|
k: usize
|
|
|
|
) -> Option<Complete<Result<JsonValue, RpcError>>> {
|
2016-10-17 15:06:45 +02:00
|
|
|
self.0.lock().remove(&k)
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_authcode(path: &PathBuf) -> Result<String, RpcError> {
|
2016-12-13 12:17:01 +01:00
|
|
|
if let Ok(fd) = File::open(path) {
|
|
|
|
if let Some(Ok(line)) = BufReader::new(fd).lines().next() {
|
|
|
|
let mut parts = line.split(';');
|
|
|
|
let token = parts.next();
|
|
|
|
|
|
|
|
if let Some(code) = token {
|
|
|
|
return Ok(code.into());
|
|
|
|
}
|
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-13 12:17:01 +01:00
|
|
|
Err(RpcError::NoAuthCode)
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The handle to the connection
|
|
|
|
pub struct Rpc {
|
|
|
|
out: Sender,
|
|
|
|
counter: AtomicUsize,
|
|
|
|
pending: Pending,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Rpc {
|
|
|
|
/// Blocking, returns a new initialized connection or RpcError
|
|
|
|
pub fn new(url: &str, authpath: &PathBuf) -> Result<Self, RpcError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
let rpc = Self::connect(url, authpath).map(|rpc| rpc).wait()?;
|
2016-09-20 12:19:07 +02:00
|
|
|
rpc
|
|
|
|
}
|
|
|
|
/// Non-blocking, returns a future
|
2016-11-02 15:55:03 +01:00
|
|
|
pub fn connect(
|
|
|
|
url: &str, authpath: &PathBuf
|
|
|
|
) -> BoxFuture<Result<Self, RpcError>, Canceled> {
|
2016-09-20 12:19:07 +02:00
|
|
|
let (c, p) = oneshot::<Result<Self, RpcError>>();
|
|
|
|
match get_authcode(authpath) {
|
|
|
|
Err(e) => return done(Ok(Err(e))).boxed(),
|
|
|
|
Ok(code) => {
|
|
|
|
let url = String::from(url);
|
2016-11-02 17:14:05 +01:00
|
|
|
// The ws::connect takes a FnMut closure, which means c cannot
|
|
|
|
// be moved into it, since it's consumed on complete.
|
2016-10-06 12:07:09 +02:00
|
|
|
// Therefore we wrap it in an option and pick it out once.
|
2016-09-30 15:30:17 +02:00
|
|
|
let mut once = Some(c);
|
2016-09-20 12:19:07 +02:00
|
|
|
thread::spawn(move || {
|
2016-09-30 15:30:17 +02:00
|
|
|
let conn = ws::connect(url, |out| {
|
2016-10-06 12:07:09 +02:00
|
|
|
// this will panic if the closure is called twice,
|
|
|
|
// which it should never be.
|
2016-11-02 17:14:05 +01:00
|
|
|
let c = once.take()
|
|
|
|
.expect("connection closure called only once");
|
2016-09-20 12:19:07 +02:00
|
|
|
RpcHandler::new(out, code.clone(), c)
|
2016-09-30 15:30:17 +02:00
|
|
|
});
|
|
|
|
match conn {
|
2016-09-20 12:19:07 +02:00
|
|
|
Err(err) => {
|
2016-09-30 15:30:17 +02:00
|
|
|
// since ws::connect is only called once, it cannot
|
|
|
|
// both fail and succeed.
|
2016-11-02 17:14:05 +01:00
|
|
|
let c = once.take()
|
|
|
|
.expect("connection closure called only once");
|
2016-09-20 12:19:07 +02:00
|
|
|
c.complete(Err(RpcError::WsError(err)));
|
|
|
|
},
|
|
|
|
// c will complete on the `on_open` event in the Handler
|
|
|
|
_ => ()
|
|
|
|
}
|
|
|
|
});
|
|
|
|
p.boxed()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/// Non-blocking, returns a future of the request response
|
2016-11-02 15:55:03 +01:00
|
|
|
pub fn request<T>(
|
|
|
|
&mut self, method: &'static str, params: Vec<JsonValue>
|
|
|
|
) -> BoxFuture<Result<T, RpcError>, Canceled>
|
2016-09-20 12:19:07 +02:00
|
|
|
where T: Deserialize + Send + Sized {
|
|
|
|
|
|
|
|
let (c, p) = oneshot::<Result<JsonValue, RpcError>>();
|
|
|
|
|
|
|
|
let id = self.counter.fetch_add(1, Ordering::Relaxed);
|
|
|
|
self.pending.insert(id, c);
|
|
|
|
|
2016-10-17 14:59:41 +02:00
|
|
|
let request = MethodCall {
|
|
|
|
jsonrpc: Version::V2,
|
|
|
|
method: method.to_owned(),
|
|
|
|
params: Some(Params::Array(params)),
|
|
|
|
id: Id::Num(id as u64),
|
|
|
|
};
|
|
|
|
|
2016-11-02 17:14:05 +01:00
|
|
|
let serialized = json::to_string(&request)
|
|
|
|
.expect("request is serializable");
|
2016-09-20 12:19:07 +02:00
|
|
|
let _ = self.out.send(serialized);
|
|
|
|
|
|
|
|
p.map(|result| {
|
|
|
|
match result {
|
|
|
|
Ok(json) => {
|
2016-12-27 12:53:56 +01:00
|
|
|
let t: T = json::from_value(json)?;
|
2016-09-20 12:19:07 +02:00
|
|
|
Ok(t)
|
|
|
|
},
|
|
|
|
Err(err) => Err(err)
|
|
|
|
}
|
|
|
|
}).boxed()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub enum RpcError {
|
|
|
|
WrongVersion(String),
|
|
|
|
ParseError(JsonError),
|
|
|
|
MalformedResponse(String),
|
2016-10-17 14:59:41 +02:00
|
|
|
JsonRpc(JsonRpcError),
|
2016-09-20 12:19:07 +02:00
|
|
|
WsError(WsError),
|
|
|
|
Canceled(Canceled),
|
|
|
|
UnexpectedId,
|
|
|
|
NoAuthCode,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debug for RpcError {
|
|
|
|
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
|
2016-10-17 14:59:41 +02:00
|
|
|
match *self {
|
|
|
|
RpcError::WrongVersion(ref s)
|
2016-09-20 12:19:07 +02:00
|
|
|
=> write!(f, "Expected version 2.0, got {}", s),
|
2016-10-17 14:59:41 +02:00
|
|
|
RpcError::ParseError(ref err)
|
2016-09-20 12:19:07 +02:00
|
|
|
=> write!(f, "ParseError: {}", err),
|
2016-10-17 14:59:41 +02:00
|
|
|
RpcError::MalformedResponse(ref s)
|
2016-09-20 12:19:07 +02:00
|
|
|
=> write!(f, "Malformed response: {}", s),
|
2016-10-17 14:59:41 +02:00
|
|
|
RpcError::JsonRpc(ref json)
|
|
|
|
=> write!(f, "JsonRpc error: {:?}", json),
|
|
|
|
RpcError::WsError(ref s)
|
2016-09-20 12:19:07 +02:00
|
|
|
=> write!(f, "Websocket error: {}", s),
|
2016-10-17 14:59:41 +02:00
|
|
|
RpcError::Canceled(ref s)
|
2016-09-20 12:19:07 +02:00
|
|
|
=> write!(f, "Futures error: {:?}", s),
|
2016-10-17 14:59:41 +02:00
|
|
|
RpcError::UnexpectedId
|
2016-09-20 12:19:07 +02:00
|
|
|
=> write!(f, "Unexpected response id"),
|
2016-10-17 14:59:41 +02:00
|
|
|
RpcError::NoAuthCode
|
2016-09-20 12:19:07 +02:00
|
|
|
=> write!(f, "No authcodes available"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JsonError> for RpcError {
|
|
|
|
fn from(err: JsonError) -> RpcError {
|
|
|
|
RpcError::ParseError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<WsError> for RpcError {
|
|
|
|
fn from(err: WsError) -> RpcError {
|
|
|
|
RpcError::WsError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<Canceled> for RpcError {
|
|
|
|
fn from(err: Canceled) -> RpcError {
|
|
|
|
RpcError::Canceled(err)
|
|
|
|
}
|
|
|
|
}
|