use crate::error::{Error, Result};
use std::{
path::{Path, PathBuf},
time::Duration,
};
const ADDR_EXPIRY_DURATION: Duration = Duration::from_secs(24 * 60 * 60);
const MAX_PEERS: usize = 1500;
const MAX_ADDRS_PER_PEER: usize = 6;
const MIN_BOOTSTRAP_CACHE_SAVE_INTERVAL: Duration = Duration::from_secs(5 * 60);
const MAX_BOOTSTRAP_CACHE_SAVE_INTERVAL: Duration = Duration::from_secs(3 * 60 * 60);
#[derive(Clone, Debug)]
pub struct BootstrapCacheConfig {
pub addr_expiry_duration: Duration,
pub max_peers: usize,
pub max_addrs_per_peer: usize,
pub cache_file_path: PathBuf,
pub disable_cache_writing: bool,
pub min_cache_save_duration: Duration,
pub max_cache_save_duration: Duration,
pub cache_save_scaling_factor: u64,
}
impl BootstrapCacheConfig {
pub fn default_config(local: bool) -> Result<Self> {
let cache_file_path = if local {
default_cache_path_local()?
} else {
default_cache_path()?
};
Ok(Self {
cache_file_path,
..Self::empty()
})
}
pub fn empty() -> Self {
Self {
addr_expiry_duration: ADDR_EXPIRY_DURATION,
max_peers: MAX_PEERS,
max_addrs_per_peer: MAX_ADDRS_PER_PEER,
cache_file_path: PathBuf::new(),
disable_cache_writing: false,
min_cache_save_duration: MIN_BOOTSTRAP_CACHE_SAVE_INTERVAL,
max_cache_save_duration: MAX_BOOTSTRAP_CACHE_SAVE_INTERVAL,
cache_save_scaling_factor: 2,
}
}
pub fn with_addr_expiry_duration(mut self, duration: Duration) -> Self {
self.addr_expiry_duration = duration;
self
}
pub fn with_cache_path<P: AsRef<Path>>(mut self, path: P) -> Self {
self.cache_file_path = path.as_ref().to_path_buf();
self
}
pub fn with_max_peers(mut self, max_peers: usize) -> Self {
self.max_peers = max_peers;
self
}
pub fn with_addrs_per_peer(mut self, max_addrs: usize) -> Self {
self.max_addrs_per_peer = max_addrs;
self
}
pub fn with_disable_cache_writing(mut self, disable: bool) -> Self {
self.disable_cache_writing = disable;
self
}
}
fn default_cache_path() -> Result<PathBuf> {
Ok(default_cache_dir()?.join(cache_file_name()))
}
fn default_cache_path_local() -> Result<PathBuf> {
Ok(default_cache_dir()?.join(cache_file_name_local()))
}
fn default_cache_dir() -> Result<PathBuf> {
let dir = dirs_next::data_dir()
.ok_or_else(|| Error::CouldNotObtainDataDir)?
.join("autonomi")
.join("bootstrap_cache");
std::fs::create_dir_all(&dir)?;
Ok(dir)
}
pub fn cache_file_name() -> String {
format!("bootstrap_cache_{}.json", crate::get_network_version())
}
pub fn cache_file_name_local() -> String {
format!(
"bootstrap_cache_local_{}.json",
crate::get_network_version()
)
}