1use crate::error::{Error, Result};
10use std::{
11 path::{Path, PathBuf},
12 time::Duration,
13};
14
15const ADDR_EXPIRY_DURATION: Duration = Duration::from_secs(24 * 60 * 60); const MAX_PEERS: usize = 1500;
20
21const MAX_ADDRS_PER_PEER: usize = 6;
23
24const MIN_BOOTSTRAP_CACHE_SAVE_INTERVAL: Duration = Duration::from_secs(5 * 60);
26
27const MAX_BOOTSTRAP_CACHE_SAVE_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
29
30#[derive(Clone, Debug)]
32pub struct BootstrapCacheConfig {
33 pub addr_expiry_duration: Duration,
35 pub max_peers: usize,
37 pub max_addrs_per_peer: usize,
39 pub cache_file_path: PathBuf,
41 pub disable_cache_writing: bool,
43 pub min_cache_save_duration: Duration,
45 pub max_cache_save_duration: Duration,
47 pub cache_save_scaling_factor: u64,
49}
50
51impl BootstrapCacheConfig {
52 pub fn default_config(local: bool) -> Result<Self> {
57 let cache_file_path = if local {
58 default_cache_path_local()?
59 } else {
60 default_cache_path()?
61 };
62 Ok(Self {
63 cache_file_path,
64 ..Self::empty()
65 })
66 }
67
68 pub fn empty() -> Self {
70 Self {
71 addr_expiry_duration: ADDR_EXPIRY_DURATION,
72 max_peers: MAX_PEERS,
73 max_addrs_per_peer: MAX_ADDRS_PER_PEER,
74 cache_file_path: PathBuf::new(),
75 disable_cache_writing: false,
76 min_cache_save_duration: MIN_BOOTSTRAP_CACHE_SAVE_INTERVAL,
77 max_cache_save_duration: MAX_BOOTSTRAP_CACHE_SAVE_INTERVAL,
78 cache_save_scaling_factor: 2,
79 }
80 }
81
82 pub fn with_addr_expiry_duration(mut self, duration: Duration) -> Self {
84 self.addr_expiry_duration = duration;
85 self
86 }
87
88 pub fn with_cache_path<P: AsRef<Path>>(mut self, path: P) -> Self {
90 self.cache_file_path = path.as_ref().to_path_buf();
91 self
92 }
93
94 pub fn with_max_peers(mut self, max_peers: usize) -> Self {
96 self.max_peers = max_peers;
97 self
98 }
99
100 pub fn with_addrs_per_peer(mut self, max_addrs: usize) -> Self {
102 self.max_addrs_per_peer = max_addrs;
103 self
104 }
105
106 pub fn with_disable_cache_writing(mut self, disable: bool) -> Self {
108 self.disable_cache_writing = disable;
109 self
110 }
111}
112
113fn default_cache_path() -> Result<PathBuf> {
115 Ok(default_cache_dir()?.join(cache_file_name()))
116}
117fn default_cache_path_local() -> Result<PathBuf> {
120 Ok(default_cache_dir()?.join(cache_file_name_local()))
121}
122
123fn default_cache_dir() -> Result<PathBuf> {
125 let dir = dirs_next::data_dir()
126 .ok_or_else(|| Error::CouldNotObtainDataDir)?
127 .join("autonomi")
128 .join("bootstrap_cache");
129
130 std::fs::create_dir_all(&dir)?;
131
132 Ok(dir)
133}
134
135pub fn cache_file_name() -> String {
137 format!("bootstrap_cache_{}.json", crate::get_network_version())
138}
139
140pub fn cache_file_name_local() -> String {
142 format!(
143 "bootstrap_cache_local_{}.json",
144 crate::get_network_version()
145 )
146}