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
use crate::Error;
use log::{debug, warn};
use qp2p::Config as QuicP2pConfig;
use serde::{Deserialize, Serialize};
use std::{
collections::HashSet,
fs::File,
io::{self, BufReader},
net::SocketAddr,
path::Path,
};
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct Config {
pub qp2p: QuicP2pConfig,
}
impl Config {
pub fn new(
config_file_path: Option<&Path>,
bootstrap_config: Option<HashSet<SocketAddr>>,
) -> Self {
let mut qp2p = match &config_file_path {
None => QuicP2pConfig::default(),
Some(path) => match read_config_file(path) {
Err(Error::IoError(ref err)) if err.kind() == io::ErrorKind::NotFound => {
QuicP2pConfig {
bootstrap_cache_dir: path.parent().map(|p| p.display().to_string()),
..Default::default()
}
}
result => result.unwrap_or_default(),
},
};
if let Some(contacts) = bootstrap_config {
debug!("Bootstrapping contacts overriden with: {:?}", contacts);
qp2p.hard_coded_contacts = contacts;
}
Self { qp2p }
}
}
fn read_config_file(filepath: &Path) -> Result<QuicP2pConfig, Error> {
match File::open(filepath) {
Ok(file) => {
debug!("Reading config file '{}' ...", filepath.display());
let reader = BufReader::new(file);
serde_json::from_reader(reader).map_err(|err| {
warn!(
"Could not parse content of config file '{}': {}",
filepath.display(),
err
);
err.into()
})
}
Err(err) => {
warn!(
"Failed to open config file from '{}': {}",
filepath.display(),
err
);
Err(err.into())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::test_utils::init_logger;
use anyhow::Result;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{env::temp_dir, fs::create_dir_all};
#[test]
#[ignore]
fn custom_config_path() -> Result<()> {
init_logger();
let path = temp_dir();
let random_filename: String = thread_rng().sample_iter(&Alphanumeric).take(15).collect();
let config_filepath = path.join(random_filename);
let config = Config::new(Some(&config_filepath), None);
let mut str_path = path
.to_str()
.ok_or(anyhow::anyhow!("No path for to_str".to_string()))?
.to_string();
if str_path.ends_with('/') {
let _ = str_path.pop();
}
let expected_config = Config {
qp2p: QuicP2pConfig {
bootstrap_cache_dir: Some(str_path),
..Default::default()
},
};
assert_eq!(config, expected_config);
create_dir_all(path)?;
let mut file = File::create(&config_filepath)?;
let config_on_disk = Config::default();
serde_json::to_writer_pretty(&mut file, &config_on_disk)?;
file.sync_all()?;
let read_cfg = Config::new(Some(&config_filepath), None);
assert_eq!(config_on_disk, read_cfg);
let default_cfg = Config::new(None, None);
assert_eq!(Config::default(), default_cfg);
Ok(())
}
}