-
Notifications
You must be signed in to change notification settings - Fork 239
Lower bandwidth used for topology refresh #5618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jmwample
wants to merge
13
commits into
develop
Choose a base branch
from
jmwample/topo-refresh
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
7619515
initial commit implementing smarter topology refresh
jmwample 1fadf8c
shift caching into the topology crate
jmwample 6ceb6c4
implementing tests
jmwample 0e544da
state test failing
jmwample 692cd32
state update test passing
jmwample 987e890
piecewise TopologyProvider tests passing with expected behavior
jmwample 65166bf
remove the nyxd provider, if implemented it will be a separate effort
jmwample 12ed915
skeleton of changes for nym api batch requests
jmwample b326993
skimmed batch endpoint implemented
jmwample 0c97b51
use new topology provider and appease wasm
jmwample e7d88c3
test the piecewise api provider against local nym api
jmwample 277305e
fix examples and simpligy imports
jmwample d9a6db6
formatting
jmwample File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
230 changes: 230 additions & 0 deletions
230
common/client-core/src/client/topology_control/smart_api_provider.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,230 @@ | ||
// Copyright 2024 - Nym Technologies SA <[email protected]> | ||
// SPDX-License-Identifier: GPL-3.0-only | ||
|
||
//! Caching, piecewise API Topology Provider | ||
//! | ||
|
||
#![warn(missing_docs)] | ||
|
||
use async_trait::async_trait; | ||
use log::{debug, error, warn}; | ||
pub use nym_topology::providers::piecewise::Config; | ||
use nym_topology::{ | ||
providers::piecewise::{NymTopologyProvider, PiecewiseTopologyProvider}, | ||
EpochRewardedSet, NymTopology, RoutingNode, TopologyProvider, | ||
}; | ||
use nym_validator_client::UserAgent; | ||
use rand::{prelude::SliceRandom, thread_rng}; | ||
use url::Url; | ||
|
||
/// Topology Provider build around a cached piecewise provider that uses the Nym API to | ||
/// fetch changes and node details. | ||
#[derive(Clone)] | ||
pub struct NymApiTopologyProvider { | ||
inner: NymTopologyProvider<NymApiPiecewiseProvider>, | ||
} | ||
|
||
impl NymApiTopologyProvider { | ||
/// Construct a new thread safe Cached topology provider using the Nym API | ||
pub fn new( | ||
config: impl Into<Config>, | ||
nym_api_urls: Vec<Url>, | ||
user_agent: Option<UserAgent>, | ||
initial_topology: Option<NymTopology>, | ||
) -> Self { | ||
let manager = NymApiPiecewiseProvider::new(nym_api_urls, user_agent); | ||
let inner = NymTopologyProvider::new(manager, config.into(), initial_topology); | ||
|
||
Self { inner } | ||
} | ||
} | ||
|
||
impl AsRef<NymTopologyProvider<NymApiPiecewiseProvider>> for NymApiTopologyProvider { | ||
fn as_ref(&self) -> &NymTopologyProvider<NymApiPiecewiseProvider> { | ||
&self.inner | ||
} | ||
} | ||
|
||
impl AsMut<NymTopologyProvider<NymApiPiecewiseProvider>> for NymApiTopologyProvider { | ||
fn as_mut(&mut self) -> &mut NymTopologyProvider<NymApiPiecewiseProvider> { | ||
&mut self.inner | ||
} | ||
} | ||
|
||
#[cfg(not(target_arch = "wasm32"))] | ||
#[async_trait] | ||
impl TopologyProvider for NymApiTopologyProvider { | ||
async fn get_new_topology(&mut self) -> Option<NymTopology> { | ||
self.as_mut().get_new_topology().await | ||
} | ||
} | ||
|
||
#[cfg(target_arch = "wasm32")] | ||
#[async_trait(?Send)] | ||
impl TopologyProvider for NymApiTopologyProvider { | ||
async fn get_new_topology(&mut self) -> Option<NymTopology> { | ||
self.as_mut().get_new_topology().await | ||
} | ||
} | ||
|
||
#[derive(Clone)] | ||
struct NymApiPiecewiseProvider { | ||
validator_client: nym_validator_client::client::NymApiClient, | ||
nym_api_urls: Vec<Url>, | ||
currently_used_api: usize, | ||
} | ||
|
||
impl NymApiPiecewiseProvider { | ||
fn new(mut nym_api_urls: Vec<Url>, user_agent: Option<UserAgent>) -> Self { | ||
nym_api_urls.shuffle(&mut thread_rng()); | ||
|
||
let validator_client = if let Some(user_agent) = user_agent { | ||
nym_validator_client::client::NymApiClient::new_with_user_agent( | ||
nym_api_urls[0].clone(), | ||
user_agent, | ||
) | ||
} else { | ||
nym_validator_client::client::NymApiClient::new(nym_api_urls[0].clone()) | ||
}; | ||
|
||
Self { | ||
validator_client, | ||
nym_api_urls, | ||
currently_used_api: 0, | ||
} | ||
} | ||
|
||
fn use_next_nym_api(&mut self) { | ||
if self.nym_api_urls.len() == 1 { | ||
warn!("There's only a single nym API available - it won't be possible to use a different one"); | ||
return; | ||
} | ||
|
||
self.currently_used_api = (self.currently_used_api + 1) % self.nym_api_urls.len(); | ||
self.validator_client | ||
.change_nym_api(self.nym_api_urls[self.currently_used_api].clone()) | ||
} | ||
|
||
async fn get_full_topology_inner(&mut self) -> Option<NymTopology> { | ||
let layer_assignments = self.get_layer_assignments().await?; | ||
|
||
let mut topology = NymTopology::new_empty(layer_assignments); | ||
|
||
let all_nodes = self | ||
.validator_client | ||
.get_all_basic_nodes() | ||
.await | ||
.inspect_err(|err| { | ||
self.use_next_nym_api(); | ||
error!("failed to get network nodes: {err}"); | ||
}) | ||
.ok()?; | ||
|
||
debug!("there are {} nodes on the network", all_nodes.len()); | ||
topology.add_additional_nodes(all_nodes.iter()); | ||
|
||
if !topology.is_minimally_routable() { | ||
error!("the current filtered active topology can't be used to construct any packets"); | ||
return None; | ||
} | ||
|
||
Some(topology) | ||
} | ||
|
||
async fn get_descriptor_batch_inner(&mut self, ids: &[u32]) -> Option<Vec<RoutingNode>> { | ||
// Does this need to return a hashmap of RoutingNodes? that is moderately inconvenient | ||
// especially when the nodes themselves contain their node_id unless we expect to directly | ||
// use the result of this fn for lookups where we would otherwise for example, have to | ||
// iterate over a whole vec to find a specific node_id. | ||
let descriptor_vec = self | ||
.validator_client | ||
.retrieve_basic_nodes_batch(ids) | ||
.await | ||
.inspect_err(|err| { | ||
self.use_next_nym_api(); | ||
error!("failed to get current rewarded set: {err}"); | ||
}) | ||
.ok()?; | ||
|
||
let mut out = Vec::new(); | ||
for node in descriptor_vec { | ||
if let Ok(routing_node) = RoutingNode::try_from(&node) { | ||
out.push(routing_node); | ||
} | ||
} | ||
Some(out) | ||
} | ||
|
||
async fn get_layer_assignments_inner(&mut self) -> Option<EpochRewardedSet> { | ||
self.validator_client | ||
.get_current_rewarded_set() | ||
.await | ||
.inspect_err(|err| { | ||
self.use_next_nym_api(); | ||
error!("failed to get current rewarded set: {err}"); | ||
}) | ||
.ok() | ||
} | ||
} | ||
|
||
#[cfg(not(target_arch = "wasm32"))] | ||
#[async_trait] | ||
impl PiecewiseTopologyProvider for NymApiPiecewiseProvider { | ||
async fn get_full_topology(&mut self) -> Option<NymTopology> { | ||
self.get_full_topology_inner().await | ||
} | ||
|
||
async fn get_descriptor_batch(&mut self, ids: &[u32]) -> Option<Vec<RoutingNode>> { | ||
self.get_descriptor_batch_inner(ids).await | ||
} | ||
|
||
async fn get_layer_assignments(&mut self) -> Option<EpochRewardedSet> { | ||
self.get_layer_assignments_inner().await | ||
} | ||
} | ||
|
||
#[cfg(target_arch = "wasm32")] | ||
#[async_trait(?Send)] | ||
impl PiecewiseTopologyProvider for NymApiPiecewiseProvider { | ||
async fn get_full_topology(&mut self) -> Option<NymTopology> { | ||
self.get_full_topology_inner().await | ||
} | ||
|
||
async fn get_descriptor_batch(&mut self, ids: &[u32]) -> Option<Vec<RoutingNode>> { | ||
self.get_descriptor_batch_inner(ids).await | ||
} | ||
|
||
async fn get_layer_assignments(&mut self) -> Option<EpochRewardedSet> { | ||
self.get_layer_assignments_inner().await | ||
} | ||
} | ||
|
||
// // Test requires running a local instance of the nym-api binary, for example using: | ||
// // `RUST_LOG="info" ./target/debug/nym-api run --nyxd-validator "https://rpc.nymtech.net"` | ||
|
||
// #[cfg(test)] | ||
// mod test { | ||
// use std::time::Duration; | ||
|
||
// use super::*; | ||
// use nym_bin_common::logging::setup_tracing_logger; | ||
|
||
// #[tokio::test] | ||
// async fn local_api_provider_test() { | ||
// setup_tracing_logger(); | ||
// let mut provider = NymApiTopologyProvider::new( | ||
// Config::default(), | ||
// vec!["http://localhost:8000" | ||
// .parse() | ||
// .expect("failed to parse api url")], | ||
// None, | ||
// None, | ||
// ); | ||
|
||
// for _ in 0..180 { | ||
// let topo = provider.get_new_topology().await; | ||
// assert!(topo.is_some()); | ||
// tokio::time::sleep(Duration::from_secs(30)).await; | ||
// } | ||
// } | ||
// } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about using something like
NymApiSmartTopologyProvider
? Having two types with the same name was a bit confusing initially when reading the the code