Skip to content
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

refactor: streamline local endpoint discovery #1847

Merged
merged 9 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
19 changes: 19 additions & 0 deletions Cargo.lock

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

29 changes: 2 additions & 27 deletions iroh-gossip/examples/chat.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, fmt, str::FromStr, sync::Arc};
use std::{collections::HashMap, fmt, str::FromStr};

use anyhow::{bail, Context};
use bytes::Bytes;
Expand All @@ -15,9 +15,7 @@ use iroh_net::{
magic_endpoint::accept_conn,
MagicEndpoint, NodeAddr,
};
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use tokio::sync::Notify;
use url::Url;

/// Chat over iroh-gossip
Expand Down Expand Up @@ -103,44 +101,21 @@ async fn main() -> anyhow::Result<()> {
};
println!("> using DERP servers: {}", fmt_derp_mode(&derp_mode));

// init a cell that will hold our gossip handle to be used in endpoint callbacks
let gossip_cell: OnceCell<Gossip> = OnceCell::new();

// setup a notification to emit once the initial endpoints of our local node are discovered
let notify = Arc::new(Notify::new());

// build our magic endpoint
let endpoint = MagicEndpoint::builder()
.secret_key(secret_key)
.alpns(vec![GOSSIP_ALPN.to_vec()])
.derp_mode(derp_mode)
.on_endpoints({
let gossip_cell = gossip_cell.clone();
let notify = notify.clone();
Box::new(move |endpoints| {
if endpoints.is_empty() {
return;
}
// send our updated endpoints to the gossip protocol to be sent as NodeAddr to peers
if let Some(gossip) = gossip_cell.get() {
gossip.update_endpoints(endpoints).ok();
}
// notify the outer task of the initial endpoint update (later updates are not interesting)
notify.notify_one();
})
})
.bind(args.bind_port)
.await?;
println!("> our node id: {}", endpoint.node_id());

// wait for a first endpoint update so that we know about our endpoint addresses
notify.notified().await;
let _endpoints = endpoint.local_endpoints().await?;

let my_addr = endpoint.my_addr().await?;
// create the gossip protocol
let gossip = Gossip::from_endpoint(endpoint.clone(), Default::default(), &my_addr.info);
// insert the gossip handle into the gossip cell to be used in the endpoint callbacks above
gossip_cell.set(gossip.clone()).unwrap();

// print a ticket that includes our own node id and endpoint addresses
let ticket = {
Expand Down
1 change: 1 addition & 0 deletions iroh-net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ tracing = "0.1"
trust-dns-resolver = "0.23.0"
ttl_cache = "0.5.1"
url = { version = "2.4", features = ["serde"] }
watchable = "1.1.1"
webpki = { package = "rustls-webpki", version = "0.101.4", features = ["std"] }
webpki-roots = "0.25"
x509-parser = "0.15"
Expand Down
37 changes: 8 additions & 29 deletions iroh-net/src/magic_endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
defaults::default_derp_map,
derp::{DerpMap, DerpMode},
key::{PublicKey, SecretKey},
magicsock::{self, Callbacks, Discovery, MagicSock},
magicsock::{self, Discovery, MagicSock},
tls,
};

Expand Down Expand Up @@ -118,7 +118,6 @@ pub struct MagicEndpointBuilder {
transport_config: Option<quinn::TransportConfig>,
concurrent_connections: Option<u32>,
keylog: bool,
callbacks: Callbacks,
discovery: Option<Box<dyn Discovery>>,
/// Path for known peers. See [`MagicEndpointBuilder::peers_data_path`].
peers_path: Option<PathBuf>,
Expand All @@ -133,7 +132,6 @@ impl Default for MagicEndpointBuilder {
transport_config: Default::default(),
concurrent_connections: Default::default(),
keylog: Default::default(),
callbacks: Default::default(),
discovery: Default::default(),
peers_path: None,
}
Expand Down Expand Up @@ -202,31 +200,6 @@ impl MagicEndpointBuilder {
self
}

/// Optionally set a callback function to be called when endpoints change.
#[allow(clippy::type_complexity)]
pub fn on_endpoints(
mut self,
on_endpoints: Box<dyn Fn(&[config::Endpoint]) + Send + Sync + 'static>,
) -> Self {
self.callbacks.on_endpoints = Some(on_endpoints);
self
}

/// Optionally set a callback funcion to be called when a connection is made to a DERP server.
pub fn on_derp_active(mut self, on_derp_active: Box<dyn Fn() + Send + Sync + 'static>) -> Self {
self.callbacks.on_derp_active = Some(on_derp_active);
self
}

/// Optionally set a callback function that provides a [config::NetInfo] when discovered network conditions change.
pub fn on_net_info(
mut self,
on_net_info: Box<dyn Fn(config::NetInfo) + Send + Sync + 'static>,
) -> Self {
self.callbacks.on_net_info = Some(on_net_info);
self
}

/// Optionally set the path where peer info should be stored.
///
/// If the file exists, it will be used to populate an initial set of peers. Peers will be
Expand Down Expand Up @@ -271,7 +244,6 @@ impl MagicEndpointBuilder {
port: bind_port,
secret_key,
derp_map,
callbacks: self.callbacks,
nodes_path: self.peers_path,
discovery: self.discovery,
};
Expand Down Expand Up @@ -376,10 +348,17 @@ impl MagicEndpoint {
/// This list contains both the locally-bound addresses and the endpoint's
/// publicly-reachable addresses, if they could be discovered through
/// STUN or port mapping.
///
/// If called before there are any endpoints, waits for the first time there are some.
pub async fn local_endpoints(&self) -> Result<Vec<config::Endpoint>> {
self.msock.local_endpoints().await
}

/// Waits for local endpoints to change and returns the new ones.
pub async fn local_endpoints_change(&self) -> Result<Vec<config::Endpoint>> {
self.msock.local_endpoints_change().await
}

/// Get the DERP region we are connected to with the lowest latency.
///
/// Returns `None` if we are not connected to any DERP region.
Expand Down
Loading
Loading