oxidite-config 2.3.1

Configuration management for the Oxidite web framework
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum ConfigError {
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("TOML parse error: {0}")]
    TomlDe(#[from] toml::de::Error),
    #[error("YAML parse error: {0}")]
    YamlDe(#[from] serde_yaml::Error),
    #[error("invalid value for environment variable `{name}`: `{value}`")]
    InvalidEnvValue { name: String, value: String },
    #[error("missing configuration key: {0}")]
    MissingKey(String),
    #[error("invalid type for configuration key: {0}")]
    InvalidType(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Environment {
    Development,
    Testing,
    Production,
}

impl Environment {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "production" | "prod" => Self::Production,
            "testing" | "test" => Self::Testing,
            _ => Self::Development,
        }
    }

    pub fn as_str(&self) -> &str {
        match self {
            Self::Development => "development",
            Self::Testing => "testing",
            Self::Production => "production",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(default)]
    pub app: AppConfig,
    #[serde(default)]
    pub server: ServerConfig,
    #[serde(default)]
    pub database: DatabaseConfig,
    #[serde(default)]
    pub cache: CacheConfig,
    #[serde(default)]
    pub queue: QueueConfig,
    #[serde(default)]
    pub security: SecurityConfig,
    /// Custom environment variables defined in `[env]` of `oxidite.toml`.
    /// These are injected into the process environment at load time so that
    /// `env::var("WATU_API_KEY")` and similar calls work.
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default)]
    pub custom: HashMap<String, toml::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
    #[serde(default = "default_app_name")]
    pub name: String,
    #[serde(default)]
    pub version: String,
    #[serde(default)]
    pub environment: String,
    #[serde(default)]
    pub debug: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    #[serde(default = "default_host")]
    pub host: String,
    #[serde(default = "default_port")]
    pub port: u16,
    #[serde(default)]
    pub workers: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    #[serde(default)]
    pub url: String,
    #[serde(default = "default_pool_size")]
    pub pool_size: u32,
    #[serde(default)]
    pub ssl: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    #[serde(default)]
    pub driver: String,
    #[serde(default)]
    pub redis_url: String,
    #[serde(default = "default_ttl")]
    pub default_ttl: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueConfig {
    #[serde(default)]
    pub driver: String,
    #[serde(default)]
    pub redis_url: String,
    #[serde(default = "default_workers")]
    pub workers: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    #[serde(default)]
    pub jwt_secret: String,
    #[serde(default = "default_jwt_expiry")]
    pub jwt_expiry: u64,
    #[serde(default)]
    pub cors_origins: Vec<String>,
    #[serde(default)]
    pub cors_methods: Vec<String>,
    #[serde(default)]
    pub cors_headers: Vec<String>,
    #[serde(default)]
    pub rate_limit: u32,
}

// Default functions
fn default_app_name() -> String {
    "oxidite-app".to_string()
}

fn default_host() -> String {
    "127.0.0.1".to_string()
}

fn default_port() -> u16 {
    3000
}

fn default_pool_size() -> u32 {
    10
}

fn default_ttl() -> u64 {
    3600
}

fn default_workers() -> usize {
    4
}

fn default_jwt_expiry() -> u64 {
    900 // 15 minutes
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            name: default_app_name(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            environment: "development".to_string(),
            debug: true,
        }
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            workers: num_cpus::get(),
        }
    }
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            url: String::new(),
            pool_size: default_pool_size(),
            ssl: false,
        }
    }
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            driver: "memory".to_string(),
            redis_url: String::new(),
            default_ttl: default_ttl(),
        }
    }
}

impl Default for QueueConfig {
    fn default() -> Self {
        Self {
            driver: "memory".to_string(),
            redis_url: String::new(),
            workers: default_workers(),
        }
    }
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            jwt_secret: String::new(),
            jwt_expiry: default_jwt_expiry(),
            cors_origins: vec![],
            cors_methods: vec![],
            cors_headers: vec![],
            rate_limit: 0,
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            app: AppConfig::default(),
            server: ServerConfig::default(),
            database: DatabaseConfig::default(),
            cache: CacheConfig::default(),
            queue: QueueConfig::default(),
            security: SecurityConfig::default(),
            env: HashMap::new(),
            custom: HashMap::new(),
        }
    }
}

impl Config {
    /// Inject `[env]` entries from the config into the process environment.
    ///
    /// Real OS env vars take precedence over `[env]` values.  A variable is
    /// considered "set" only if it exists in the environment **and** is not
    /// empty, so blank `.env` entries like `WATU_API_KEY=` still allow the
    /// `oxidite.toml` fallback to apply.
    fn inject_env_vars(&self) {
        for (key, value) in &self.env {
            let already_set = env::var(key)
                .map(|v| !v.is_empty())
                .unwrap_or(false);
            if !already_set {
                env::set_var(key, value);
            }
        }
    }

    fn apply_env_overrides(&mut self) -> Result<(), ConfigError> {
        if let Ok(val) = env::var("APP_NAME") {
            self.app.name = val;
        }
        if let Ok(val) = env::var("SERVER_HOST") {
            self.server.host = val;
        }
        if let Ok(val) = env::var("SERVER_PORT") {
            self.server.port = val
                .parse()
                .map_err(|_| ConfigError::InvalidEnvValue {
                    name: "SERVER_PORT".to_string(),
                    value: val,
                })?;
        }
        if let Ok(val) = env::var("DATABASE_URL") {
            self.database.url = val;
        }
        if let Ok(val) = env::var("REDIS_URL") {
            self.cache.redis_url = val.clone();
            self.queue.redis_url = val;
        }
        if let Ok(val) = env::var("JWT_SECRET") {
            self.security.jwt_secret = val;
        }
        Ok(())
    }

    fn has_key(&self, key: &str) -> bool {
        if self.custom.contains_key(key) {
            return true;
        }
        let root = toml::Value::try_from(self).ok();
        if let Some(root) = root {
            let mut cursor = &root;
            for part in key.split('.') {
                if let Some(next) = cursor.get(part) {
                    cursor = next;
                } else {
                    return false;
                }
            }
            return true;
        }
        false
    }

    pub fn load() -> Result<Self, ConfigError> {
        // Load .env only if OXIDITE_SKIP_DOTENV is not set
        if env::var("OXIDITE_SKIP_DOTENV").is_err() {
            let _ = dotenv::dotenv();
        }

        let env_val = env::var("OXIDITE_ENV")
            .or_else(|_| env::var("ENVIRONMENT"))
            .unwrap_or_else(|_| "development".to_string());

        let mut config = if Path::new("oxidite.toml").exists() {
            let content = fs::read_to_string("oxidite.toml")?;
            toml::from_str(&content)?
        } else {
            Config::default()
        };

        // Inject [env] vars from oxidite.toml into the process environment.
        // Real OS env vars take precedence, so inject_env_vars only sets
        // variables that are not already defined.
        config.inject_env_vars();

        config.apply_env_overrides()?;
        config.app.environment = env_val;
        Ok(config)
    }

    pub fn load_from(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        // Load .env only if OXIDITE_SKIP_DOTENV is not set
        if env::var("OXIDITE_SKIP_DOTENV").is_err() {
            let _ = dotenv::dotenv();
        }

        let env_name = env::var("OXIDITE_ENV")
            .or_else(|_| env::var("ENVIRONMENT"))
            .unwrap_or_else(|_| "development".to_string());

        let mut config = if path.as_ref().exists() {
            let content = fs::read_to_string(path)?;
            toml::from_str(&content)?
        } else {
            Config::default()
        };

        // Inject [env] vars from oxidite.toml into the process environment
        config.inject_env_vars();

        config.app.environment = env_name;
        config.apply_env_overrides()?;
        Ok(config)
    }

    pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
        if let Some(value) = self.custom.get(key) {
            if let Ok(parsed) = T::deserialize(value.clone()) {
                return Some(parsed);
            }
        }

        let root = toml::Value::try_from(self).ok()?;
        let mut cursor = &root;
        for part in key.split('.') {
            cursor = cursor.get(part)?;
        }

        T::deserialize(cursor.clone()).ok()
    }

    pub fn get_required<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Result<T, ConfigError> {
        self.get(key).ok_or_else(|| {
            if self.has_key(key) {
                ConfigError::InvalidType(key.to_string())
            } else {
                ConfigError::MissingKey(key.to_string())
            }
        })
    }

    pub fn get_u16(&self, key: &str) -> Result<u16, ConfigError> {
        self.get_required(key)
    }

    pub fn get_bool(&self, key: &str) -> Result<bool, ConfigError> {
        self.get_required(key)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.server.host, "127.0.0.1");
        assert_eq!(config.server.port, 3000);
    }

    #[test]
    fn test_environment_parsing() {
        assert_eq!(Environment::from_str("production"), Environment::Production);
        assert_eq!(Environment::from_str("PROD"), Environment::Production);
    }

    #[test]
    fn test_get_required_typed_values() {
        let config = Config::default();
        assert_eq!(config.get_u16("server.port").unwrap(), 3000);
    }

    #[test]
    fn test_invalid_server_port_env_returns_error() {
        let _lock = SERIAL_TEST.lock().unwrap();
        let prev = env::var("SERVER_PORT").ok();
        env::set_var("SERVER_PORT", "not-a-port");
        let result = Config::load();
        if let Some(v) = prev { env::set_var("SERVER_PORT", v); } else { env::remove_var("SERVER_PORT"); }
        assert!(result.is_err());
    }

    #[test]
    fn test_load_from_applies_env_overrides() {
        let _lock = SERIAL_TEST.lock().unwrap();
        let prev_host = env::var("SERVER_HOST").ok();
        env::set_var("SERVER_HOST", "0.0.0.0");
        let cfg = Config::load_from("non-existent.toml").unwrap();
        if let Some(v) = prev_host { env::set_var("SERVER_HOST", v); } else { env::remove_var("SERVER_HOST"); }
        assert_eq!(cfg.server.host, "0.0.0.0");
    }

    use std::sync::Mutex;
    static SERIAL_TEST: Mutex<()> = Mutex::new(());
}