Skip to content

Commit

Permalink
chore(config): do not cache or attempt to read the config from disk
Browse files Browse the repository at this point in the history
  • Loading branch information
bochaco committed Feb 19, 2021
1 parent 7453c00 commit 6f6f1f4
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 108 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ webpki = "~0.21.3"
features = [ "serde" ]

[dependencies.igd]
version = "~0.11.1"
version = "~0.12.0"
features = [ "aio" ]
optional = true

Expand Down
14 changes: 3 additions & 11 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use super::{
use futures::{future, TryFutureExt};
use log::{debug, error, info, trace};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
use std::{collections::HashSet, path::PathBuf};
use std::path::PathBuf;

/// In the absence of a port supplied by the user via the config we will first try using this
/// before using a random port.
Expand Down Expand Up @@ -95,12 +95,8 @@ impl QuicP2p {

let mut qp2p_config = cfg.clone();

if cfg.clean {
BootstrapCache::clear_from_disk(custom_dirs.as_ref())?;
}

let mut bootstrap_cache =
BootstrapCache::new(cfg.hard_coded_contacts, custom_dirs.as_ref(), cfg.fresh)?;
BootstrapCache::new(cfg.hard_coded_contacts, custom_dirs.as_ref())?;
if use_bootstrap_cache {
bootstrap_cache.peers_mut().extend(bootstrap_nodes);
} else {
Expand Down Expand Up @@ -301,7 +297,7 @@ fn bind(
}

fn unwrap_config_or_default(cfg: Option<Config>) -> Result<Config> {
let mut cfg = cfg.map_or(Config::read_or_construct_default(None)?, |cfg| cfg);
let mut cfg = cfg.map_or(Config::default(), |cfg| cfg);

if cfg.local_ip.is_none() {
debug!("Realizing local IP by connecting to contacts");
Expand All @@ -316,9 +312,5 @@ fn unwrap_config_or_default(cfg: Option<Config>) -> Result<Config> {
cfg.local_ip = local_ip;
};

if cfg.clean {
Config::clear_config_from_disk(None)?;
}

Ok(cfg)
}
17 changes: 6 additions & 11 deletions src/bootstrap_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ impl BootstrapCache {
pub fn new(
hard_coded_contacts: HashSet<SocketAddr>,
user_override: Option<&PathBuf>,
fresh: bool,
) -> Result<BootstrapCache> {
let get_cache_path = |dir: &PathBuf| dir.join("bootstrap_cache");

Expand All @@ -52,11 +51,7 @@ impl BootstrapCache {
)?;

let peers = if cache_path.exists() {
if fresh {
VecDeque::new()
} else {
utils::read_from_disk(&cache_path)?
}
utils::read_from_disk(&cache_path)?
} else {
let cache_dir = cache_path.parent().ok_or_else(|| {
Error::InvalidPath(format!(
Expand Down Expand Up @@ -154,15 +149,15 @@ mod tests {
#[test]
fn when_10_peers_are_added_they_are_synced_to_disk() -> Result<(), Error> {
let dirs = test_dirs();
let mut cache = BootstrapCache::new(Default::default(), Some(&dirs), false)?;
let mut cache = BootstrapCache::new(Default::default(), Some(&dirs))?;

for _ in 0..10 {
cache.add_peer(rand_node_addr());
}

assert_eq!(cache.peers.len(), 10);

let cache = BootstrapCache::new(Default::default(), Some(&dirs), false)?;
let cache = BootstrapCache::new(Default::default(), Some(&dirs))?;
assert_eq!(cache.peers.len(), 10);
Ok(())
}
Expand All @@ -175,7 +170,7 @@ mod tests {
assert!(hard_coded.insert(peer1));

let dirs = test_dirs();
let mut cache = BootstrapCache::new(hard_coded, Some(&dirs), false)?;
let mut cache = BootstrapCache::new(hard_coded, Some(&dirs))?;

cache.add_peer(peer1);
cache.add_peer(peer2);
Expand All @@ -190,7 +185,7 @@ mod tests {
let dirs = test_dirs();
let port_base = 5000;

let mut cache = BootstrapCache::new(Default::default(), Some(&dirs), false)?;
let mut cache = BootstrapCache::new(Default::default(), Some(&dirs))?;

for i in 0..MAX_CACHE_SIZE {
cache.add_peer(make_node_addr(port_base + i as u16));
Expand All @@ -209,7 +204,7 @@ mod tests {
#[test]
fn it_moves_given_node_to_the_top_of_the_list() -> Result<(), Error> {
let dirs = test_dirs();
let mut cache = BootstrapCache::new(Default::default(), Some(&dirs), false)?;
let mut cache = BootstrapCache::new(Default::default(), Some(&dirs))?;
let peer1 = rand_node_addr();
let peer2 = rand_node_addr();
let peer3 = rand_node_addr();
Expand Down
79 changes: 4 additions & 75 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ use crate::{
utils,
};
use bytes::Bytes;
use log::trace;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::{
collections::HashSet, fmt, fs, io, net::IpAddr, net::SocketAddr, path::PathBuf, str::FromStr,
collections::HashSet,
fmt,
net::{IpAddr, SocketAddr},
str::FromStr,
};
use structopt::StructOpt;

Expand Down Expand Up @@ -79,46 +80,6 @@ pub struct Config {
/// Duration of a UPnP port mapping.
#[structopt(long)]
pub upnp_lease_duration: Option<u32>,
/// Use a fresh config without re-using any config available on disk
#[structopt(long)]
pub fresh: bool,
/// Clean all existing config available on disk
#[structopt(long)]
pub clean: bool,
}

impl Config {
/// Try and read the config off the disk first. If such a file-path doesn't exist it'll create
/// a default one with random certificate and write that to the disk, eventually returning that
/// config to the caller.
pub fn read_or_construct_default(user_override: Option<&Path>) -> Result<Config> {
let config_path = config_path(user_override)?;

if config_path.exists() {
trace!("Reading config from {:?}", config_path);
Ok(utils::read_from_disk(&config_path)?)
} else {
let config_dir = config_path
.parent()
.ok_or_else(|| io::ErrorKind::NotFound.into())
.map_err(Error::Io)?;
fs::create_dir_all(&config_dir)?;

let cfg = Config::default();
utils::write_to_disk(&config_path, &cfg)?;

Ok(cfg)
}
}

/// Clear all configuration files from disk
pub fn clear_config_from_disk(user_override: Option<&Path>) -> Result<()> {
let config_path = config_path(user_override)?;
if config_path.exists() {
fs::remove_file(&config_path)?;
}
Ok(())
}
}

/// To be used to read and write our certificate and private key to disk esp. as a part of our
Expand Down Expand Up @@ -174,35 +135,3 @@ impl fmt::Debug for SerialisableCertificate {
)
}
}

fn config_path(user_override: Option<&Path>) -> Result<PathBuf> {
let get_config_file = |dir: &Path| dir.join("config");

let cfg_path = user_override.map_or_else(
|| Ok::<_, Error>(get_config_file(&utils::project_dir()?)),
|d| Ok(get_config_file(d)),
)?;

Ok(cfg_path)
}

#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::test_dirs;
use crate::{utils, Error};

#[test]
fn config_create_read_and_write() -> Result<(), Error> {
let dir = test_dirs();
let config_path = config_path(Some(&dir))?;

assert!(utils::read_from_disk::<Config>(&config_path).is_err());

let cfg = Config::read_or_construct_default(Some(&dir))?;
let read_cfg = utils::read_from_disk(&config_path)?;

assert_eq!(cfg, read_cfg);
Ok(())
}
}
17 changes: 7 additions & 10 deletions src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const CERT_SERVER_NAME: &str = "MaidSAFE.net";
#[cfg(not(feature = "no-igd"))]
const PORT_FORWARD_TIMEOUT: u64 = 30;

// Number of seconds before timing out the echo service query.
const ECHO_SERVICE_QUERY_TIMEOUT: u64 = 30;

/// Channel on which incoming messages can be listened to
pub struct IncomingMessages(pub(crate) UnboundedReceiver<(SocketAddr, Bytes)>);

Expand Down Expand Up @@ -250,20 +253,14 @@ impl Endpoint {
if addr.is_none() {
// Try to contact an echo service
match timeout(
Duration::from_secs(PORT_FORWARD_TIMEOUT),
Duration::from_secs(ECHO_SERVICE_QUERY_TIMEOUT),
self.query_ip_echo_service(),
)
.await
{
Ok(res) => match res {
Ok(echo_res) => {
addr = Some(echo_res);
}
Err(err) => {
info!("Could not contact echo service: {} - {:?}", err, err);
}
},
Err(e) => info!("Echo service timed out: {:?}", e),
Ok(Ok(echo_res)) => addr = Some(echo_res),
Ok(Err(err)) => info!("Could not contact echo service: {} - {:?}", err, err),
Err(err) => info!("Query to echo service timed out: {:?}", err),
}
}

Expand Down

0 comments on commit 6f6f1f4

Please sign in to comment.