Skip to main content

config_lib/
config.rs

1//! # High-Level Configuration Management
2//!
3//! Advanced configuration management API providing intuitive interfaces for
4//! loading, modifying, validating, and saving configurations with format preservation.
5
6use crate::error::{Error, Result};
7use crate::parsers;
8use crate::value::Value;
9use dashmap::DashMap;
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{Arc, RwLock};
14
15#[cfg(feature = "schema")]
16use crate::schema::Schema;
17
18#[cfg(feature = "validation")]
19use crate::validation::{ValidationError, ValidationRuleSet};
20
21/// High-level configuration manager with format preservation and change tracking
22///
23/// [`Config`] provides a comprehensive API for managing configurations
24/// throughout their lifecycle. It maintains both the resolved values (for fast access)
25/// and format-specific preservation data (for round-trip editing).
26///
27/// ## Key Features
28///
29/// - **Format Preservation**: Maintains comments, whitespace, and original formatting
30/// - **Change Tracking**: Automatic detection of modifications
31/// - **Type Safety**: Rich type conversion with comprehensive error handling
32/// - **Path-based Access**: Dot notation for nested value access
33/// - **Multi-format Support**: CONF, TOML, JSON, NOML formats
34/// - **Schema Validation**: Optional schema validation and enforcement
35/// - **Async Support**: Non-blocking file operations (with feature flag)
36///
37/// ## Examples
38///
39/// ```rust
40/// use config_lib::Config;
41///
42/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
43/// // Load from string
44/// let mut config = Config::from_string("port = 8080\nname = \"MyApp\"", None)?;
45///
46/// // Access values
47/// let port = config.get("port").unwrap().as_integer()?;
48/// let name = config.get("name").unwrap().as_string()?;
49///
50/// // Modify values
51/// config.set("port", 9000)?;
52///
53/// # Ok(())
54/// # }
55/// ```
56#[derive(Debug)]
57pub struct Config {
58    /// The resolved configuration values
59    values: Value,
60
61    /// Path to the source file (if loaded from file)
62    file_path: Option<PathBuf>,
63
64    /// Detected or specified format
65    format: String,
66
67    /// Change tracking - has the config been modified?
68    modified: bool,
69
70    /// Opt-out behavior knobs (read-only, cache sizing, etc.).
71    /// See [`ConfigOptions`].
72    options: ConfigOptions,
73
74    /// Cache hit counter (loaded via `Ordering::Relaxed` from
75    /// [`Config::cache_stats`]). Wired in v0.9.9 — populated by
76    /// [`Config::get_arc`] when the cache layer is enabled.
77    cache_hits: AtomicU64,
78
79    /// Cache miss counter. See [`Config::cache_stats`].
80    cache_misses: AtomicU64,
81
82    /// Resolved-path cache. `DashMap` is sharded so reads hold a
83    /// short shard-local lock rather than a global lock; under
84    /// typical config workloads (read-mostly, infrequent writes)
85    /// this provides effectively-lock-free reads. Storing
86    /// `Arc<Value>` keeps clones cheap on hit (refcount bump only).
87    ///
88    /// Population is lazy — only paths actually requested through
89    /// [`Config::get_arc`] enter the cache. `set` / `remove` /
90    /// `merge` clear the cache entirely (writes are rare in the
91    /// design envelope; a per-prefix invalidation strategy is
92    /// post-1.0 backlog).
93    cache: DashMap<Box<str>, Arc<Value>>,
94
95    /// Per-path defaults table consulted by [`Config::get_or_default`]
96    /// when the requested path is missing from `values`. Wrapped in
97    /// `Arc<RwLock<_>>` so defaults can be updated independently of
98    /// the main value tree, including under `read_only` mode (defaults
99    /// are operator-provided fallbacks, not user-supplied data).
100    defaults: Arc<RwLock<BTreeMap<String, Value>>>,
101
102    /// Format-specific preservation data
103    #[cfg(feature = "noml")]
104    noml_document: Option<noml::Document>,
105
106    /// Validation rules for this configuration
107    #[cfg(feature = "validation")]
108    validation_rules: Option<ValidationRuleSet>,
109}
110
111impl Config {
112    /// Create a new empty configuration
113    pub fn new() -> Self {
114        Self {
115            values: Value::table(BTreeMap::new()),
116            file_path: None,
117            format: "conf".to_string(),
118            modified: false,
119            options: ConfigOptions::default(),
120            cache_hits: AtomicU64::new(0),
121            cache_misses: AtomicU64::new(0),
122            cache: DashMap::new(),
123            defaults: Arc::new(RwLock::new(BTreeMap::new())),
124            #[cfg(feature = "noml")]
125            noml_document: None,
126            #[cfg(feature = "validation")]
127            validation_rules: None,
128        }
129    }
130
131    /// Load configuration from a string
132    pub fn from_string(source: &str, format: Option<&str>) -> Result<Self> {
133        let detected_format = format.unwrap_or_else(|| parsers::detect_format(source));
134        let values = parsers::parse_string(source, Some(detected_format))?;
135        Ok(Self::from_parsed(source, detected_format, values))
136    }
137
138    /// Load configuration from a string without reading anything outside it
139    ///
140    /// The same as [`Config::from_string`] for every format except NOML
141    /// (feature `noml`): `include` and every function call (`env()`
142    /// included) are refused with [`Error::Parse`] carrying the line and
143    /// column of the first one, and the message does not quote the input.
144    /// NOML native types (`@size("10MB")`) and `${...}` references to other
145    /// values in the same document still work.
146    ///
147    /// Use it when the caller has checked the configuration file itself
148    /// (owner, mode, size, file type) before handing its text over: an
149    /// include would read a second file without those checks, and `env()`
150    /// would copy an environment variable into the configuration.
151    ///
152    /// TOML, JSON, CONF and the other formats read only the text in both
153    /// entry points (TOML refuses NOML's `include` and `env()` everywhere
154    /// since v1.3.0). With no format hint, a document that uses `include`
155    /// or `env(` is detected as NOML and refused here.
156    ///
157    /// Since v1.3.0.
158    ///
159    /// # Examples
160    ///
161    /// ```rust
162    /// use config_lib::Config;
163    ///
164    /// let config = Config::from_string_strict("port = 8080", Some("conf"))?;
165    /// assert_eq!(config.get("port").map(|v| v.as_integer()).transpose()?, Some(8080));
166    /// # Ok::<(), config_lib::Error>(())
167    /// ```
168    pub fn from_string_strict(source: &str, format: Option<&str>) -> Result<Self> {
169        let detected_format = format.unwrap_or_else(|| parsers::detect_format(source));
170        let values = parsers::parse_string_strict(source, Some(detected_format))?;
171        Ok(Self::from_parsed(source, detected_format, values))
172    }
173
174    /// Build a `Config` from values already parsed out of `source`
175    fn from_parsed(source: &str, detected_format: &str, values: Value) -> Self {
176        #[cfg(not(feature = "noml"))]
177        let _ = source;
178
179        #[cfg(feature = "noml")]
180        let mut config = Self {
181            values,
182            file_path: None,
183            format: detected_format.to_string(),
184            modified: false,
185            options: ConfigOptions::default(),
186            cache_hits: AtomicU64::new(0),
187            cache_misses: AtomicU64::new(0),
188            cache: DashMap::new(),
189            defaults: Arc::new(RwLock::new(BTreeMap::new())),
190            noml_document: None,
191            #[cfg(feature = "validation")]
192            validation_rules: None,
193        };
194
195        #[cfg(not(feature = "noml"))]
196        let config = Self {
197            values,
198            file_path: None,
199            format: detected_format.to_string(),
200            modified: false,
201            options: ConfigOptions::default(),
202            cache_hits: AtomicU64::new(0),
203            cache_misses: AtomicU64::new(0),
204            cache: DashMap::new(),
205            defaults: Arc::new(RwLock::new(BTreeMap::new())),
206            #[cfg(feature = "validation")]
207            validation_rules: None,
208        };
209
210        // Store format-specific preservation data (parsed only, never
211        // resolved, so nothing outside `source` is read here)
212        #[cfg(feature = "noml")]
213        if detected_format == "noml" || detected_format == "toml" {
214            if let Ok(document) = noml::parse_string(source, None) {
215                config.noml_document = Some(document);
216            }
217        }
218
219        config
220    }
221
222    /// Load configuration from a file
223    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
224        let path = path.as_ref();
225        let content =
226            std::fs::read_to_string(path).map_err(|e| Error::io(path.display().to_string(), e))?;
227
228        let format = parsers::detect_format_from_path(path)
229            .unwrap_or_else(|| parsers::detect_format(&content));
230
231        let mut config = Self::from_string(&content, Some(format))?;
232        config.file_path = Some(path.to_path_buf());
233
234        Ok(config)
235    }
236
237    /// Async version of from_file
238    #[cfg(feature = "async")]
239    pub async fn from_file_async<P: AsRef<Path>>(path: P) -> Result<Self> {
240        let path = path.as_ref();
241        let content = tokio::fs::read_to_string(path)
242            .await
243            .map_err(|e| Error::io(path.display().to_string(), e))?;
244
245        let format = parsers::detect_format_from_path(path)
246            .unwrap_or_else(|| parsers::detect_format(&content));
247
248        let mut config = Self::from_string(&content, Some(format))?;
249        config.file_path = Some(path.to_path_buf());
250
251        Ok(config)
252    }
253
254    /// Get a value by path
255    pub fn get(&self, path: &str) -> Option<&Value> {
256        self.values.get(path)
257    }
258
259    /// Get a mutable reference to a value by path
260    pub fn get_mut(&mut self, path: &str) -> Result<&mut Value> {
261        self.values.get_mut_nested(path)
262    }
263
264    /// Set a value by path
265    ///
266    /// Invalidates the entire resolved-path cache (writes are rare in
267    /// the design envelope; a per-prefix invalidation strategy is
268    /// post-1.0 backlog).
269    ///
270    /// # Errors
271    ///
272    /// Returns an error if:
273    /// - The configuration was constructed with [`ConfigOptions::read_only`]
274    /// - The path is invalid (e.g. attempts to insert into a non-table value)
275    pub fn set<V: Into<Value>>(&mut self, path: &str, value: V) -> Result<()> {
276        self.ensure_writable()?;
277        self.values.set_nested(path, value.into())?;
278        self.modified = true;
279        self.cache.clear();
280        Ok(())
281    }
282
283    /// Remove a value by path
284    ///
285    /// Invalidates the entire resolved-path cache on success.
286    ///
287    /// # Errors
288    ///
289    /// Returns an error if:
290    /// - The configuration was constructed with [`ConfigOptions::read_only`]
291    /// - The path is malformed
292    pub fn remove(&mut self, path: &str) -> Result<Option<Value>> {
293        self.ensure_writable()?;
294        let result = self.values.remove(path)?;
295        if result.is_some() {
296            self.modified = true;
297            self.cache.clear();
298        }
299        Ok(result)
300    }
301
302    /// Check if a path exists
303    pub fn contains_key(&self, path: &str) -> bool {
304        self.values.contains_key(path)
305    }
306
307    /// Get all keys in the configuration
308    pub fn keys(&self) -> Result<Vec<&str>> {
309        self.values.keys()
310    }
311
312    /// Check if the configuration has been modified
313    pub fn is_modified(&self) -> bool {
314        self.modified
315    }
316
317    /// Mark the configuration as unmodified
318    pub fn mark_clean(&mut self) {
319        self.modified = false;
320    }
321
322    /// Get the configuration format
323    pub fn format(&self) -> &str {
324        &self.format
325    }
326
327    /// Get the file path (if loaded from file)
328    pub fn file_path(&self) -> Option<&Path> {
329        self.file_path.as_deref()
330    }
331
332    /// Save the configuration to its original file
333    pub fn save(&mut self) -> Result<()> {
334        match &self.file_path {
335            Some(path) => {
336                self.save_to_file(path.clone())?;
337                self.modified = false;
338                Ok(())
339            }
340            None => Err(Error::internal(
341                "Cannot save configuration that wasn't loaded from a file",
342            )),
343        }
344    }
345
346    /// Save the configuration to a specific file
347    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
348        let serialized = self.serialize()?;
349        std::fs::write(path, serialized).map_err(|e| Error::io("save".to_string(), e))?;
350        Ok(())
351    }
352
353    /// Async version of save
354    #[cfg(feature = "async")]
355    pub async fn save_async(&mut self) -> Result<()> {
356        match &self.file_path {
357            Some(path) => {
358                self.save_to_file_async(path.clone()).await?;
359                self.modified = false;
360                Ok(())
361            }
362            None => Err(Error::internal(
363                "Cannot save configuration that wasn't loaded from a file",
364            )),
365        }
366    }
367
368    /// Async version of save_to_file
369    #[cfg(feature = "async")]
370    pub async fn save_to_file_async<P: AsRef<Path>>(&self, path: P) -> Result<()> {
371        let serialized = self.serialize()?;
372        tokio::fs::write(path, serialized)
373            .await
374            .map_err(|e| Error::io("save".to_string(), e))?;
375        Ok(())
376    }
377
378    /// Serialize the configuration to string format
379    pub fn serialize(&self) -> Result<String> {
380        match self.format.as_str() {
381            "json" => {
382                #[cfg(any(feature = "json", feature = "jsonx"))]
383                return crate::parsers::json_parser::serialize(&self.values);
384                #[cfg(not(any(feature = "json", feature = "jsonx")))]
385                return Err(Error::feature_not_enabled("json"));
386            }
387            "toml" => {
388                #[cfg(feature = "toml")]
389                {
390                    // The preserved document keeps comments and formatting,
391                    // but only matches the values until they are changed
392                    #[cfg(feature = "noml")]
393                    if !self.modified {
394                        if let Some(ref document) = self.noml_document {
395                            return Ok(noml::serialize_document(document)?);
396                        }
397                    }
398                    self.serialize_as_toml(false)
399                }
400                #[cfg(not(feature = "toml"))]
401                return Err(Error::feature_not_enabled("toml"));
402            }
403            "noml" => {
404                #[cfg(feature = "noml")]
405                {
406                    if !self.modified {
407                        if let Some(ref document) = self.noml_document {
408                            return Ok(noml::serialize_document(document)?);
409                        }
410                    }
411                    self.serialize_as_toml(true)
412                }
413                #[cfg(not(feature = "noml"))]
414                return Err(Error::feature_not_enabled("noml"));
415            }
416            "conf" => self.serialize_as_conf(),
417            _ => Err(Error::unknown_format(&self.format)),
418        }
419    }
420
421    /// Serialize as CONF format
422    fn serialize_as_conf(&self) -> Result<String> {
423        let mut output = String::new();
424        if let Value::Table(table) = &self.values {
425            self.write_conf_table(&mut output, table, "")?;
426        }
427        Ok(output)
428    }
429
430    /// Helper to write CONF format table
431    fn write_conf_table(
432        &self,
433        output: &mut String,
434        table: &BTreeMap<String, Value>,
435        section_prefix: &str,
436    ) -> Result<()> {
437        // First pass: write simple key-value pairs
438        for (key, value) in table {
439            if !value.is_table() {
440                let formatted_value = self.format_conf_value(value)?;
441                output.push_str(&format!("{key} = {formatted_value}\n"));
442            }
443        }
444
445        // Second pass: write sections
446        for (key, value) in table {
447            if let Value::Table(nested_table) = value {
448                let section_name = if section_prefix.is_empty() {
449                    key.clone()
450                } else {
451                    format!("{section_prefix}.{key}")
452                };
453
454                output.push_str(&format!("\n[{section_name}]\n"));
455                self.write_conf_table(output, nested_table, &section_name)?;
456            }
457        }
458
459        Ok(())
460    }
461
462    /// Format a value for CONF output
463    #[allow(clippy::only_used_in_recursion)]
464    fn format_conf_value(&self, value: &Value) -> Result<String> {
465        match value {
466            Value::Null => Ok("null".to_string()),
467            Value::Bool(b) => Ok(b.to_string()),
468            Value::Integer(i) => Ok(i.to_string()),
469            Value::Float(f) => Ok(f.to_string()),
470            Value::String(s) => {
471                if s.contains(' ') || s.contains('\t') || s.contains('\n') {
472                    Ok(format!("\"{}\"", s.replace('"', "\\\"")))
473                } else {
474                    Ok(s.clone())
475                }
476            }
477            Value::Array(arr) => {
478                let items: Result<Vec<String>> =
479                    arr.iter().map(|v| self.format_conf_value(v)).collect();
480                Ok(items?.join(" "))
481            }
482            Value::Table(_) => Err(Error::type_error(
483                "Cannot serialize nested table as value",
484                "primitive",
485                "table",
486            )),
487            #[cfg(feature = "chrono")]
488            Value::DateTime(dt) => Ok(dt.to_rfc3339()),
489        }
490    }
491
492    /// Serialize the values as TOML text.
493    ///
494    /// Writes the current values as TOML. With `noml` set, a literal `${` in
495    /// a string is written as `$${` so NOML does not treat it as
496    /// interpolation when the file is read back. TOML has no null, so a null
497    /// value is an error unless writing NOML.
498    #[cfg(any(feature = "toml", feature = "noml"))]
499    fn serialize_as_toml(&self, noml: bool) -> Result<String> {
500        let mut out = String::new();
501        if let Value::Table(table) = &self.values {
502            toml_writer::write_table(&mut out, table, &mut Vec::new(), noml)?;
503        }
504        Ok(out)
505    }
506
507    /// Validate the configuration against a schema
508    #[cfg(feature = "schema")]
509    pub fn validate_schema(&self, schema: &Schema) -> Result<()> {
510        schema.validate(&self.values)
511    }
512
513    /// Get the underlying Value
514    pub fn as_value(&self) -> &Value {
515        &self.values
516    }
517
518    /// Merge another configuration into this one
519    ///
520    /// Invalidates the entire resolved-path cache.
521    ///
522    /// # Errors
523    ///
524    /// Returns an error if the configuration was constructed with
525    /// [`ConfigOptions::read_only`].
526    pub fn merge(&mut self, other: &Config) -> Result<()> {
527        self.ensure_writable()?;
528        self.merge_value(&other.values)?;
529        self.modified = true;
530        self.cache.clear();
531        Ok(())
532    }
533
534    /// Helper to merge values recursively
535    fn merge_value(&mut self, other: &Value) -> Result<()> {
536        match (&mut self.values, other) {
537            (Value::Table(self_table), Value::Table(other_table)) => {
538                for (key, other_value) in other_table {
539                    match self_table.get_mut(key) {
540                        Some(self_value) => {
541                            if let (Value::Table(_), Value::Table(_)) = (&*self_value, other_value)
542                            {
543                                // Create a temporary config for recursive merging
544                                let mut temp_config = Config::new();
545                                temp_config.values = self_value.clone();
546                                temp_config.merge_value(other_value)?;
547                                *self_value = temp_config.values;
548                            } else {
549                                // Replace value
550                                *self_value = other_value.clone();
551                            }
552                        }
553                        None => {
554                            // Insert new value
555                            self_table.insert(key.clone(), other_value.clone());
556                        }
557                    }
558                }
559            }
560            _ => {
561                // Replace entire value
562                self.values = other.clone();
563            }
564        }
565        Ok(())
566    }
567
568    // =====================================================================
569    // Validation Methods (Feature-gated)
570    // =====================================================================
571
572    // --- CONVENIENCE METHODS & BUILDER PATTERN ---
573
574    /// Get a value by path with a more ergonomic API
575    pub fn key(&self, path: &str) -> ConfigValue<'_> {
576        ConfigValue::new(self.get(path))
577    }
578
579    /// Check if configuration has any value at the given path
580    pub fn has(&self, path: &str) -> bool {
581        self.contains_key(path)
582    }
583
584    /// Get a value with a default fallback
585    pub fn get_or<V>(&self, path: &str, default: V) -> V
586    where
587        V: TryFrom<Value> + Clone,
588        V::Error: std::fmt::Debug,
589    {
590        self.get(path)
591            .and_then(|v| V::try_from(v.clone()).ok())
592            .unwrap_or(default)
593    }
594
595    // --- VALIDATION SUPPORT ---
596
597    /// Set validation rules for this configuration
598    #[cfg(feature = "validation")]
599    pub fn set_validation_rules(&mut self, rules: ValidationRuleSet) {
600        self.validation_rules = Some(rules);
601    }
602
603    /// Validate the current configuration against all registered rules
604    #[cfg(feature = "validation")]
605    pub fn validate(&mut self) -> Result<Vec<ValidationError>> {
606        match &mut self.validation_rules {
607            Some(rules) => {
608                if let Value::Table(table) = &self.values {
609                    let mut errors = Vec::new();
610
611                    // Validate each key-value pair
612                    for (key, value) in table {
613                        errors.extend(rules.validate(key, value));
614                    }
615
616                    // Also validate for required keys (if any RequiredKeyValidator exists)
617                    // This is handled by individual rule implementations
618
619                    Ok(errors)
620                } else {
621                    Err(Error::validation(
622                        "Configuration root must be a table for validation",
623                    ))
624                }
625            }
626            None => Ok(Vec::new()), // No rules = no errors
627        }
628    }
629
630    /// Validate and return only critical errors
631    #[cfg(feature = "validation")]
632    pub fn validate_critical_only(&mut self) -> Result<Vec<ValidationError>> {
633        let all_errors = self.validate()?;
634        Ok(all_errors
635            .into_iter()
636            .filter(|e| e.severity == crate::validation::ValidationSeverity::Critical)
637            .collect())
638    }
639
640    /// Check if configuration is valid (has no critical errors)
641    #[cfg(feature = "validation")]
642    pub fn is_valid(&mut self) -> Result<bool> {
643        let critical_errors = self.validate_critical_only()?;
644        Ok(critical_errors.is_empty())
645    }
646
647    /// Validate a specific value at a path
648    #[cfg(feature = "validation")]
649    pub fn validate_path(&mut self, path: &str) -> Result<Vec<ValidationError>> {
650        // Get the value first to avoid borrowing conflicts, clone to own it
651        let value = self
652            .get(path)
653            .ok_or_else(|| Error::key_not_found(path))?
654            .clone();
655
656        match &mut self.validation_rules {
657            Some(rules) => Ok(rules.validate(path, &value)),
658            None => Ok(Vec::new()),
659        }
660    }
661}
662
663impl Default for Config {
664    fn default() -> Self {
665        Self::new()
666    }
667}
668
669// =========================================================================
670// ConfigOptions — opt-out behavior knobs (foundation for v0.9.5)
671// =========================================================================
672
673/// Opt-out behavior knobs for [`Config`].
674///
675/// `ConfigOptions` carries the small set of toggles that should not be
676/// enabled by default: making a `Config` read-only, sizing the cache,
677/// and so on. The struct is `#[non_exhaustive]` so v0.9.x can add new
678/// knobs without breaking SemVer. Users construct it via
679/// [`ConfigOptions::new`] or [`ConfigOptions::default`] and apply
680/// individual toggles through the consuming builder methods.
681///
682/// The field set lays the groundwork for the lock-free caching work
683/// landing in v0.9.5. In v0.9.4 the only knob that has runtime effect
684/// is [`ConfigOptions::read_only`]; the cache-related knobs are
685/// accepted today so that the public API surface does not change
686/// again when v0.9.5 switches the cache on.
687///
688/// # Examples
689///
690/// ```rust
691/// use config_lib::{Config, ConfigOptions};
692///
693/// // Default options — caching on, writes allowed.
694/// let _cfg = Config::with_options(ConfigOptions::default());
695///
696/// // Read-only configuration for a hot path that must never be mutated.
697/// let opts = ConfigOptions::new().read_only(true);
698/// let _cfg = Config::with_options(opts);
699/// ```
700#[derive(Debug, Clone)]
701#[non_exhaustive]
702pub struct ConfigOptions {
703    /// Reject every `set` / `remove` / `merge` call with
704    /// [`Error::general`] instead of mutating. Useful for once-loaded
705    /// configurations that must never change at runtime.
706    pub read_only: bool,
707
708    /// Whether the internal caching layer is active. **Reserved** — the
709    /// caching layer ships in v0.9.5; in v0.9.4 this field is accepted
710    /// for forward compatibility but does not yet change runtime
711    /// behavior (every `get` already hits an in-memory `Value`).
712    pub cache_enabled: bool,
713
714    /// Maximum number of resolved-key entries the cache will hold
715    /// before evicting. **Reserved for v0.9.5.**
716    pub cache_capacity: usize,
717}
718
719impl Default for ConfigOptions {
720    /// The canonical options for the Hive DB use case:
721    /// caching enabled, writes allowed, capacity tuned for typical
722    /// server config size.
723    fn default() -> Self {
724        Self {
725            read_only: false,
726            cache_enabled: true,
727            cache_capacity: 1024,
728        }
729    }
730}
731
732impl ConfigOptions {
733    /// Construct a `ConfigOptions` with default values
734    /// ([`ConfigOptions::default`]).
735    pub fn new() -> Self {
736        Self::default()
737    }
738
739    /// Set the read-only flag. See [`ConfigOptions::read_only`].
740    pub fn read_only(mut self, read_only: bool) -> Self {
741        self.read_only = read_only;
742        self
743    }
744
745    /// Toggle the caching layer. **Reserved for v0.9.5** — currently
746    /// a no-op at runtime; the setter exists so call-sites compile
747    /// against the same shape they will use after the cache lands.
748    pub fn cache_enabled(mut self, cache_enabled: bool) -> Self {
749        self.cache_enabled = cache_enabled;
750        self
751    }
752
753    /// Set the cache capacity. **Reserved for v0.9.5** — see
754    /// [`ConfigOptions::cache_enabled`].
755    pub fn cache_capacity(mut self, cache_capacity: usize) -> Self {
756        self.cache_capacity = cache_capacity;
757        self
758    }
759}
760
761impl Config {
762    /// Construct a new empty [`Config`] with the supplied
763    /// [`ConfigOptions`].
764    ///
765    /// This is the explicit opt-out constructor. For the canonical
766    /// defaults (caching on, writes allowed), prefer [`Config::new`].
767    pub fn with_options(options: ConfigOptions) -> Self {
768        let mut config = Self::new();
769        config.options = options;
770        config
771    }
772
773    /// Return the [`ConfigOptions`] currently in effect on this config.
774    pub fn options(&self) -> &ConfigOptions {
775        &self.options
776    }
777
778    /// Returns `true` if this configuration was constructed read-only
779    /// (see [`ConfigOptions::read_only`]).
780    pub fn is_read_only(&self) -> bool {
781        self.options.read_only
782    }
783
784    /// Helper used by mutating methods to short-circuit when the
785    /// configuration is in read-only mode.
786    fn ensure_writable(&self) -> Result<()> {
787        if self.options.read_only {
788            Err(Error::general("Configuration is read-only"))
789        } else {
790            Ok(())
791        }
792    }
793
794    /// Return a snapshot of the cache-hit / cache-miss counters.
795    ///
796    /// Counters are loaded with `Ordering::Relaxed` — the values are
797    /// statistics, not synchronisation primitives, and the hit/miss
798    /// classification is best-effort under concurrent reads.
799    pub fn cache_stats(&self) -> CacheStats {
800        let hits = self.cache_hits.load(Ordering::Relaxed);
801        let misses = self.cache_misses.load(Ordering::Relaxed);
802        let total = hits.saturating_add(misses);
803        let hit_ratio = if total == 0 {
804            0.0
805        } else {
806            hits as f64 / total as f64
807        };
808        CacheStats {
809            hits,
810            misses,
811            hit_ratio,
812        }
813    }
814
815    /// Resolve a dotted path to a cached `Arc<Value>`.
816    ///
817    /// `get_arc` is the cache-backed thread-safe accessor introduced
818    /// in v0.9.9. The first lookup of a given path walks the value
819    /// tree, allocates an `Arc<Value>` containing a clone of the
820    /// resolved node, and inserts it into the resolved-path cache.
821    /// Subsequent lookups of the same path hit the cache and return
822    /// a cheap refcount-bump clone of the `Arc<Value>`.
823    ///
824    /// This is the recommended accessor for:
825    ///
826    /// - **Multi-threaded reads.** `Arc<Value>` is `Send + Sync` and
827    ///   independent of `&self`'s lifetime, so the value can be
828    ///   handed off to other threads.
829    /// - **Hot loops.** Cache hits avoid the tree walk; the
830    ///   refcount bump is a single relaxed atomic.
831    ///
832    /// The existing `Config::get(&self, path) -> Option<&Value>` is
833    /// still the right choice for single-threaded reads that just
834    /// peek and drop the borrow — no clone, no Arc bump.
835    ///
836    /// The cache is invalidated wholesale on any `set` / `remove` /
837    /// `merge`. The runtime knob [`ConfigOptions::cache_enabled`]
838    /// (default `true`) toggles the cache layer; with it disabled,
839    /// every `get_arc` call walks the tree and allocates a fresh
840    /// `Arc<Value>`.
841    pub fn get_arc(&self, path: &str) -> Option<Arc<Value>> {
842        if self.options.cache_enabled {
843            if let Some(entry) = self.cache.get(path) {
844                self.cache_hits.fetch_add(1, Ordering::Relaxed);
845                return Some(Arc::clone(entry.value()));
846            }
847            self.cache_misses.fetch_add(1, Ordering::Relaxed);
848            let resolved = self.values.get(path)?.clone();
849            let arc = Arc::new(resolved);
850            self.cache.insert(path.into(), Arc::clone(&arc));
851            Some(arc)
852        } else {
853            self.cache_misses.fetch_add(1, Ordering::Relaxed);
854            Some(Arc::new(self.values.get(path)?.clone()))
855        }
856    }
857
858    /// Clear the resolved-path cache.
859    ///
860    /// Idempotent; safe to call from any thread. Useful when an
861    /// out-of-band actor (e.g. a hot-reload watcher) has changed
862    /// the underlying value tree and the cache snapshot is now stale.
863    pub fn clear_cache(&self) {
864        self.cache.clear();
865    }
866
867    /// Set a default value for the given path.
868    ///
869    /// Defaults are an operator-supplied fallback table consulted by
870    /// [`Config::get_or_default`] when the requested path is missing
871    /// from the main value tree. Defaults are independent of the
872    /// `read_only` flag — a read-only configuration can still have
873    /// its defaults table populated (defaults are deployment-time
874    /// declarations, not user-supplied data).
875    ///
876    /// Calls to `set_default` do **not** invalidate the cache; the
877    /// cache is keyed on observed value-tree resolutions, not on
878    /// defaults-table membership.
879    ///
880    /// # Errors
881    ///
882    /// Returns an error if the defaults-table lock has been poisoned.
883    pub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()> {
884        let mut defaults = self
885            .defaults
886            .write()
887            .map_err(|_| Error::concurrency("defaults table lock poisoned"))?;
888        defaults.insert(path.to_string(), value.into());
889        Ok(())
890    }
891
892    /// Resolve a path against the main value tree, falling back to the
893    /// defaults table when not found.
894    ///
895    /// Returns `None` only when neither the value tree nor the defaults
896    /// table contains an entry for `path`. The return type is owned
897    /// (`Option<Value>`) because the defaults table sits behind an
898    /// `Arc<RwLock<_>>` and producing a borrowed reference would
899    /// require holding the lock guard across the caller's use.
900    pub fn get_or_default(&self, path: &str) -> Option<Value> {
901        if let Some(v) = self.values.get(path) {
902            return Some(v.clone());
903        }
904        let defaults = self.defaults.read().ok()?;
905        defaults.get(path).cloned()
906    }
907
908    /// Toggle this configuration into read-only mode at runtime.
909    ///
910    /// Equivalent to constructing with
911    /// `ConfigOptions::new().read_only(true)` but available as a
912    /// post-construction switch. Subsequent calls to `set` / `remove`
913    /// / `merge` return `Err(Error::general("Configuration is
914    /// read-only"))`.
915    ///
916    /// The toggle is **one-way** by design — there is no
917    /// `make_writable()` companion. A configuration that has been
918    /// declared immutable should not become mutable again; if you
919    /// need that flexibility, keep two `Config` handles instead.
920    pub fn make_read_only(&mut self) {
921        self.options.read_only = true;
922    }
923}
924
925// =========================================================================
926// CacheStats — read-only snapshot of cache performance counters
927// =========================================================================
928
929/// Snapshot of a [`Config`]'s cache-hit / cache-miss counters.
930///
931/// Returned by [`Config::cache_stats`]. The struct is `#[non_exhaustive]`
932/// so the v1.x SemVer contract can add new counter fields (e.g.
933/// `evictions`, `insertions`, per-shard breakdowns) in MINOR releases
934/// without breaking user code.
935///
936/// # Stability note for v0.9.5
937///
938/// In v0.9.5 every `CacheStats` returned by [`Config::cache_stats`]
939/// has `hits = 0`, `misses = 0`, `hit_ratio = 0.0`. The lock-free
940/// cache layer that populates these counters lands in a follow-up
941/// v0.9.5 implementation release. The struct is shipping now so the
942/// API surface is locked in ahead of the implementation.
943///
944/// # Examples
945///
946/// ```rust
947/// use config_lib::Config;
948///
949/// let cfg = Config::new();
950/// let stats = cfg.cache_stats();
951/// assert_eq!(stats.hits, 0);
952/// assert_eq!(stats.misses, 0);
953/// assert_eq!(stats.hit_ratio, 0.0);
954/// ```
955#[derive(Debug, Clone, Copy)]
956#[non_exhaustive]
957pub struct CacheStats {
958    /// Number of cache lookups that resolved to a cached value.
959    pub hits: u64,
960    /// Number of cache lookups that did not find a cached value and
961    /// fell through to the canonical storage.
962    pub misses: u64,
963    /// `hits / (hits + misses)` as an f64 in `[0.0, 1.0]`. Returns
964    /// `0.0` when no lookups have happened yet.
965    pub hit_ratio: f64,
966}
967
968/// Ergonomic wrapper for accessing configuration values
969pub struct ConfigValue<'a> {
970    value: Option<&'a Value>,
971}
972
973impl<'a> ConfigValue<'a> {
974    fn new(value: Option<&'a Value>) -> Self {
975        Self { value }
976    }
977
978    /// Get as string with default fallback
979    pub fn as_string(&self) -> Result<String> {
980        match self.value {
981            Some(v) => v.as_string().map(|s| s.to_string()),
982            None => Err(Error::key_not_found("value not found")),
983        }
984    }
985
986    /// Get as string with custom default
987    pub fn as_string_or(&self, default: &str) -> String {
988        self.value
989            .and_then(|v| v.as_string().ok())
990            .map(|s| s.to_string())
991            .unwrap_or_else(|| default.to_string())
992    }
993
994    /// Get as integer with default fallback
995    pub fn as_integer(&self) -> Result<i64> {
996        match self.value {
997            Some(v) => v.as_integer(),
998            None => Err(Error::key_not_found("value not found")),
999        }
1000    }
1001
1002    /// Get as integer with custom default
1003    pub fn as_integer_or(&self, default: i64) -> i64 {
1004        self.value
1005            .and_then(|v| v.as_integer().ok())
1006            .unwrap_or(default)
1007    }
1008
1009    /// Get as boolean with default fallback
1010    pub fn as_bool(&self) -> Result<bool> {
1011        match self.value {
1012            Some(v) => v.as_bool(),
1013            None => Err(Error::key_not_found("value not found")),
1014        }
1015    }
1016
1017    /// Get as boolean with custom default
1018    pub fn as_bool_or(&self, default: bool) -> bool {
1019        self.value.and_then(|v| v.as_bool().ok()).unwrap_or(default)
1020    }
1021
1022    /// Check if the value exists
1023    pub fn exists(&self) -> bool {
1024        self.value.is_some()
1025    }
1026
1027    /// Get the underlying Value reference if it exists
1028    pub fn value(&self) -> Option<&'a Value> {
1029        self.value
1030    }
1031}
1032
1033/// Builder pattern for Config creation
1034pub struct ConfigBuilder {
1035    format: Option<String>,
1036    #[cfg(feature = "validation")]
1037    validation_rules: Option<ValidationRuleSet>,
1038}
1039
1040impl ConfigBuilder {
1041    /// Create a new ConfigBuilder
1042    pub fn new() -> Self {
1043        Self {
1044            format: None,
1045            #[cfg(feature = "validation")]
1046            validation_rules: None,
1047        }
1048    }
1049
1050    /// Set the configuration format
1051    pub fn format<S: Into<String>>(mut self, format: S) -> Self {
1052        self.format = Some(format.into());
1053        self
1054    }
1055
1056    /// Set validation rules
1057    #[cfg(feature = "validation")]
1058    pub fn validation_rules(mut self, rules: ValidationRuleSet) -> Self {
1059        self.validation_rules = Some(rules);
1060        self
1061    }
1062
1063    /// Build Config from string
1064    pub fn from_string(self, source: &str) -> Result<Config> {
1065        #[cfg(feature = "validation")]
1066        let mut config = Config::from_string(source, self.format.as_deref())?;
1067        #[cfg(not(feature = "validation"))]
1068        let config = Config::from_string(source, self.format.as_deref())?;
1069
1070        #[cfg(feature = "validation")]
1071        if let Some(rules) = self.validation_rules {
1072            config.set_validation_rules(rules);
1073        }
1074
1075        Ok(config)
1076    }
1077
1078    /// Build Config from file
1079    pub fn from_file<P: AsRef<Path>>(self, path: P) -> Result<Config> {
1080        #[cfg(feature = "validation")]
1081        let mut config = Config::from_file(path)?;
1082        #[cfg(not(feature = "validation"))]
1083        let config = Config::from_file(path)?;
1084
1085        #[cfg(feature = "validation")]
1086        if let Some(rules) = self.validation_rules {
1087            config.set_validation_rules(rules);
1088        }
1089
1090        Ok(config)
1091    }
1092}
1093
1094impl Default for ConfigBuilder {
1095    fn default() -> Self {
1096        Self::new()
1097    }
1098}
1099
1100/// Convert Value to Config
1101impl From<Value> for Config {
1102    fn from(value: Value) -> Self {
1103        Self {
1104            values: value,
1105            file_path: None,
1106            format: "conf".to_string(),
1107            modified: false,
1108            options: ConfigOptions::default(),
1109            cache_hits: AtomicU64::new(0),
1110            cache_misses: AtomicU64::new(0),
1111            cache: DashMap::new(),
1112            defaults: Arc::new(RwLock::new(BTreeMap::new())),
1113            #[cfg(feature = "noml")]
1114            noml_document: None,
1115            #[cfg(feature = "validation")]
1116            validation_rules: None,
1117        }
1118    }
1119}
1120
1121/// TOML text output for TOML and modified NOML configurations
1122#[cfg(any(feature = "toml", feature = "noml"))]
1123mod toml_writer {
1124    use crate::error::{Error, Result};
1125    use crate::value::Value;
1126    use std::collections::BTreeMap;
1127    use std::fmt::Write;
1128
1129    fn is_table_array(value: &Value) -> bool {
1130        matches!(value, Value::Array(items)
1131            if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Table(_))))
1132    }
1133
1134    /// Write plain keys first, then `[table]` and `[[array]]` sections
1135    pub(super) fn write_table(
1136        out: &mut String,
1137        table: &BTreeMap<String, Value>,
1138        path: &mut Vec<String>,
1139        noml: bool,
1140    ) -> Result<()> {
1141        for (key, value) in table {
1142            if !matches!(value, Value::Table(_)) && !is_table_array(value) {
1143                write_key(out, key);
1144                out.push_str(" = ");
1145                write_value(out, value, path, key, noml)?;
1146                out.push('\n');
1147            }
1148        }
1149        for (key, value) in table {
1150            path.push(key.clone());
1151            match value {
1152                Value::Table(inner) => {
1153                    header(out, path, false);
1154                    write_table(out, inner, path, noml)?;
1155                }
1156                Value::Array(items) if is_table_array(value) => {
1157                    for item in items {
1158                        header(out, path, true);
1159                        if let Value::Table(inner) = item {
1160                            write_table(out, inner, path, noml)?;
1161                        }
1162                    }
1163                }
1164                _ => {}
1165            }
1166            path.pop();
1167        }
1168        Ok(())
1169    }
1170
1171    fn header(out: &mut String, path: &[String], array: bool) {
1172        if !out.is_empty() {
1173            out.push('\n');
1174        }
1175        out.push_str(if array { "[[" } else { "[" });
1176        for (i, key) in path.iter().enumerate() {
1177            if i > 0 {
1178                out.push('.');
1179            }
1180            write_key(out, key);
1181        }
1182        out.push_str(if array { "]]\n" } else { "]\n" });
1183    }
1184
1185    fn write_key(out: &mut String, key: &str) {
1186        let bare = key.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
1187            && key
1188                .bytes()
1189                .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
1190        if bare {
1191            out.push_str(key);
1192        } else {
1193            write_string(out, key, false);
1194        }
1195    }
1196
1197    fn write_string(out: &mut String, s: &str, noml: bool) {
1198        out.push('"');
1199        let mut chars = s.chars().peekable();
1200        while let Some(c) = chars.next() {
1201            match c {
1202                '"' => out.push_str("\\\""),
1203                '\\' => out.push_str("\\\\"),
1204                '\n' => out.push_str("\\n"),
1205                '\t' => out.push_str("\\t"),
1206                '\r' => out.push_str("\\r"),
1207                '$' if noml && chars.peek() == Some(&'{') => out.push_str("$$"),
1208                c if c.is_control() => {
1209                    let _ = write!(out, "\\u{:04X}", c as u32);
1210                }
1211                c => out.push(c),
1212            }
1213        }
1214        out.push('"');
1215    }
1216
1217    fn write_value(
1218        out: &mut String,
1219        value: &Value,
1220        path: &[String],
1221        key: &str,
1222        noml: bool,
1223    ) -> Result<()> {
1224        match value {
1225            Value::Null if noml => out.push_str("null"),
1226            Value::Null => {
1227                let mut full = path.join(".");
1228                if !full.is_empty() {
1229                    full.push('.');
1230                }
1231                full.push_str(key);
1232                return Err(Error::serialize(format!(
1233                    "TOML has no null value; cannot write '{full}'"
1234                )));
1235            }
1236            Value::Bool(b) => {
1237                let _ = write!(out, "{b}");
1238            }
1239            Value::Integer(i) => {
1240                let _ = write!(out, "{i}");
1241            }
1242            Value::Float(f) => {
1243                if f.is_nan() {
1244                    out.push_str("nan");
1245                } else if f.is_infinite() {
1246                    out.push_str(if *f > 0.0 { "inf" } else { "-inf" });
1247                } else {
1248                    // Debug always keeps a '.' or exponent, so it reads back as a float
1249                    let _ = write!(out, "{f:?}");
1250                }
1251            }
1252            Value::String(s) => write_string(out, s, noml),
1253            Value::Array(items) => {
1254                out.push('[');
1255                for (i, item) in items.iter().enumerate() {
1256                    if i > 0 {
1257                        out.push_str(", ");
1258                    }
1259                    write_value(out, item, path, key, noml)?;
1260                }
1261                out.push(']');
1262            }
1263            Value::Table(table) => {
1264                out.push('{');
1265                for (i, (k, v)) in table.iter().enumerate() {
1266                    out.push_str(if i > 0 { ", " } else { " " });
1267                    write_key(out, k);
1268                    out.push_str(" = ");
1269                    write_value(out, v, path, key, noml)?;
1270                }
1271                out.push_str(if table.is_empty() { "}" } else { " }" });
1272            }
1273            #[cfg(feature = "chrono")]
1274            Value::DateTime(dt) => write_string(out, &dt.to_rfc3339(), noml),
1275        }
1276        Ok(())
1277    }
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282    use super::*;
1283
1284    #[test]
1285    fn test_config_creation() {
1286        let config = Config::new();
1287        assert!(!config.is_modified());
1288        assert_eq!(config.format(), "conf");
1289    }
1290
1291    #[test]
1292    fn test_config_from_string() {
1293        let config = Config::from_string("key = value\nport = 8080", Some("conf")).unwrap();
1294
1295        assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
1296        assert_eq!(config.get("port").unwrap().as_integer().unwrap(), 8080);
1297    }
1298
1299    #[test]
1300    fn test_config_modification() {
1301        let mut config = Config::new();
1302        assert!(!config.is_modified());
1303
1304        config.set("key", "value").unwrap();
1305        assert!(config.is_modified());
1306
1307        config.mark_clean();
1308        assert!(!config.is_modified());
1309    }
1310
1311    #[test]
1312    fn test_config_merge() {
1313        let mut config1 = Config::new();
1314        config1.set("a", 1).unwrap();
1315        config1.set("b.x", 2).unwrap();
1316
1317        let mut config2 = Config::new();
1318        config2.set("b.y", 3).unwrap();
1319        config2.set("c", 4).unwrap();
1320
1321        config1.merge(&config2).unwrap();
1322
1323        assert_eq!(config1.get("a").unwrap().as_integer().unwrap(), 1);
1324        assert_eq!(config1.get("b.x").unwrap().as_integer().unwrap(), 2);
1325        assert_eq!(config1.get("b.y").unwrap().as_integer().unwrap(), 3);
1326        assert_eq!(config1.get("c").unwrap().as_integer().unwrap(), 4);
1327    }
1328
1329    #[cfg(feature = "toml")]
1330    #[test]
1331    fn modified_toml_serializes_current_values() {
1332        let source = "# comment\nname = \"app\"\n\n[server]\nport = 80\n";
1333        let mut config = Config::from_string(source, Some("toml")).unwrap();
1334
1335        // Unchanged: the original text is kept when the document is preserved
1336        #[cfg(feature = "noml")]
1337        assert_eq!(config.serialize().unwrap(), source);
1338
1339        config.set("server.port", 8080).unwrap();
1340        config.set("path", "C:\\dir \"q\"").unwrap();
1341        let text = config.serialize().unwrap();
1342        let reloaded = Config::from_string(&text, Some("toml")).unwrap();
1343        assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1344
1345        config.set("nothing", Value::Null).unwrap();
1346        assert!(config.serialize().is_err(), "TOML has no null");
1347    }
1348
1349    #[cfg(feature = "noml")]
1350    #[test]
1351    fn modified_noml_serializes_current_values() {
1352        let source = "name = \"app\"\nlog = \"/var/log/${name}.log\"\n";
1353        let mut config = Config::from_string(source, Some("noml")).unwrap();
1354        assert_eq!(
1355            config.get("log").unwrap().as_string().unwrap(),
1356            "/var/log/app.log"
1357        );
1358
1359        config.set("template", "${not_a_reference}").unwrap();
1360        config.set("nothing", Value::Null).unwrap();
1361        let text = config.serialize().unwrap();
1362        let reloaded = Config::from_string(&text, Some("noml")).unwrap();
1363        assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1364    }
1365}