Skip to content

Commit

Permalink
Cache socket addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
sandreae committed Jun 14, 2024
1 parent f8a7884 commit 7cd36dd
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 20 deletions.
17 changes: 12 additions & 5 deletions aquadoggo/src/api/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use p2panda_rs::schema::SchemaId;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tempfile::TempDir;

use crate::{network::PeerAddress, AllowList, Configuration, NetworkConfiguration};
use crate::{AllowList, Configuration, NetworkConfiguration};

const WILDCARD: &str = "*";

Expand Down Expand Up @@ -153,7 +153,7 @@ pub struct ConfigFile {
/// addresses or even with nodes behind a firewall or NAT, do not use this field but use at
/// least one relay.
#[serde(default)]
pub direct_node_addresses: Vec<PeerAddress>,
pub direct_node_addresses: Vec<String>,

/// List of peers which are allowed to connect to your node.
///
Expand Down Expand Up @@ -195,7 +195,7 @@ pub struct ConfigFile {
/// trusted relays or make sure your IP address is hidden via a VPN or proxy if you're
/// concerned about leaking your IP.
#[serde(default)]
pub relay_addresses: Vec<PeerAddress>,
pub relay_addresses: Vec<String>,

/// Enable if node should also function as a relay. Disabled by default.
///
Expand Down Expand Up @@ -286,6 +286,13 @@ impl TryFrom<ConfigFile> for Configuration {
.to_path_buf(),
};

let relay_addresses = value.relay_addresses.into_iter().map(From::from).collect();
let direct_node_addresses = value
.direct_node_addresses
.into_iter()
.map(From::from)
.collect();

Ok(Configuration {
allow_schema_ids,
database_url: value.database_url,
Expand All @@ -296,10 +303,10 @@ impl TryFrom<ConfigFile> for Configuration {
network: NetworkConfiguration {
quic_port: value.quic_port,
mdns: value.mdns,
direct_node_addresses: value.direct_node_addresses,
direct_node_addresses,
allow_peer_ids,
block_peer_ids: value.block_peer_ids,
relay_addresses: value.relay_addresses,
relay_addresses,
relay_mode: value.relay_mode,
..Default::default()
},
Expand Down
44 changes: 35 additions & 9 deletions aquadoggo/src/network/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,19 +153,39 @@ impl NetworkConfiguration {
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerAddress(String);
pub struct PeerAddress {
addr_str: String,
socket_addr: Option<SocketAddr>,
multi_addr: Option<Multiaddr>,
}

impl PeerAddress {
pub fn to_socket(&self) -> Result<SocketAddr, Error> {
match self.0.to_socket_addrs() {
Ok(mut addrs) => addrs
.next()
.ok_or(anyhow::format_err!("No socket addresses found")),
Err(e) => Err(e.into()),
pub fn new(addr_str: String) -> Self {
PeerAddress {
addr_str,
socket_addr: None,
multi_addr: None,
}
}

pub fn to_quic_multiaddr(&self) -> Result<Multiaddr, Error> {
pub fn to_socket(&mut self) -> Result<SocketAddr, Error> {
if let Some(socket_addr) = self.socket_addr {
return Ok(socket_addr);
}

let socket_addr = match self.addr_str.to_socket_addrs() {
Ok(mut addrs) => match addrs.next() {
Some(addrs) => addrs,
None => return Err(anyhow::format_err!("No socket addresses found")),
},
Err(e) => return Err(e.into()),
};

let _ = self.socket_addr.replace(socket_addr);
Ok(socket_addr)
}

pub fn to_quic_multiaddr(&mut self) -> Result<Multiaddr, Error> {
match self.to_socket() {
Ok(socket_address) => {
let mut multiaddr = match socket_address.ip() {
Expand All @@ -181,8 +201,14 @@ impl PeerAddress {
}
}

impl From<String> for PeerAddress {
fn from(value: String) -> Self {
Self::new(value)
}
}

impl std::fmt::Display for PeerAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
write!(f, "{}", self.addr_str)
}
}
2 changes: 1 addition & 1 deletion aquadoggo/src/network/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ mod swarm;
mod transport;
pub mod utils;

pub use config::{NetworkConfiguration, PeerAddress};
pub use config::NetworkConfiguration;
pub use peers::{Peer, PeerMessage};
pub use service::network_service;
pub use shutdown::ShutdownHandler;
10 changes: 5 additions & 5 deletions aquadoggo/src/network/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub async fn network_service(
tx: ServiceSender,
tx_ready: ServiceReadySender,
) -> Result<()> {
let network_config = &context.config.network;
let mut network_config = context.config.network.clone();
let key_pair = identity::to_libp2p_key_pair(&context.key_pair);
let local_peer_id = key_pair.public().to_peer_id();

Expand All @@ -49,7 +49,7 @@ pub async fn network_service(
// The swarm can be initiated with or without "relay" capabilities.
let mut swarm = if network_config.relay_mode {
info!("Networking service initializing with relay capabilities...");
let mut swarm = swarm::build_relay_swarm(network_config, key_pair).await?;
let mut swarm = swarm::build_relay_swarm(&network_config, key_pair).await?;

// Start listening on tcp address.
let listen_addr_tcp = Multiaddr::empty()
Expand All @@ -60,7 +60,7 @@ pub async fn network_service(
swarm
} else {
info!("Networking service initializing...");
swarm::build_client_swarm(network_config, key_pair).await?
swarm::build_client_swarm(&network_config, key_pair).await?
};

// Start listening on QUIC address. Pick a random one if the given is taken already.
Expand Down Expand Up @@ -93,7 +93,7 @@ pub async fn network_service(
// replication sessions, which could leave the node in a strange state.
swarm.behaviour_mut().peers.disable();

for relay_address in &network_config.relay_addresses {
for relay_address in network_config.relay_addresses.iter_mut() {
info!("Connecting to relay node {}", relay_address);

let mut relay_address = match relay_address.to_quic_multiaddr() {
Expand Down Expand Up @@ -167,7 +167,7 @@ pub async fn network_service(
}

// Dial all nodes we want to directly connect to.
for direct_node_address in &network_config.direct_node_addresses {
for direct_node_address in network_config.direct_node_addresses.iter_mut() {
info!("Connecting to node @ {}", direct_node_address);

let direct_node_address = match direct_node_address.to_quic_multiaddr() {
Expand Down

0 comments on commit 7cd36dd

Please sign in to comment.