Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

RPC middleware: Informant & Client.keep_alive #4384

Merged
merged 8 commits into from
Feb 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 24 additions & 20 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions dapps/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ use std::sync::{Arc, Mutex};
use std::net::SocketAddr;
use std::collections::HashMap;

use ethcore_rpc::Metadata;
use ethcore_rpc::{Metadata};
use fetch::{Fetch, Client as FetchClient};
use hash_fetch::urlhint::ContractClient;
use jsonrpc_core::Middleware;
use jsonrpc_core::reactor::RpcHandler;
use router::auth::{Authorization, NoAuth, HttpBasicAuth};
use parity_reactor::Remote;
Expand Down Expand Up @@ -179,7 +180,7 @@ impl<T: Fetch> ServerBuilder<T> {

/// Asynchronously start server with no authentication,
/// returns result with `Server` handle on success or an error.
pub fn start_unsecured_http(self, addr: &SocketAddr, handler: RpcHandler<Metadata>) -> Result<Server, ServerError> {
pub fn start_unsecured_http<S: Middleware<Metadata>>(self, addr: &SocketAddr, handler: RpcHandler<Metadata, S>) -> Result<Server, ServerError> {
let fetch = self.fetch_client()?;
Server::start_http(
addr,
Expand All @@ -199,7 +200,7 @@ impl<T: Fetch> ServerBuilder<T> {

/// Asynchronously start server with `HTTP Basic Authentication`,
/// return result with `Server` handle on success or an error.
pub fn start_basic_auth_http(self, addr: &SocketAddr, username: &str, password: &str, handler: RpcHandler<Metadata>) -> Result<Server, ServerError> {
pub fn start_basic_auth_http<S: Middleware<Metadata>>(self, addr: &SocketAddr, username: &str, password: &str, handler: RpcHandler<Metadata, S>) -> Result<Server, ServerError> {
let fetch = self.fetch_client()?;
Server::start_http(
addr,
Expand Down Expand Up @@ -258,11 +259,11 @@ impl Server {
}
}

fn start_http<A: Authorization + 'static, F: Fetch>(
fn start_http<A: Authorization + 'static, F: Fetch, T: Middleware<Metadata>>(
addr: &SocketAddr,
hosts: Option<Vec<String>>,
authorization: A,
handler: RpcHandler<Metadata>,
handler: RpcHandler<Metadata, T>,
dapps_path: PathBuf,
extra_dapps: Vec<PathBuf>,
signer_address: Option<(String, u16)>,
Expand Down
12 changes: 8 additions & 4 deletions dapps/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@ use std::sync::{Arc, Mutex};
use hyper;

use ethcore_rpc::{Metadata, Origin};
use jsonrpc_core::Middleware;
use jsonrpc_core::reactor::RpcHandler;
use jsonrpc_http_server::{Rpc, ServerHandler, PanicHandler, AccessControlAllowOrigin, HttpMetaExtractor};
use endpoint::{Endpoint, EndpointPath, Handler};

pub fn rpc(handler: RpcHandler<Metadata>, panic_handler: Arc<Mutex<Option<Box<Fn() -> () + Send>>>>) -> Box<Endpoint> {
pub fn rpc<T: Middleware<Metadata>>(
handler: RpcHandler<Metadata, T>,
panic_handler: Arc<Mutex<Option<Box<Fn() -> () + Send>>>>,
) -> Box<Endpoint> {
Box::new(RpcEndpoint {
handler: handler,
meta_extractor: Arc::new(MetadataExtractor),
Expand All @@ -33,15 +37,15 @@ pub fn rpc(handler: RpcHandler<Metadata>, panic_handler: Arc<Mutex<Option<Box<Fn
})
}

struct RpcEndpoint {
handler: RpcHandler<Metadata>,
struct RpcEndpoint<T: Middleware<Metadata>> {
handler: RpcHandler<Metadata, T>,
meta_extractor: Arc<HttpMetaExtractor<Metadata>>,
panic_handler: Arc<Mutex<Option<Box<Fn() -> () + Send>>>>,
cors_domain: Option<Vec<AccessControlAllowOrigin>>,
allowed_hosts: Option<Vec<String>>,
}

impl Endpoint for RpcEndpoint {
impl<T: Middleware<Metadata>> Endpoint for RpcEndpoint<T> {
fn to_async_handler(&self, _path: EndpointPath, control: hyper::Control) -> Box<Handler> {
let panic_handler = PanicHandler { handler: self.panic_handler.clone() };
Box::new(ServerHandler::new(
Expand Down
6 changes: 3 additions & 3 deletions dapps/src/tests/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use tests::helpers::{serve_with_rpc, request};
#[test]
fn should_serve_rpc() {
// given
let mut io = MetaIoHandler::new();
let mut io = MetaIoHandler::default();
io.add_method("rpc_test", |_| {
Ok(Value::String("Hello World!".into()))
});
Expand Down Expand Up @@ -53,7 +53,7 @@ fn should_serve_rpc() {
#[test]
fn should_extract_metadata() {
// given
let mut io = MetaIoHandler::new();
let mut io = MetaIoHandler::default();
io.add_method_with_meta("rpc_test", |_params, meta: Metadata| {
assert_eq!(meta.dapp_id, Some("https://parity.io/".to_owned()));
assert_eq!(meta.origin, Origin::Dapps);
Expand Down Expand Up @@ -87,7 +87,7 @@ fn should_extract_metadata() {
#[test]
fn should_extract_metadata_from_custom_header() {
// given
let mut io = MetaIoHandler::new();
let mut io = MetaIoHandler::default();
io.add_method_with_meta("rpc_test", |_params, meta: Metadata| {
assert_eq!(meta.dapp_id, Some("https://parity.io/".to_owned()));
assert_eq!(meta.origin, Origin::Dapps);
Expand Down
23 changes: 12 additions & 11 deletions ethcore/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,18 @@ impl Client {
Ok(client)
}

/// Wakes up client if it's a sleep.
pub fn keep_alive(&self) {
let should_wake = match *self.mode.lock() {
Mode::Dark(..) | Mode::Passive(..) => true,
_ => false,
};
if should_wake {
self.wake_up();
(*self.sleep_state.lock()).last_activity = Some(Instant::now());
}
}

/// Adds an actor to be notified on certain events
pub fn add_notify(&self, target: Arc<ChainNotify>) {
self.notify.write().push(Arc::downgrade(&target));
Expand Down Expand Up @@ -1011,17 +1023,6 @@ impl BlockChainClient for Client {
Ok(ret)
}

fn keep_alive(&self) {
let should_wake = match *self.mode.lock() {
Mode::Dark(..) | Mode::Passive(..) => true,
_ => false,
};
if should_wake {
self.wake_up();
(*self.sleep_state.lock()).last_activity = Some(Instant::now());
}
}

fn mode(&self) -> IpcMode {
let r = self.mode.lock().clone().into();
trace!(target: "mode", "Asked for mode = {:?}. returning {:?}", &*self.mode.lock(), r);
Expand Down
4 changes: 0 additions & 4 deletions ethcore/src/client/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ use encoded;
/// Blockchain database client. Owns and manages a blockchain and a block queue.
pub trait BlockChainClient : Sync + Send {

/// Should be called by any external-facing interface when actively using the client.
/// To minimise chatter, there's no need to call more than once every 30s.
fn keep_alive(&self) {}

/// Get raw block header data by block id.
fn block_header(&self, id: BlockId) -> Option<encoded::Header>;

Expand Down
2 changes: 1 addition & 1 deletion parity/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
}
};

let informant = Arc::new(Informant::new(client.clone(), None, None, None, cmd.with_color));
let informant = Arc::new(Informant::new(client.clone(), None, None, None, None, cmd.with_color));
service.register_io_handler(informant).map_err(|_| "Unable to register informant handler".to_owned())?;

let do_import = |bytes| {
Expand Down
4 changes: 3 additions & 1 deletion parity/dapps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use std::sync::Arc;

use dir::default_data_path;
use ethcore::client::Client;
use ethcore_rpc::informant::RpcStats;
use ethsync::SyncProvider;
use hash_fetch::fetch::Client as FetchClient;
use helpers::replace_home;
Expand Down Expand Up @@ -64,6 +65,7 @@ pub struct Dependencies {
pub remote: Remote,
pub fetch: FetchClient,
pub signer: Arc<SignerService>,
pub stats: Arc<RpcStats>,
}

pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<WebappServer>, String> {
Expand Down Expand Up @@ -174,7 +176,7 @@ mod server {
} else {
rpc_apis::ApiSet::UnsafeContext
};
let apis = rpc_apis::setup_rpc(Default::default(), deps.apis.clone(), api_set);
let apis = rpc_apis::setup_rpc(deps.stats, deps.apis.clone(), api_set);
let handler = RpcHandler::new(Arc::new(apis), deps.remote);
let start_result = match auth {
None => {
Expand Down
Loading