Skip to content

Commit

Permalink
fix(sdk): create channel error due to empty address
Browse files Browse the repository at this point in the history
  • Loading branch information
shumkov committed Nov 8, 2024
1 parent 48cca1a commit b8a887e
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 47 deletions.
55 changes: 26 additions & 29 deletions packages/rs-dapi-client/src/address_list.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Subsystem to manage DAPI nodes.
use chrono::Utc;
use dapi_grpc::tonic::codegen::http;
use dapi_grpc::tonic::transport::Uri;
use rand::{rngs::SmallRng, seq::IteratorRandom, SeedableRng};
use std::collections::HashSet;
Expand All @@ -26,8 +25,8 @@ impl FromStr for Address {

fn from_str(s: &str) -> Result<Self, Self::Err> {
Uri::from_str(s)
.map(Address::from)
.map_err(AddressListError::from)
.map_err(|e| AddressListError::InvalidAddressUri(e.to_string()))
.map(Address::try_from)?
}
}

Expand All @@ -49,13 +48,19 @@ impl Hash for Address {
}
}

impl From<Uri> for Address {
fn from(uri: Uri) -> Self {
Address {
impl TryFrom<Uri> for Address {
type Error = AddressListError;

fn try_from(value: Uri) -> Result<Self, Self::Error> {
if value.host().is_none() {
return Err(AddressListError::InvalidAddressUri("uri must contain host".to_string()));
}

Ok(Address {
ban_count: 0,
banned_until: None,
uri,
}
uri: value,
})
}
}

Expand Down Expand Up @@ -96,7 +101,7 @@ pub enum AddressListError {
/// A valid uri is required to create an Address
#[error("unable parse address: {0}")]
#[cfg_attr(feature = "mocks", serde(skip))]
InvalidAddressUri(#[from] http::uri::InvalidUri),
InvalidAddressUri(String),
}

/// A structure to manage DAPI addresses to select from
Expand Down Expand Up @@ -167,15 +172,6 @@ impl AddressList {
self.addresses.insert(address)
}

// TODO: this is the most simple way to add an address
// however we need to support bulk loading (e.g. providing a network name)
// and also fetch updated from SML.
/// Add a node [Address] to [AddressList] by [Uri].
/// Returns false if the address is already in the list.
pub fn add_uri(&mut self, uri: Uri) -> bool {
self.addresses.insert(uri.into())
}

/// Randomly select a not banned address.
pub fn get_live_address(&self) -> Option<&Address> {
let mut rng = SmallRng::from_entropy();
Expand All @@ -185,7 +181,7 @@ impl AddressList {

/// Get all addresses that are not banned.
fn unbanned(&self) -> Vec<&Address> {
let now = chrono::Utc::now();
let now = Utc::now();

self.addresses
.iter()
Expand Down Expand Up @@ -216,23 +212,24 @@ impl AddressList {
}
}

// TODO: Must be changed to FromStr
impl From<&str> for AddressList {
fn from(value: &str) -> Self {
let uri_list: Vec<Uri> = value
impl FromStr for AddressList {
type Err = AddressListError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let uri_list: Vec<Address> = s
.split(',')
.map(|uri| Uri::from_str(uri).expect("invalid uri"))
.collect();
.map(Address::from_str)
.collect::<Result<_, _>>()?;

Self::from_iter(uri_list)
Ok(Self::from_iter(uri_list))
}
}

impl FromIterator<Uri> for AddressList {
fn from_iter<T: IntoIterator<Item = Uri>>(iter: T) -> Self {
impl FromIterator<Address> for AddressList {
fn from_iter<T: IntoIterator<Item = Address>>(iter: T) -> Self {
let mut address_list = Self::new();
for uri in iter {
address_list.add_uri(uri);
address_list.add(uri);
}

address_list
Expand Down
4 changes: 2 additions & 2 deletions packages/rs-dapi-client/src/transport/grpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ impl TransportClient for PlatformGrpcClient {
.get_or_create(PoolPrefix::Platform, &uri, None, || {
match create_channel(uri.clone(), None) {
Ok(channel) => Ok(Self::new(channel).into()),
Err(e) => Err(dapi_grpc::tonic::Status::failed_precondition(format!(
"Channel creation failed: {}",
Err(e) => Err(dapi_grpc::tonic::Status::invalid_argument(format!(
"channel creation failed: {}",
e
))),
}
Expand Down
8 changes: 4 additions & 4 deletions packages/rs-sdk/examples/read_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{num::NonZeroUsize, str::FromStr};
use clap::Parser;
use dash_sdk::{mock::provider::GrpcContextProvider, platform::Fetch, Sdk, SdkBuilder};
use dpp::prelude::{DataContract, Identifier};
use rs_dapi_client::AddressList;
use rs_dapi_client::{Address, AddressList};
use zeroize::Zeroizing;

#[derive(clap::Parser, Debug)]
Expand Down Expand Up @@ -80,14 +80,14 @@ fn setup_sdk(config: &Config) -> Sdk {

// Let's build the Sdk.
// First, we need an URI of some Dash Platform DAPI host to connect to and use as seed.
let uri = http::Uri::from_str(&format!(
"http://{}:{}",
let address = Address::from_str(&format!(
"https://{}:{}",
config.server_address, config.platform_port
))
.expect("parse uri");

// Now, we create the Sdk with the wallet and context provider.
let sdk = SdkBuilder::new(AddressList::from_iter([uri]))
let sdk = SdkBuilder::new(AddressList::from_iter([address]))
.build()
.expect("cannot build sdk");

Expand Down
4 changes: 2 additions & 2 deletions packages/rs-sdk/src/platform/types/evonode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ use std::fmt::Debug;
/// use futures::executor::block_on;
///
/// let sdk = Sdk::new_mock();
/// let uri: http::Uri = "http://127.0.0.1:1".parse().unwrap();
/// let node = EvoNode::new(uri.into());
/// let address = "http://127.0.0.1:1".parse().expect("valid address");
/// let node = EvoNode::new(address);
/// let status = block_on(EvoNodeStatus::fetch_unproved(&sdk, node)).unwrap();
/// ```
Expand Down
7 changes: 3 additions & 4 deletions packages/rs-sdk/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,10 @@ where
let result= ::backon::Retryable::retry(closure,backoff_strategy)
.when(|e| {
if e.can_retry() {
// requests sent for current execution attempt;
// requests sent for current execution attempt;
let requests_sent = e.retries + 1;

// requests sent in all preceeding attempts; user expects `settings.retries +1`
// requests sent in all preceeding attempts; user expects `settings.retries +1`
retries += requests_sent;
let all_requests_sent = retries;

Expand Down Expand Up @@ -231,7 +231,6 @@ where
#[cfg(test)]
mod test {
use super::*;
use http::Uri;
use rs_dapi_client::ExecutionError;
use std::{
future::Future,
Expand Down Expand Up @@ -342,7 +341,7 @@ mod test {
Err(ExecutionError {
inner: MockError::Generic,
retries,
address: Some(Uri::from_static("http://localhost").into()),
address: Some("http://localhost".parse().expect("valid address")),
})
}

Expand Down
6 changes: 3 additions & 3 deletions packages/rs-sdk/tests/fetch/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use dpp::{
dashcore::{hashes::Hash, ProTxHash},
prelude::Identifier,
};
use rs_dapi_client::AddressList;
use rs_dapi_client::{Address, AddressList};
use serde::Deserialize;
use std::{path::PathBuf, str::FromStr};
use zeroize::Zeroizing;
Expand Down Expand Up @@ -131,9 +131,9 @@ impl Config {
false => "http",
};

let address: String = format!("{}://{}:{}", scheme, self.platform_host, self.platform_port);
let address: Address = format!("{}://{}:{}", scheme, self.platform_host, self.platform_port).parse().expect("valid address");

AddressList::from_iter(vec![http::Uri::from_str(&address).expect("valid uri")])
AddressList::from_iter([address])
}

/// Create new SDK instance
Expand Down
7 changes: 4 additions & 3 deletions packages/rs-sdk/tests/fetch/evonode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use http::Uri;
use std::time::Duration;
/// Given some existing evonode URIs, WHEN we connect to them, THEN we get status.
use tokio::time::timeout;
use rs_dapi_client::Address;

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_evonode_status() {
Expand Down Expand Up @@ -61,11 +62,11 @@ async fn test_evonode_status_refused() {
let cfg = Config::new();
let sdk = cfg.setup_api("test_evonode_status_refused").await;

let uri: Uri = "http://127.0.0.1:1".parse().unwrap();
let address: Address = "http://127.0.0.1:1".parse().expect("valid address");

let node = EvoNode::new(uri.clone().into());
let node = EvoNode::new(address.clone());
let result = EvoNodeStatus::fetch_unproved(&sdk, node).await;
tracing::debug!(?result, ?uri, "evonode status");
tracing::debug!(?result, ?address, "evonode status");

assert!(result.is_err());
}

0 comments on commit b8a887e

Please sign in to comment.