1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use crate::client::{Error, Result};
use qp2p::Config as QuicP2pConfig;
use serde::{Deserialize, Serialize};
use std::{
net::{Ipv4Addr, SocketAddr},
path::{Path, PathBuf},
time::Duration,
};
use tokio::{
fs::File,
io::{self, AsyncReadExt},
};
use tracing::{debug, warn};
const DEFAULT_LOCAL_ADDR: (Ipv4Addr, u16) = (Ipv4Addr::UNSPECIFIED, 0);
pub const DEFAULT_QUERY_TIMEOUT: Duration = Duration::from_secs(90);
const DEFAULT_ROOT_DIR_NAME: &str = "root_dir";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Config {
pub local_addr: SocketAddr,
pub root_dir: PathBuf,
pub genesis_key: bls::PublicKey,
pub qp2p: QuicP2pConfig,
pub query_timeout: Duration,
}
impl Config {
pub async fn new(
root_dir: Option<&Path>,
local_addr: Option<SocketAddr>,
genesis_key: bls::PublicKey,
config_file_path: Option<&Path>,
query_timeout: Option<Duration>,
) -> Self {
let root_dir = root_dir
.map(|p| p.to_path_buf())
.unwrap_or_else(default_dir);
let mut qp2p = match &config_file_path {
None => QuicP2pConfig::default(),
Some(path) => read_config_file(path).await.unwrap_or_default(),
};
qp2p.idle_timeout = Some(Duration::from_secs(5));
qp2p.keep_alive_interval = Some(Duration::from_secs(1));
Self {
local_addr: local_addr.unwrap_or_else(|| SocketAddr::from(DEFAULT_LOCAL_ADDR)),
root_dir: root_dir.clone(),
genesis_key,
qp2p,
query_timeout: query_timeout.unwrap_or(DEFAULT_QUERY_TIMEOUT),
}
}
}
async fn read_config_file(filepath: &Path) -> Result<QuicP2pConfig, Error> {
debug!("Reading config file '{}' ...", filepath.display());
let mut file = File::open(filepath).await?;
let mut contents = vec![];
let _ = file.read_to_end(&mut contents).await?;
serde_json::from_slice(&contents).map_err(|err| {
warn!(
"Could not parse content of config file '{}': {}",
filepath.display(),
err
);
err.into()
})
}
fn default_dir() -> PathBuf {
project_dirs()
.unwrap_or_default()
.join(DEFAULT_ROOT_DIR_NAME)
}
fn project_dirs() -> Result<PathBuf> {
let mut home_dir = dirs_next::home_dir()
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Home directory not found"))?;
home_dir.push(".safe");
home_dir.push("client");
Ok(home_dir)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::client::utils::test_utils::init_test_logger;
use bincode::serialize;
use eyre::Result;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::fs::File;
use tempfile::tempdir;
use tokio::fs::create_dir_all;
#[tokio::test(flavor = "multi_thread")]
async fn custom_config_path() -> Result<()> {
init_test_logger();
let temp_dir = tempdir().map_err(|e| Error::Generic(e.to_string()))?;
let root_dir = temp_dir.path().to_path_buf();
let cfg_filename: String = thread_rng().sample_iter(&Alphanumeric).take(15).collect();
let config_filepath = root_dir.join(&cfg_filename);
let genesis_key = bls::SecretKey::random().public_key();
let config = Config::new(
Some(&root_dir),
None,
genesis_key,
Some(&config_filepath),
None,
)
.await;
let mut str_path = root_dir
.to_str()
.ok_or(eyre::eyre!("No path for to_str".to_string()))?
.to_string();
if str_path.ends_with('/') {
let _ = str_path.pop();
}
let expected_config = Config {
local_addr: (Ipv4Addr::UNSPECIFIED, 0).into(),
root_dir: root_dir.clone(),
genesis_key,
qp2p: QuicP2pConfig::default(),
query_timeout: DEFAULT_QUERY_TIMEOUT,
};
assert_eq!(serialize(&config)?, serialize(&expected_config)?);
create_dir_all(&root_dir).await?;
let mut file = File::create(&config_filepath)?;
let config_on_disk =
Config::new(None, None, genesis_key, Some(&config_filepath), None).await;
serde_json::to_writer_pretty(&mut file, &config_on_disk)?;
file.sync_all()?;
let read_cfg = Config::new(None, None, genesis_key, None, None).await;
assert_eq!(serialize(&config_on_disk)?, serialize(&read_cfg)?);
Ok(())
}
}