rustf 1.0.0

A simple MVC web framework inspired by Total.js
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
//! Global configuration access for RustF framework
//!
//! This module provides a global configuration singleton that enables uniform
//! configuration access throughout the application using dot notation paths.
//! All configuration sections - both predefined and custom - are accessed the same way.
//!
//! # Usage
//! ```rust
//! use rustf::CONF;
//!
//! // Access predefined configuration sections
//! let port = CONF::get_int("server.port").unwrap_or(8000);
//! let db_url = CONF::get_string("database.url");
//! let cache_enabled = CONF::get_bool("views.cache_enabled");
//!
//! // Access custom configuration sections (same syntax!)
//! let feature_flag = CONF::get_string("my-section.feature_flag");
//! let api_endpoint = CONF::get_string("my-section.api_endpoint");
//! let custom_val = CONF::get_string("custom.api_key");
//!
//! // With defaults
//! let timeout = CONF::get_or("server.timeout", 30);
//!
//! // Check existence
//! if CONF::has("database.url") {
//!     // Database is configured
//! }
//! ```

use crate::config::AppConfig;
use crate::error::{Error, Result};
use once_cell::sync::OnceCell;
use serde_json::Value;
use std::sync::Arc;

/// Global configuration instance
static CONFIG: OnceCell<ConfigStore> = OnceCell::new();

/// Internal storage for configuration
struct ConfigStore {
    /// Original typed configuration
    config: Arc<AppConfig>,
    /// JSON representation for path-based access
    json: Value,
}

/// Global configuration access point
///
/// Provides Total.js-style uniform configuration access using dot notation paths.
/// This allows any part of the application to access configuration values without
/// needing a Context or dependency injection.
pub struct CONF;

impl CONF {
    /// Initialize the global configuration
    ///
    /// This should be called once during application startup, typically in the
    /// RustF application builder.
    ///
    /// # Arguments
    /// * `config` - The application configuration to make globally available
    ///
    /// # Examples
    /// ```rust,ignore
    /// let config = AppConfig::load()?;
    /// CONF::init(config)?;
    /// ```
    pub fn init(config: AppConfig) -> Result<()> {
        // Convert config to JSON for path-based access
        let json = serde_json::to_value(&config)
            .map_err(|e| Error::internal(format!("Failed to serialize config: {}", e)))?;

        let store = ConfigStore {
            config: Arc::new(config),
            json,
        };

        CONFIG.set(store).map_err(|_| {
            Error::internal("Configuration has already been initialized".to_string())
        })?;

        log::debug!("Global configuration initialized");
        Ok(())
    }

    /// Get a configuration value by dot-notation path
    ///
    /// Returns the value at the specified path, or None if the path doesn't exist.
    /// The type T must implement Deserialize.
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the configuration value
    ///
    /// # Examples
    /// ```rust,ignore
    /// let port: Option<u16> = CONF::get("server.port");
    /// let db_url: Option<String> = CONF::get("database.url");
    /// ```
    pub fn get<T: serde::de::DeserializeOwned>(path: &str) -> Option<T> {
        let store = CONFIG.get()?;
        let value = Self::get_nested(&store.json, path)?;
        // Lenient: a value read with "(env) NAME" in a custom section is a
        // string; it still reads as a number or boolean when T asks for one.
        crate::config_lenient::from_value(value).ok()
    }

    /// Get a string configuration value
    ///
    /// Convenience method for getting string values.
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the configuration value
    ///
    /// # Examples
    /// ```rust,ignore
    /// let db_url = CONF::get_string("database.url");
    /// let api_key = CONF::get_string("custom.api_key");
    /// ```
    pub fn get_string(path: &str) -> Option<String> {
        Self::get(path)
    }

    /// Get an integer configuration value
    ///
    /// Convenience method for getting integer values.
    /// Handles both i64 and u64 internally.
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the configuration value
    ///
    /// # Examples
    /// ```rust,ignore
    /// let port = CONF::get_int("server.port").unwrap_or(8000);
    /// let max_connections = CONF::get_int("server.max_connections");
    /// ```
    pub fn get_int(path: &str) -> Option<i64> {
        let store = CONFIG.get()?;
        let value = Self::get_nested(&store.json, path)?;

        match value {
            Value::Number(n) => n.as_i64().or_else(|| n.as_u64().map(|u| u as i64)),
            // A custom value read with "(env) NAME" is kept as a string.
            Value::String(s) => s.trim().parse().ok(),
            _ => None,
        }
    }

    /// Get a boolean configuration value
    ///
    /// Convenience method for getting boolean values.
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the configuration value
    ///
    /// # Examples
    /// ```rust,ignore
    /// let ssl_enabled = CONF::get_bool("server.ssl_enabled").unwrap_or(false);
    /// let cache_enabled = CONF::get_bool("views.cache_enabled");
    /// ```
    pub fn get_bool(path: &str) -> Option<bool> {
        let store = CONFIG.get()?;
        match Self::get_nested(&store.json, path)? {
            Value::Bool(b) => Some(*b),
            // A custom value read with "(env) NAME" is kept as a string.
            Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
                "true" => Some(true),
                "false" => Some(false),
                _ => None,
            },
            _ => None,
        }
    }

    /// Get a float configuration value
    ///
    /// Convenience method for getting float values.
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the configuration value
    ///
    /// # Examples
    /// ```rust,ignore
    /// let rate = CONF::get_float("custom.exchange_rate");
    /// ```
    pub fn get_float(path: &str) -> Option<f64> {
        let store = CONFIG.get()?;
        let value = Self::get_nested(&store.json, path)?;

        match value {
            Value::Number(n) => n.as_f64(),
            // A custom value read with "(env) NAME" is kept as a string.
            Value::String(s) => s.trim().parse().ok(),
            _ => None,
        }
    }

    /// Get a configuration value with a default
    ///
    /// Returns the value at the specified path, or the default if the path doesn't exist.
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to the configuration value
    /// * `default` - Default value to return if path doesn't exist
    ///
    /// # Examples
    /// ```rust,ignore
    /// let port = CONF::get_or("server.port", 8000);
    /// let timeout = CONF::get_or("server.timeout", 30);
    /// ```
    pub fn get_or<T: serde::de::DeserializeOwned>(path: &str, default: T) -> T {
        Self::get(path).unwrap_or(default)
    }

    /// Check if a configuration path exists
    ///
    /// Returns true if the specified path exists in the configuration.
    ///
    /// # Arguments
    /// * `path` - Dot-separated path to check
    ///
    /// # Examples
    /// ```rust,ignore
    /// if CONF::has("database.url") {
    ///     // Database is configured
    /// }
    /// ```
    pub fn has(path: &str) -> bool {
        CONFIG
            .get()
            .and_then(|store| Self::get_nested(&store.json, path))
            .is_some()
    }

    /// Get the entire configuration
    ///
    /// Returns the full AppConfig. This is rarely needed as path-based access
    /// is preferred, but it's available for cases where the typed config is required.
    ///
    /// # Examples
    /// ```rust,ignore
    /// let config = CONF::all();
    /// let env = config.environment.as_str();
    /// ```
    pub fn all() -> Option<Arc<AppConfig>> {
        CONFIG.get().map(|store| store.config.clone())
    }

    /// Get the current environment
    ///
    /// Convenience method to get the current environment.
    ///
    /// # Examples
    /// ```rust,ignore
    /// let env = CONF::env(); // "development", "production", etc.
    /// ```
    pub fn env() -> Option<String> {
        Self::get_string("environment")
    }

    /// Check if running in production
    ///
    /// Convenience method to check if the application is in production mode.
    ///
    /// # Examples
    /// ```rust,ignore
    /// if CONF::is_production() {
    ///     // Enable production optimizations
    /// }
    /// ```
    pub fn is_production() -> bool {
        Self::env().map(|e| e == "production").unwrap_or(false)
    }

    /// Check if running in development
    ///
    /// Convenience method to check if the application is in development mode.
    ///
    /// # Examples
    /// ```rust,ignore
    /// if CONF::is_development() {
    ///     // Enable development features
    /// }
    /// ```
    pub fn is_development() -> bool {
        Self::env().map(|e| e == "development").unwrap_or(true)
    }

    /// Check if configuration is initialized
    ///
    /// Returns true if CONF::init() has been called successfully.
    ///
    /// # Examples
    /// ```rust,ignore
    /// if CONF::is_initialized() {
    ///     let port = CONF::get_int("server.port");
    /// }
    /// ```
    pub fn is_initialized() -> bool {
        CONFIG.get().is_some()
    }

    /// Internal helper to get nested values from JSON using dot notation
    fn get_nested<'a>(obj: &'a Value, path: &str) -> Option<&'a Value> {
        let parts: Vec<&str> = path.split('.').collect();
        let mut current = obj;

        for part in parts {
            match current {
                Value::Object(map) => {
                    current = map.get(part)?;
                }
                _ => return None,
            }
        }

        Some(current)
    }
}

/// Global DEBUG variable (Total.js style)
///
/// In Total.js style, DEBUG is a boolean variable that is true when the application
/// is in development mode, and false when in production mode.
///
/// This is based on the environment configuration (development vs production),
/// not on the compilation mode.
///
/// # Usage
/// ```rust
/// use rustf::prelude::*;
///
/// if *DEBUG {
///     // Enable debug features (development mode)
///     println!("Debug mode is active");
/// }
/// ```
///
/// Note: In Rust, you need to dereference with `*DEBUG` to get the bool value.
/// For a more Total.js-like experience, you can use `DEBUG.get()`.
pub static DEBUG: Debug = Debug;

/// The type of [`DEBUG`]. Reads the current environment every time, so it
/// cannot disagree with the loaded configuration: a value cached before
/// `CONF` was initialised would stay `true` in an app configured for
/// production.
#[derive(Debug, Clone, Copy)]
pub struct Debug;

impl Debug {
    /// Whether the application runs in development: `CONF`'s environment
    /// once loaded; before that, `RUSTF_ENV` (development when unset, not
    /// development when invalid — loading reports that as an error).
    pub fn get(&self) -> bool {
        if CONF::is_initialized() {
            CONF::is_development()
        } else {
            match crate::config::Environment::from_process_env() {
                Ok(Some(env)) => env.is_development(),
                Ok(None) => true,
                Err(_) => false,
            }
        }
    }
}

impl std::ops::Deref for Debug {
    type Target = bool;

    fn deref(&self) -> &bool {
        if self.get() {
            &true
        } else {
            &false
        }
    }
}

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

    #[test]
    fn test_conf_initialization_and_access() {
        // Create a test config
        // Create a test config using TOML to ensure correct section flattening
        let config_toml = r#"
            [server]
            port = 3000
            host = "localhost"

            [views]
            directory = "/test/views"

            [custom]
            api_key = "secret"
        "#;

        let config: AppConfig = toml::from_str(config_toml).unwrap();
        // Note: App-defined sections are now accessed via config.section() or CONF::get_string()
        // with unified access patterns, not via a separate .custom field

        // Initialize CONF
        CONF::init(config).unwrap();

        // Test various access methods
        assert_eq!(CONF::get_int("server.port"), Some(3000));
        assert_eq!(
            CONF::get_string("server.host"),
            Some("localhost".to_string())
        );
        assert_eq!(
            CONF::get_string("views.directory"),
            Some("/test/views".to_string())
        );

        // Test with defaults
        assert_eq!(CONF::get_or("server.port", 8000), 3000);
        assert_eq!(
            CONF::get_or("non.existent", "default".to_string()),
            "default".to_string()
        );

        // Test existence checks
        assert!(CONF::has("server.port"));
        assert!(CONF::has("custom.api_key"));
        assert!(!CONF::has("non.existent.path"));

        // Test environment helpers
        assert!(CONF::is_development());
        assert!(!CONF::is_production());
    }

    #[test]
    fn test_debug_reads_the_current_environment() {
        // `*DEBUG` and `DEBUG.get()` agree, and are recomputed on each read.
        assert_eq!(*DEBUG, DEBUG.get());
    }
}