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