Exposing RPC over websockets

This commit is contained in:
Tomasz Drwięga
2016-05-27 17:46:15 +02:00
parent cf19e38663
commit c4e2f65051
9 changed files with 140 additions and 51 deletions

View File

@@ -50,6 +50,7 @@ extern crate rustc_serialize;
extern crate ethcore_util as util;
extern crate ethcore_rpc as rpc;
extern crate jsonrpc_core;
extern crate ws;
mod signing_queue;

View File

@@ -45,7 +45,7 @@ mod test {
use std::collections::HashSet;
use util::hash::Address;
use util::numbers::U256;
use rpc::v1::types::transaction_request::TransactionRequest;
use rpc::v1::types::TransactionRequest;
use super::*;
#[test]

View File

@@ -19,11 +19,14 @@
use ws;
use std;
use std::thread;
use std::default::Default;
use std::ops::Drop;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::net::SocketAddr;
use util::panics::{PanicHandler, OnPanicListener, MayPanic};
use jsonrpc_core::{IoHandler, IoDelegate};
mod session;
/// Signer startup error
#[derive(Debug)]
@@ -43,9 +46,40 @@ impl From<ws::Error> for ServerError {
}
}
/// Builder for `WebSockets` server
pub struct ServerBuilder {
handler: Arc<IoHandler>,
}
impl Default for ServerBuilder {
fn default() -> Self {
ServerBuilder::new()
}
}
impl ServerBuilder {
/// Creates new `ServerBuilder`
pub fn new() -> Self {
ServerBuilder {
handler: Arc::new(IoHandler::new())
}
}
/// Adds rpc delegate
pub fn add_delegate<D>(&self, delegate: IoDelegate<D>) where D: Send + Sync + 'static {
self.handler.add_delegate(delegate);
}
/// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped.
pub fn start(self, addr: SocketAddr) -> Result<Server, ServerError> {
Server::start(addr, self.handler)
}
}
/// `WebSockets` server implementation.
pub struct Server {
handle: Option<thread::JoinHandle<ws::WebSocket<Factory>>>,
handle: Option<thread::JoinHandle<ws::WebSocket<session::Factory>>>,
broadcaster: ws::Sender,
panic_handler: Arc<PanicHandler>,
}
@@ -53,7 +87,7 @@ pub struct Server {
impl Server {
/// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped.
pub fn start(addr: SocketAddr) -> Result<Server, ServerError> {
pub fn start(addr: SocketAddr, handler: Arc<IoHandler>) -> Result<Server, ServerError> {
let config = {
let mut config = ws::Settings::default();
config.max_connections = 5;
@@ -62,10 +96,7 @@ impl Server {
};
// Create WebSocket
let session_id = Arc::new(AtomicUsize::new(1));
let ws = try!(ws::Builder::new().with_settings(config).build(Factory {
session_id: session_id,
}));
let ws = try!(ws::Builder::new().with_settings(config).build(session::Factory::new(handler)));
let panic_handler = PanicHandler::new_in_arc();
let ph = panic_handler.clone();
@@ -98,31 +129,3 @@ impl Drop for Server {
self.handle.take().unwrap().join().unwrap();
}
}
struct Session {
id: usize,
out: ws::Sender,
}
impl ws::Handler for Session {
fn on_open(&mut self, _shake: ws::Handshake) -> ws::Result<()> {
try!(self.out.send(format!("Hello client no: {}. We are not implemented yet.", self.id)));
try!(self.out.close(ws::CloseCode::Normal));
Ok(())
}
}
struct Factory {
session_id: Arc<AtomicUsize>,
}
impl ws::Factory for Factory {
type Handler = Session;
fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler {
Session {
id: self.session_id.fetch_add(1, Ordering::SeqCst),
out: sender,
}
}
}

View File

@@ -0,0 +1,59 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Session handlers factory.
use ws;
use std::sync::Arc;
use jsonrpc_core::IoHandler;
pub struct Session {
out: ws::Sender,
handler: Arc<IoHandler>,
}
impl ws::Handler for Session {
fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
let req = try!(msg.as_text());
match self.handler.handle_request(req) {
Some(res) => self.out.send(res),
None => Ok(()),
}
}
}
pub struct Factory {
handler: Arc<IoHandler>,
}
impl Factory {
pub fn new(handler: Arc<IoHandler>) -> Self {
Factory {
handler: handler,
}
}
}
impl ws::Factory for Factory {
type Handler = Session;
fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler {
Session {
out: sender,
handler: self.handler.clone(),
}
}
}