Skip to content

Commit

Permalink
Update Url scheme
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhauner committed Sep 5, 2020
1 parent e9da8a4 commit 044da99
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 46 deletions.
16 changes: 10 additions & 6 deletions beacon_node/http_api/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use beacon_chain::{
test_utils::{AttestationStrategy, BeaconChainHarness, BlockStrategy, HarnessType},
BeaconChain,
};
use eth2::{types::*, BeaconNodeClient};
use eth2::{types::*, BeaconNodeClient, Url};
use http_api::Context;
use std::sync::Arc;
use store::config::StoreConfig;
Expand Down Expand Up @@ -87,11 +87,15 @@ impl ApiTester {

tokio::spawn(async { server.await });

let client = BeaconNodeClient::new(format!(
"http://{}:{}",
listening_socket.ip(),
listening_socket.port()
));
let client = BeaconNodeClient::new(
Url::parse(&format!(
"http://{}:{}",
listening_socket.ip(),
listening_socket.port()
))
.unwrap(),
)
.unwrap();

Self {
chain,
Expand Down
122 changes: 82 additions & 40 deletions common/eth2/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,29 @@
pub mod types;

use self::types::*;
use reqwest::{Error, StatusCode, Url};
use reqwest::{Error, IntoUrl, StatusCode};
use serde::de::DeserializeOwned;

const VERSION: &str = "eth/v1";
pub use reqwest::Url;

pub struct BeaconNodeClient {
client: reqwest::Client,
server: String,
server: Url,
}

impl BeaconNodeClient {
pub fn new(server: String) -> Self {
Self {
/// Returns `Err(())` if the URL is invalid.
pub fn new(mut server: Url) -> Result<Self, ()> {
server.path_segments_mut()?.push("eth").push("v1");

Ok(Self {
client: reqwest::Client::new(),
server,
}
}

pub fn from_parts(client: reqwest::Client, server: String) -> Self {
Self { client, server }
}

fn path(&self, path: &str) -> String {
format!("{}/{}/{}", self.server, VERSION, path)
})
}

async fn get_opt<T: DeserializeOwned>(&self, path: &str) -> Result<Option<T>, Error> {
match self
.client
.get(&self.path(path))
.send()
.await?
.error_for_status()
{
async fn get_opt<T: DeserializeOwned, U: IntoUrl>(&self, url: U) -> Result<Option<T>, Error> {
match self.client.get(url).send().await?.error_for_status() {
Ok(resp) => resp.json().await.map(Option::Some),
Err(err) => {
if err.status() == Some(StatusCode::NOT_FOUND) {
Expand All @@ -53,8 +42,16 @@ impl BeaconNodeClient {
&self,
state_id: StateId,
) -> Result<Option<GenericResponse<RootData>>, Error> {
self.get_opt(&format!("beacon/states/{}/root", state_id))
.await
let mut path = self.server.clone();

path.path_segments_mut()
.expect("path is base")
.push("beacon")
.push("states")
.push(&state_id.to_string())
.push("root");

self.get_opt(path).await
}

/// `GET beacon/states/{state_id}/fork`
Expand All @@ -64,8 +61,16 @@ impl BeaconNodeClient {
&self,
state_id: StateId,
) -> Result<Option<GenericResponse<Fork>>, Error> {
self.get_opt(&format!("beacon/states/{}/fork", state_id))
.await
let mut path = self.server.clone();

path.path_segments_mut()
.expect("path is base")
.push("beacon")
.push("states")
.push(&state_id.to_string())
.push("fork");

self.get_opt(path).await
}

/// `GET beacon/states/{state_id}/finality_checkpoints`
Expand All @@ -75,8 +80,16 @@ impl BeaconNodeClient {
&self,
state_id: StateId,
) -> Result<Option<GenericResponse<FinalityCheckpointsData>>, Error> {
self.get_opt(&format!("beacon/states/{}/finality_checkpoints", state_id))
.await
let mut path = self.server.clone();

path.path_segments_mut()
.expect("path is base")
.push("beacon")
.push("states")
.push(&state_id.to_string())
.push("finality_checkpoints");

self.get_opt(path).await
}

/// `GET beacon/states/{state_id}/validators`
Expand All @@ -86,8 +99,16 @@ impl BeaconNodeClient {
&self,
state_id: StateId,
) -> Result<Option<GenericResponse<Vec<ValidatorData>>>, Error> {
self.get_opt(&format!("beacon/states/{}/validators", state_id))
.await
let mut path = self.server.clone();

path.path_segments_mut()
.expect("path is base")
.push("beacon")
.push("states")
.push(&state_id.to_string())
.push("validators");

self.get_opt(path).await
}

/// `GET beacon/states/{state_id}/committees?slot,index`
Expand All @@ -100,8 +121,15 @@ impl BeaconNodeClient {
slot: Option<Slot>,
index: Option<u64>,
) -> Result<Option<GenericResponse<Vec<CommitteeData>>>, Error> {
let mut path = Url::parse(&format!("beacon/states/{}/committees/{}", state_id, epoch))
.expect("url should always be valid");
let mut path = self.server.clone();

path.path_segments_mut()
.expect("path is base")
.push("beacon")
.push("states")
.push(&state_id.to_string())
.push("committees")
.push(&epoch.to_string());

if let Some(slot) = slot {
path.query_pairs_mut()
Expand All @@ -113,7 +141,7 @@ impl BeaconNodeClient {
.append_pair("index", &index.to_string());
}

self.get_opt(&path.to_string()).await
self.get_opt(path).await
}

/// `GET beacon/states/{state_id}/validators/{validator_id}`
Expand All @@ -124,11 +152,17 @@ impl BeaconNodeClient {
state_id: StateId,
validator_id: &ValidatorId,
) -> Result<Option<GenericResponse<ValidatorData>>, Error> {
self.get_opt(&format!(
"beacon/states/{}/validators/{}",
state_id, validator_id
))
.await
let mut path = self.server.clone();

path.path_segments_mut()
.expect("path is base")
.push("beacon")
.push("states")
.push(&state_id.to_string())
.push("validators")
.push(&validator_id.to_string());

self.get_opt(path).await
}

/// `GET beacon/blocks/{block_id}/root`
Expand All @@ -138,7 +172,15 @@ impl BeaconNodeClient {
&self,
block_id: BlockId,
) -> Result<Option<GenericResponse<RootData>>, Error> {
self.get_opt(&format!("beacon/blocks/{}/root", block_id))
.await
let mut path = self.server.clone();

path.path_segments_mut()
.expect("path is base")
.push("beacon")
.push("blocks")
.push(&block_id.to_string())
.push("root");

self.get_opt(path).await
}
}

0 comments on commit 044da99

Please sign in to comment.