about summary refs log tree commit diff
path: root/src/config.rs
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabua@gmail.com>2026-10-03 20:25:37 +0300
committerAlexander_Kabui <alexanderkabua@gmail.com>2026-10-03 20:25:37 +0300
commitfd0d45b98ec1136aeb84fc28fa647df9023abf75 (patch)
tree05748707d319deb9668a194a90c3724a69c4f328 /src/config.rs
parent5ecc6b70e8a6ce2ba91f7808295a7d7672481d58 (diff)
downloadgenenetwork4-fd0d45b98ec1136aeb84fc28fa647df9023abf75.tar.gz
Add foundation structure: config layering, response envelope, routes modules.
* src/config.rs: New module. Layered configuration,
  defaults -> GN4_CONF -> GN4_SECRETS -> environment, mirroring
  GeneNetwork3's SQL_URI convention so the two services can share
  configuration. Missing config files are ignored.
* src/response.rs: New module. The descriptive success envelope
  (data + next actions) from the foundation design note
  (topics/gn4/gn4-api-foundation.gmi). Not yet adopted by existing
  endpoints; that is a deliberate wire-format change to agree on
  before it ships.
* src/routes/mod.rs, species.rs, groups.rs: Move the species and
  groups handlers out of lib.rs into one module per domain, per the
  foundation structure. Handlers are pub; lib.rs just registers them.
* src/lib.rs (app): Register the moved routes. hello_world and
  version predate the domain split and stay as top-level utility
  routes.
* src/db.rs (sql_uri): Resolve through config::Config instead of
  reading the environment directly.
* src/main.rs: Bind the port from config::Config.
Diffstat (limited to 'src/config.rs')
-rw-r--r--src/config.rs92
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);
+    }
+}