-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathconfig.rs
More file actions
290 lines (247 loc) · 9.27 KB
/
config.rs
File metadata and controls
290 lines (247 loc) · 9.27 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use anyhow::{Context, Result, bail};
use figment::Figment;
use figment::providers::{Env, Format, Toml};
use http::Uri;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::num::NonZeroU16;
use std::str::FromStr;
fn default_base() -> String {
"http://localhost:9042".to_string()
}
fn default_port() -> u16 {
9042
}
fn default_listen() -> ListenAddr {
ListenAddr::Port(default_port())
}
#[must_use]
pub fn default_maxmind_edition() -> String {
"GeoLite2-City".to_string()
}
fn default_data_dir() -> String {
#[cfg(target_family = "unix")]
{
let home = std::env::var("HOME").ok().unwrap_or_else(|| "/root".to_string());
std::env::var("XDG_DATA_HOME")
.map_or_else(|_| format!("{home}/.local/share/liwan/data"), |data_home| format!("{data_home}/liwan/data"))
}
#[cfg(not(target_family = "unix"))]
"./liwan-data".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
#[serde(default = "default_base")]
pub base_url: String,
#[serde(default = "default_listen", alias = "port")]
pub listen: ListenAddr,
#[serde(default)]
// don't load favicons from the duckduckgo api
pub disable_favicons: bool,
#[serde(default = "default_data_dir")]
pub data_dir: String,
#[serde(default)]
pub geoip: GeoIpConfig,
#[serde(default)]
pub duckdb: DuckdbConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum ListenAddr {
Port(u16),
Addr(String),
}
impl ListenAddr {
pub fn addr(&self) -> String {
match self {
ListenAddr::Port(port) => SocketAddr::from(([0, 0, 0, 0], *port)).to_string(),
ListenAddr::Addr(addr) => addr.clone(),
}
}
}
impl Default for Config {
fn default() -> Self {
Self {
base_url: default_base(),
listen: default_listen(),
data_dir: default_data_dir(),
geoip: Default::default(),
duckdb: Default::default(),
disable_favicons: false,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GeoIpConfig {
#[serde(default)]
pub maxmind_db_path: Option<String>,
#[serde(default, deserialize_with = "deserialize_string_from_number")]
pub maxmind_account_id: Option<String>,
#[serde(default)]
pub maxmind_license_key: Option<String>,
#[serde(default = "default_maxmind_edition")]
pub maxmind_edition: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DuckdbConfig {
#[serde(default)]
pub memory_limit: Option<String>,
#[serde(default)]
pub threads: Option<NonZeroU16>,
}
pub fn deserialize_string_from_number<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrNumber {
String(String),
Number(i64),
Float(f64),
}
match StringOrNumber::deserialize(deserializer)? {
StringOrNumber::String(s) => Ok(Some(s)),
StringOrNumber::Number(i) => Ok(Some(i.to_string())),
StringOrNumber::Float(f) => Ok(Some(f.to_string())),
}
}
pub static DEFAULT_CONFIG: &str = include_str!("../data/config.example.toml");
impl Config {
pub fn load(path: Option<String>) -> Result<Self> {
tracing::debug!(path = ?path, "loading config");
let path = path.or_else(|| std::env::var("LIWAN_CONFIG").ok());
let mut config = Figment::new()
.merge(Toml::file("liwan.config.toml"))
.merge(Toml::file(path.unwrap_or("liwan.config.toml".to_string())));
#[cfg(target_family = "unix")]
{
let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
let config_dir = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| format!("{home}/.config"));
config = config
.join(Toml::file(format!("{config_dir}/liwan/config.toml")))
.join(Toml::file(format!("{config_dir}/liwan/liwan.config.toml")))
.join(Toml::file(format!("{config_dir}/liwan.config.toml")));
}
let config: Self = config
.merge(Env::raw().filter_map(|key| match key {
k if !k.starts_with("LIWAN_") => None,
k if k.starts_with("LIWAN_MAXMIND_") => Some(format!("geoip.maxmind_{}", &k[14..]).into()),
k if k.starts_with("LIWAN_DUCKDB_") => Some(format!("duckdb.{}", &k[13..]).into()),
k => Some(k[6..].as_str().to_lowercase().into()),
}))
.extract()?;
let url: Uri = Uri::from_str(&config.base_url).context("Invalid base URL")?;
if ![Some("http"), Some("https")].contains(&url.scheme_str()) {
bail!("Invalid base URL: protocol must be either http or https");
}
Ok(config)
}
pub fn secure(&self) -> bool {
self.base_url.starts_with("https")
}
}
#[cfg(test)]
#[allow(clippy::result_large_err)]
mod test {
use super::*;
use figment::Jail;
#[test]
fn test_config() {
Jail::expect_with(|jail| {
jail.create_file(
"liwan2.config.toml",
r#"
base_url = "http://localhost:8081"
data_dir = "./liwan-test-data"
[geoip]
maxmind_db_path = "test2"
"#,
)?;
jail.set_env("LIWAN_MAXMIND_EDITION", "test");
jail.set_env("LIWAN_GEOIP_MAXMIND_EDITION", "test2");
jail.set_env("GEOIP_MAXMIND_EDITION", "test3");
jail.set_env("LIWAN_DUCKDB_MEMORY_LIMIT", "2GB");
jail.set_env("LIWAN_DUCKDB_THREADS", 4);
jail.set_env("LIWAN_MAXMIND_LICENSE_KEY", "test");
jail.set_env("LIWAN_MAXMIND_ACCOUNT_ID", "test");
jail.set_env("LIWAN_MAXMIND_DB_PATH", "test");
let config = Config::load(Some("liwan2.config.toml".into())).expect("failed to load config");
assert_eq!(config.geoip.maxmind_edition, "test".to_string());
assert_eq!(config.geoip.maxmind_license_key, Some("test".to_string()));
assert_eq!(config.geoip.maxmind_account_id, Some("test".to_string()));
assert_eq!(config.geoip.maxmind_db_path, Some("test".to_string()));
assert_eq!(config.base_url, "http://localhost:8081");
assert_eq!(config.data_dir, "./liwan-test-data");
assert_eq!(config.listen, ListenAddr::Port(9042));
assert_eq!(config.duckdb.memory_limit, Some("2GB".to_string()));
assert_eq!(config.duckdb.threads, Some(NonZeroU16::new(4).unwrap()));
Ok(())
});
}
#[test]
fn test_no_geoip() {
Jail::expect_with(|jail| {
jail.create_file(
"liwan3.config.toml",
r#"
base_url = "http://localhost:8081"
data_dir = "./liwan-test-data"
"#,
)?;
let config = Config::load(Some("liwan3.config.toml".into())).expect("failed to load config");
assert!(config.geoip.maxmind_db_path.is_none());
assert!(config.geoip.maxmind_account_id.is_none());
assert!(config.geoip.maxmind_license_key.is_none());
assert_eq!(config.base_url, "http://localhost:8081");
assert_eq!(config.data_dir, "./liwan-test-data");
assert_eq!(config.listen, ListenAddr::Port(9042));
Ok(())
});
}
#[test]
fn test_default_geoip() {
Jail::expect_with(|jail| {
jail.create_file(
"liwan3.config.toml",
r#"
base_url = "http://localhost:8081"
data_dir = "./liwan-test-data"
[geoip]
maxmind_db_path = "test2"
"#,
)?;
let config = Config::load(Some("liwan3.config.toml".into())).expect("failed to load config");
assert_eq!(config.geoip.maxmind_edition, default_maxmind_edition());
assert_eq!(config.geoip.maxmind_db_path, Some("test2".to_string()));
assert_eq!(config.base_url, "http://localhost:8081");
assert_eq!(config.data_dir, "./liwan-test-data");
Ok(())
});
}
#[test]
fn test_env() {
Jail::expect_with(|jail| {
jail.set_env("LIWAN_DATA_DIR", "/data");
jail.set_env("LIWAN_BASE_URL", "https://example.com");
jail.set_env("LIWAN_MAXMIND_ACCOUNT_ID", 123);
let config = Config::load(None).expect("failed to load config");
assert_eq!(config.data_dir, "/data");
assert_eq!(config.base_url, "https://example.com");
assert_eq!(config.geoip.maxmind_account_id, Some("123".to_string()));
Ok(())
});
}
#[test]
fn test_no_config() {
Jail::expect_with(|_jail| {
let config = Config::load(None).expect("failed to load config");
assert!(config.geoip.maxmind_db_path.is_none());
assert!(config.geoip.maxmind_account_id.is_none());
assert!(config.geoip.maxmind_license_key.is_none());
assert_eq!(config.base_url, "http://localhost:9042");
assert_eq!(config.listen, ListenAddr::Port(9042));
Ok(())
});
}
}