diff options
Diffstat (limited to 'src/config.rs')
| -rw-r--r-- | src/config.rs | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..eff8f22 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,92 @@ +//! Layered configuration, mirroring GeneNetwork3's convention: +//! +//! ```text +//! built-in defaults -> GN4_CONF file -> GN4_SECRETS file -> environment +//! ``` +//! +//! GN4_CONF and GN4_SECRETS are paths to files of `KEY=VALUE` lines +//! (# comments and blank lines allowed). Splitting secrets into their +//! own file lets GN4_CONF be checked into a repo while GN4_SECRETS +//! stays out of it. Environment variables always win, so ad-hoc +//! overrides never need a file edit. + +use std::collections::HashMap; + +/// The GeneNetwork4 configuration. +pub struct Config { + /// mysql://user:password@host/database. Same SQL_URI config key + /// GeneNetwork3 uses, so the two services can share configuration. + pub sql_uri: String, + /// TCP port to bind. + pub port: u16, +} + +impl Config { + /// Load configuration from all layers, highest priority last. + pub fn load() -> Config { + let mut values = HashMap::<String, String>::new(); + + // Layer 1: built-in defaults. + values.insert("SQL_URI".to_string(), "mysql://webqtlout:webqtlout@127.0.0.1/db_webqtl".to_string()); + values.insert("GENENETWORK4_PORT".to_string(), "3000".to_string()); + + // Layers 2 and 3: config files, in increasing priority. + for env_key in ["GN4_CONF", "GN4_SECRETS"] { + if let Ok(path) = std::env::var(env_key) { + for (key, value) in load_file(&path) { + values.insert(key, value); + } + } + } + + // Layer 4: environment wins over everything. + for key in ["SQL_URI", "GENENETWORK4_PORT"] { + if let Ok(value) = std::env::var(key) { + values.insert(key.to_string(), value); + } + } + + Config { + sql_uri: values["SQL_URI"].clone(), + port: values["GENENETWORK4_PORT"] + .parse() + .expect("GENENETWORK4_PORT must be a number"), + } + } +} + +/// Parse a `KEY=VALUE` file into a map. Missing/unreadable files are +/// ignored so a stale GN4_CONF path never stops the server from +/// starting on defaults. +fn load_file(path: &str) -> HashMap<String, String> { + let Ok(contents) = std::fs::read_to_string(path) else { + return HashMap::new(); + }; + let mut map = HashMap::new(); + for line in contents.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + if let Some((key, value)) = line.split_once('=') { + map.insert(key.trim().to_string(), value.trim().to_string()); + } + } + map +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_apply_with_no_files_or_env() { + // Safe only because tests run without these set; guard anyway. + if std::env::var("SQL_URI").is_ok() || std::env::var("GN4_CONF").is_ok() { + return; + } + let config = Config::load(); + assert!(config.sql_uri.contains("db_webqtl")); + assert_eq!(config.port, 3000); + } +} |
