Getting regular endpoint functions to return futures.

- Wrapped endpoint functions in new into_boxfut function
 - Undid changes to Network API service, now returning ApiResult again.
 - Cleaning up of functions, and removal of success_response functions in updated endpoints.
 - A bunch of other clean-ups.
This commit is contained in:
Luke Anderson 2019-09-12 15:20:31 +10:00
parent 82f4303787
commit cd8f40b4b7
No known key found for this signature in database
GPG Key ID: 44408169EC61E228
7 changed files with 50 additions and 52 deletions

View File

@ -191,13 +191,7 @@ pub fn get_state<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult
Ok(query) => { Ok(query) => {
// We have *some* parameters, just check them. // We have *some* parameters, just check them.
let query_params = ["root", "slot"]; let query_params = ["root", "slot"];
match query.first_of(&query_params) { query.first_of(&query_params)?
Ok((k, v)) => (k, v),
Err(e) => {
// Wrong parameters provided, or another error, return the error.
return Err(e);
}
}
} }
Err(ApiError::InvalidQueryParams(_)) => { Err(ApiError::InvalidQueryParams(_)) => {
// No parameters provided at all, use current slot. // No parameters provided at all, use current slot.

View File

@ -1,4 +1,6 @@
use crate::BoxFut; use crate::BoxFut;
use futures::future::IntoFuture;
use futures::Future;
use hyper::{Body, Method, Request, Response, Server, StatusCode}; use hyper::{Body, Method, Request, Response, Server, StatusCode};
use std::error::Error as StdError; use std::error::Error as StdError;

View File

@ -21,6 +21,7 @@ use client_network::NetworkMessage;
use client_network::Service as NetworkService; use client_network::Service as NetworkService;
use error::{ApiError, ApiResult}; use error::{ApiError, ApiResult};
use eth2_config::Eth2Config; use eth2_config::Eth2Config;
use futures::future::IntoFuture;
use hyper::rt::Future; use hyper::rt::Future;
use hyper::server::conn::AddrStream; use hyper::server::conn::AddrStream;
use hyper::service::{MakeService, Service}; use hyper::service::{MakeService, Service};
@ -33,7 +34,6 @@ use std::sync::Arc;
use tokio::runtime::TaskExecutor; use tokio::runtime::TaskExecutor;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use url_query::UrlQuery; use url_query::UrlQuery;
use futures::future::IntoFuture;
pub use beacon::{BlockResponse, HeadResponse, StateResponse}; pub use beacon::{BlockResponse, HeadResponse, StateResponse};
pub use config::Config as ApiConfig; pub use config::Config as ApiConfig;
@ -51,6 +51,14 @@ pub struct ApiService<T: BeaconChainTypes + 'static> {
eth2_config: Arc<Eth2Config>, eth2_config: Arc<Eth2Config>,
} }
fn into_boxfut<F: IntoFuture + 'static>(item: F) -> BoxFut
where
F: IntoFuture<Item = Response<Body>, Error = ApiError>,
F::Future: Send,
{
Box::new(item.into_future())
}
impl<T: BeaconChainTypes> Service for ApiService<T> { impl<T: BeaconChainTypes> Service for ApiService<T> {
type ReqBody = Body; type ReqBody = Body;
type ResBody = Body; type ResBody = Body;
@ -82,20 +90,25 @@ impl<T: BeaconChainTypes> Service for ApiService<T> {
// Route the request to the correct handler. // Route the request to the correct handler.
let result = match (req.method(), path.as_ref()) { let result = match (req.method(), path.as_ref()) {
// Methods for Client // Methods for Client
(&Method::GET, "/node/version") => Box::new(node::get_version(req).into_future()), (&Method::GET, "/node/version") => into_boxfut(node::get_version(req)),
(&Method::GET, "/node/genesis_time") => Box::new(node::get_genesis_time::<T>(req).into_future()), (&Method::GET, "/node/genesis_time") => into_boxfut(node::get_genesis_time::<T>(req)),
(&Method::GET, "/node/syncing") => Box::new(helpers::implementation_pending_response(req).into_future()), (&Method::GET, "/node/syncing") => {
/* into_boxfut(helpers::implementation_pending_response(req))
}
// Methods for Network // Methods for Network
(&Method::GET, "/network/enr") => network::get_enr::<T>(req), (&Method::GET, "/network/enr") => into_boxfut(network::get_enr::<T>(req)),
(&Method::GET, "/network/peer_count") => network::get_peer_count::<T>(req), (&Method::GET, "/network/peer_count") => into_boxfut(network::get_peer_count::<T>(req)),
(&Method::GET, "/network/peer_id") => network::get_peer_id::<T>(req), (&Method::GET, "/network/peer_id") => into_boxfut(network::get_peer_id::<T>(req)),
(&Method::GET, "/network/peers") => network::get_peer_list::<T>(req), (&Method::GET, "/network/peers") => into_boxfut(network::get_peer_list::<T>(req)),
(&Method::GET, "/network/listen_port") => network::get_listen_port::<T>(req), (&Method::GET, "/network/listen_port") => {
(&Method::GET, "/network/listen_addresses") => network::get_listen_addresses::<T>(req), into_boxfut(network::get_listen_port::<T>(req))
}
(&Method::GET, "/network/listen_addresses") => {
into_boxfut(network::get_listen_addresses::<T>(req))
}
/* /*
// Methods for Beacon Node // Methods for Beacon Node
(&Method::GET, "/beacon/head") => beacon::get_head::<T>(req), (&Method::GET, "/beacon/head") => beacon::get_head::<T>(req),
(&Method::GET, "/beacon/block") => beacon::get_block::<T>(req), (&Method::GET, "/beacon/block") => beacon::get_block::<T>(req),

View File

@ -1,5 +1,7 @@
use crate::error::{ApiError, ApiResult};
use crate::helpers::*; use crate::helpers::*;
use crate::{ApiError, BoxFut, NetworkService}; use crate::response_builder::ResponseBuilder;
use crate::NetworkService;
use beacon_chain::BeaconChainTypes; use beacon_chain::BeaconChainTypes;
use eth2_libp2p::{Enr, Multiaddr, PeerId}; use eth2_libp2p::{Enr, Multiaddr, PeerId};
use hyper::{Body, Request}; use hyper::{Body, Request};
@ -8,81 +10,70 @@ use std::sync::Arc;
/// HTTP handler to return the list of libp2p multiaddr the client is listening on. /// HTTP handler to return the list of libp2p multiaddr the client is listening on.
/// ///
/// Returns a list of `Multiaddr`, serialized according to their `serde` impl. /// Returns a list of `Multiaddr`, serialized according to their `serde` impl.
pub fn get_listen_addresses<T: BeaconChainTypes>(req: Request<Body>) -> BoxFut { pub fn get_listen_addresses<T: BeaconChainTypes>(req: Request<Body>) -> ApiResult {
let network = req let network = req
.extensions() .extensions()
.get::<Arc<NetworkService<T>>>() .get::<Arc<NetworkService<T>>>()
.expect("The network service should always be there, we put it there"); .expect("The network service should always be there, we put it there");
let multiaddresses: Vec<Multiaddr> = network.listen_multiaddrs(); let multiaddresses: Vec<Multiaddr> = network.listen_multiaddrs();
success_response_json(req, &multiaddresses) ResponseBuilder::new(&req).body_json(&multiaddresses)
} }
/// HTTP handler to return the network port the client is listening on. /// HTTP handler to return the network port the client is listening on.
/// ///
/// Returns the TCP port number in its plain form (which is also valid JSON serialization) /// Returns the TCP port number in its plain form (which is also valid JSON serialization)
pub fn get_listen_port<T: BeaconChainTypes>(req: Request<Body>) -> BoxFut { pub fn get_listen_port<T: BeaconChainTypes>(req: Request<Body>) -> ApiResult {
let network = req let network = req
.extensions() .extensions()
.get::<Arc<NetworkService<T>>>() .get::<Arc<NetworkService<T>>>()
.expect("The network service should always be there, we put it there") .expect("The network service should always be there, we put it there")
.clone(); .clone();
ResponseBuilder::new(&req).body(&network.listen_port())
success_response(req, &network.listen_port())
} }
/// HTTP handler to return the Discv5 ENR from the client's libp2p service. /// HTTP handler to return the Discv5 ENR from the client's libp2p service.
/// ///
/// ENR is encoded as base64 string. /// ENR is encoded as base64 string.
pub fn get_enr<T: BeaconChainTypes>(req: Request<Body>) -> BoxFut { pub fn get_enr<T: BeaconChainTypes>(req: Request<Body>) -> ApiResult {
let network = req let network = req
.extensions() .extensions()
.get::<Arc<NetworkService<T>>>() .get::<Arc<NetworkService<T>>>()
.expect("The network service should always be there, we put it there"); .expect("The network service should always be there, we put it there");
ResponseBuilder::new(&req).body_json(&network.local_enr().to_base64())
let enr: Enr = network.local_enr();
success_response_json(req, &enr.to_base64())
} }
/// HTTP handler to return the `PeerId` from the client's libp2p service. /// HTTP handler to return the `PeerId` from the client's libp2p service.
/// ///
/// PeerId is encoded as base58 string. /// PeerId is encoded as base58 string.
pub fn get_peer_id<T: BeaconChainTypes>(req: Request<Body>) -> BoxFut { pub fn get_peer_id<T: BeaconChainTypes>(req: Request<Body>) -> ApiResult {
let network = req let network = req
.extensions() .extensions()
.get::<Arc<NetworkService<T>>>() .get::<Arc<NetworkService<T>>>()
.expect("The network service should always be there, we put it there"); .expect("The network service should always be there, we put it there");
ResponseBuilder::new(&req).body_json(&network.local_peer_id().to_base58())
let peer_id: PeerId = network.local_peer_id();
success_response_json(req, &peer_id.to_base58())
} }
/// HTTP handler to return the number of peers connected in the client's libp2p service. /// HTTP handler to return the number of peers connected in the client's libp2p service.
pub fn get_peer_count<T: BeaconChainTypes>(req: Request<Body>) -> BoxFut { pub fn get_peer_count<T: BeaconChainTypes>(req: Request<Body>) -> ApiResult {
let network = req let network = req
.extensions() .extensions()
.get::<Arc<NetworkService<T>>>() .get::<Arc<NetworkService<T>>>()
.expect("The network service should always be there, we put it there"); .expect("The network service should always be there, we put it there");
ResponseBuilder::new(&req).body(&network.connected_peers())
let connected_peers: usize = network.connected_peers();
success_response(req, &connected_peers)
} }
/// HTTP handler to return the list of peers connected to the client's libp2p service. /// HTTP handler to return the list of peers connected to the client's libp2p service.
/// ///
/// Peers are presented as a list of `PeerId::to_string()`. /// Peers are presented as a list of `PeerId::to_string()`.
pub fn get_peer_list<T: BeaconChainTypes>(req: Request<Body>) -> BoxFut { pub fn get_peer_list<T: BeaconChainTypes>(req: Request<Body>) -> ApiResult {
let network = req let network = req
.extensions() .extensions()
.get::<Arc<NetworkService<T>>>() .get::<Arc<NetworkService<T>>>()
.expect("The network service should always be there, we put it there"); .expect("The network service should always be there, we put it there");
let connected_peers: Vec<String> = network let connected_peers: Vec<String> = network
.connected_peer_set() .connected_peer_set()
.iter() .iter()
.map(PeerId::to_string) .map(PeerId::to_string)
.collect(); .collect();
ResponseBuilder::new(&req).body_json(&connected_peers)
success_response_json(req, &connected_peers)
} }

View File

@ -1,4 +1,5 @@
use crate::helpers::*; use crate::helpers::*;
use crate::response_builder::ResponseBuilder;
use crate::{ApiResult, BoxFut}; use crate::{ApiResult, BoxFut};
use beacon_chain::BeaconChainTypes; use beacon_chain::BeaconChainTypes;
use hyper::{Body, Request}; use hyper::{Body, Request};
@ -6,13 +7,12 @@ use version;
/// Read the version string from the current Lighthouse build. /// Read the version string from the current Lighthouse build.
pub fn get_version(req: Request<Body>) -> ApiResult { pub fn get_version(req: Request<Body>) -> ApiResult {
success_response_2_json(req, &version::version()) ResponseBuilder::new(&req).body_json(&version::version())
} }
/// Read the genesis time from the current beacon chain state. /// Read the genesis time from the current beacon chain state.
pub fn get_genesis_time<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult { pub fn get_genesis_time<T: BeaconChainTypes + 'static>(req: Request<Body>) -> ApiResult {
let beacon_chain = get_beacon_chain_from_request::<T>(&req)?; let beacon_chain = get_beacon_chain_from_request::<T>(&req)?;
let head_state = get_head_state(beacon_chain)?; let head_state = get_head_state(beacon_chain)?;
let gen_time: u64 = head_state.genesis_time; ResponseBuilder::new(&req).body(&head_state.genesis_time)
success_response_2(req, &gen_time)
} }

View File

@ -1,6 +1,6 @@
use crate::helpers::*; use crate::helpers::*;
use crate::response_builder::ResponseBuilder; use crate::response_builder::ResponseBuilder;
use crate::{ApiError, ApiResult, UrlQuery, BoxFut}; use crate::{ApiError, ApiResult, BoxFut, UrlQuery};
use beacon_chain::{BeaconChainTypes, BlockProcessingOutcome}; use beacon_chain::{BeaconChainTypes, BlockProcessingOutcome};
use bls::{AggregateSignature, PublicKey, Signature}; use bls::{AggregateSignature, PublicKey, Signature};
use futures::future::Future; use futures::future::Future;
@ -197,7 +197,7 @@ pub fn get_new_beacon_block<T: BeaconChainTypes + 'static>(req: Request<Body>) -
pub fn publish_beacon_block<T: BeaconChainTypes + 'static>(req: Request<Body>) -> BoxFut { pub fn publish_beacon_block<T: BeaconChainTypes + 'static>(req: Request<Body>) -> BoxFut {
let _ = try_future!(check_content_type_for_json(&req)); let _ = try_future!(check_content_type_for_json(&req));
let log = get_logger_from_request(&req); let log = get_logger_from_request(&req);
let (beacon_chain, _head_state) = try_future!(get_beacon_chain_from_request::<T>(&req)); let beacon_chain = try_future!(get_beacon_chain_from_request::<T>(&req));
// Get the network sending channel from the request, for later transmission // Get the network sending channel from the request, for later transmission
let network_chan = req let network_chan = req
.extensions() .extensions()
@ -250,8 +250,6 @@ pub fn publish_beacon_block<T: BeaconChainTypes + 'static>(req: Request<Body>) -
}).and_then(|_| { }).and_then(|_| {
response_builder.body_json(&()) response_builder.body_json(&())
})) }))
} }
/// HTTP Handler to produce a new Attestation from the current state, ready to be signed by a validator. /// HTTP Handler to produce a new Attestation from the current state, ready to be signed by a validator.

View File

@ -63,12 +63,12 @@ impl<'a, B: BeaconNodeBlock, S: Signer, E: EthSpec> BlockProducer<'a, B, S, E> {
pub fn handle_produce_block(&mut self) { pub fn handle_produce_block(&mut self) {
match self.produce_block() { match self.produce_block() {
Ok(ValidatorEvent::BlockProduced(slot)) => info!( Ok(ValidatorEvent::BlockProduced(slot)) => info!(
log, self.log,
"Block produced"; "Block produced";
"validator" => format!("{}", self.signer), "validator" => format!("{}", self.signer),
"slot" => slot, "slot" => slot,
), ),
Err(e) => error!(log, "Block production error"; "Error" => format!("{:?}", e)), Err(e) => error!(self.log, "Block production error"; "Error" => format!("{:?}", e)),
Ok(ValidatorEvent::SignerRejection(_slot)) => { Ok(ValidatorEvent::SignerRejection(_slot)) => {
error!(self.log, "Block production error"; "Error" => "Signer Could not sign the block".to_string()) error!(self.log, "Block production error"; "Error" => "Signer Could not sign the block".to_string())
} }