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, §ion_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 converted to `V`, or `default` when the path is missing
585 /// or the value does not convert.
586 ///
587 /// `V` can be `bool`, `String`, `f64`, any integer type from `i8`/`u8`
588 /// to `i64`/`u64`, `isize`, `usize`, or `Value` itself. Integer reads
589 /// are range-checked, so `70000` read as `u16` returns the default. See
590 /// the `TryFrom<Value>` impls on [`Value`] for the conversion rules.
591 ///
592 /// # Examples
593 ///
594 /// ```rust
595 /// use config_lib::Config;
596 ///
597 /// let config = Config::from_string(
598 /// r#"
599 /// [server]
600 /// port = 8080
601 /// host = "0.0.0.0"
602 /// "#,
603 /// Some("conf"),
604 /// )?;
605 ///
606 /// let port: u16 = config.get_or("server.port", 3000);
607 /// let host: String = config.get_or("server.host", "localhost".to_string());
608 /// let tls = config.get_or("server.tls", false); // missing, so the default
609 ///
610 /// assert_eq!(port, 8080);
611 /// assert_eq!(host, "0.0.0.0");
612 /// assert!(!tls);
613 /// # Ok::<(), config_lib::Error>(())
614 /// ```
615 pub fn get_or<V>(&self, path: &str, default: V) -> V
616 where
617 V: TryFrom<Value> + Clone,
618 V::Error: std::fmt::Debug,
619 {
620 self.get(path)
621 .and_then(|v| V::try_from(v.clone()).ok())
622 .unwrap_or(default)
623 }
624
625 // --- VALIDATION SUPPORT ---
626
627 /// Set validation rules for this configuration
628 #[cfg(feature = "validation")]
629 pub fn set_validation_rules(&mut self, rules: ValidationRuleSet) {
630 self.validation_rules = Some(rules);
631 }
632
633 /// Validate the current configuration against all registered rules
634 #[cfg(feature = "validation")]
635 pub fn validate(&mut self) -> Result<Vec<ValidationError>> {
636 match &mut self.validation_rules {
637 Some(rules) => {
638 if let Value::Table(table) = &self.values {
639 let mut errors = Vec::new();
640
641 // Validate each key-value pair
642 for (key, value) in table {
643 errors.extend(rules.validate(key, value));
644 }
645
646 // Also validate for required keys (if any RequiredKeyValidator exists)
647 // This is handled by individual rule implementations
648
649 Ok(errors)
650 } else {
651 Err(Error::validation(
652 "Configuration root must be a table for validation",
653 ))
654 }
655 }
656 None => Ok(Vec::new()), // No rules = no errors
657 }
658 }
659
660 /// Validate and return only critical errors
661 #[cfg(feature = "validation")]
662 pub fn validate_critical_only(&mut self) -> Result<Vec<ValidationError>> {
663 let all_errors = self.validate()?;
664 Ok(all_errors
665 .into_iter()
666 .filter(|e| e.severity == crate::validation::ValidationSeverity::Critical)
667 .collect())
668 }
669
670 /// Check if configuration is valid (has no critical errors)
671 #[cfg(feature = "validation")]
672 pub fn is_valid(&mut self) -> Result<bool> {
673 let critical_errors = self.validate_critical_only()?;
674 Ok(critical_errors.is_empty())
675 }
676
677 /// Validate a specific value at a path
678 #[cfg(feature = "validation")]
679 pub fn validate_path(&mut self, path: &str) -> Result<Vec<ValidationError>> {
680 // Get the value first to avoid borrowing conflicts, clone to own it
681 let value = self
682 .get(path)
683 .ok_or_else(|| Error::key_not_found(path))?
684 .clone();
685
686 match &mut self.validation_rules {
687 Some(rules) => Ok(rules.validate(path, &value)),
688 None => Ok(Vec::new()),
689 }
690 }
691}
692
693impl Default for Config {
694 fn default() -> Self {
695 Self::new()
696 }
697}
698
699// =========================================================================
700// ConfigOptions — opt-out behavior knobs (foundation for v0.9.5)
701// =========================================================================
702
703/// Opt-out behavior knobs for [`Config`].
704///
705/// `ConfigOptions` carries the small set of toggles that should not be
706/// enabled by default: making a `Config` read-only, sizing the cache,
707/// and so on. The struct is `#[non_exhaustive]` so v0.9.x can add new
708/// knobs without breaking SemVer. Users construct it via
709/// [`ConfigOptions::new`] or [`ConfigOptions::default`] and apply
710/// individual toggles through the consuming builder methods.
711///
712/// The field set lays the groundwork for the lock-free caching work
713/// landing in v0.9.5. In v0.9.4 the only knob that has runtime effect
714/// is [`ConfigOptions::read_only`]; the cache-related knobs are
715/// accepted today so that the public API surface does not change
716/// again when v0.9.5 switches the cache on.
717///
718/// # Examples
719///
720/// ```rust
721/// use config_lib::{Config, ConfigOptions};
722///
723/// // Default options — caching on, writes allowed.
724/// let _cfg = Config::with_options(ConfigOptions::default());
725///
726/// // Read-only configuration for a hot path that must never be mutated.
727/// let opts = ConfigOptions::new().read_only(true);
728/// let _cfg = Config::with_options(opts);
729/// ```
730#[derive(Debug, Clone)]
731#[non_exhaustive]
732pub struct ConfigOptions {
733 /// Reject every `set` / `remove` / `merge` call with
734 /// [`Error::general`] instead of mutating. Useful for once-loaded
735 /// configurations that must never change at runtime.
736 pub read_only: bool,
737
738 /// Whether the internal caching layer is active. **Reserved** — the
739 /// caching layer ships in v0.9.5; in v0.9.4 this field is accepted
740 /// for forward compatibility but does not yet change runtime
741 /// behavior (every `get` already hits an in-memory `Value`).
742 pub cache_enabled: bool,
743
744 /// Maximum number of resolved-key entries the cache will hold
745 /// before evicting. **Reserved for v0.9.5.**
746 pub cache_capacity: usize,
747}
748
749impl Default for ConfigOptions {
750 /// The canonical options for the Hive DB use case:
751 /// caching enabled, writes allowed, capacity tuned for typical
752 /// server config size.
753 fn default() -> Self {
754 Self {
755 read_only: false,
756 cache_enabled: true,
757 cache_capacity: 1024,
758 }
759 }
760}
761
762impl ConfigOptions {
763 /// Construct a `ConfigOptions` with default values
764 /// ([`ConfigOptions::default`]).
765 pub fn new() -> Self {
766 Self::default()
767 }
768
769 /// Set the read-only flag. See [`ConfigOptions::read_only`].
770 pub fn read_only(mut self, read_only: bool) -> Self {
771 self.read_only = read_only;
772 self
773 }
774
775 /// Toggle the caching layer. **Reserved for v0.9.5** — currently
776 /// a no-op at runtime; the setter exists so call-sites compile
777 /// against the same shape they will use after the cache lands.
778 pub fn cache_enabled(mut self, cache_enabled: bool) -> Self {
779 self.cache_enabled = cache_enabled;
780 self
781 }
782
783 /// Set the cache capacity. **Reserved for v0.9.5** — see
784 /// [`ConfigOptions::cache_enabled`].
785 pub fn cache_capacity(mut self, cache_capacity: usize) -> Self {
786 self.cache_capacity = cache_capacity;
787 self
788 }
789}
790
791impl Config {
792 /// Construct a new empty [`Config`] with the supplied
793 /// [`ConfigOptions`].
794 ///
795 /// This is the explicit opt-out constructor. For the canonical
796 /// defaults (caching on, writes allowed), prefer [`Config::new`].
797 pub fn with_options(options: ConfigOptions) -> Self {
798 let mut config = Self::new();
799 config.options = options;
800 config
801 }
802
803 /// Return the [`ConfigOptions`] currently in effect on this config.
804 pub fn options(&self) -> &ConfigOptions {
805 &self.options
806 }
807
808 /// Returns `true` if this configuration was constructed read-only
809 /// (see [`ConfigOptions::read_only`]).
810 pub fn is_read_only(&self) -> bool {
811 self.options.read_only
812 }
813
814 /// Helper used by mutating methods to short-circuit when the
815 /// configuration is in read-only mode.
816 fn ensure_writable(&self) -> Result<()> {
817 if self.options.read_only {
818 Err(Error::general("Configuration is read-only"))
819 } else {
820 Ok(())
821 }
822 }
823
824 /// Return a snapshot of the cache-hit / cache-miss counters.
825 ///
826 /// Counters are loaded with `Ordering::Relaxed` — the values are
827 /// statistics, not synchronisation primitives, and the hit/miss
828 /// classification is best-effort under concurrent reads.
829 pub fn cache_stats(&self) -> CacheStats {
830 let hits = self.cache_hits.load(Ordering::Relaxed);
831 let misses = self.cache_misses.load(Ordering::Relaxed);
832 let total = hits.saturating_add(misses);
833 let hit_ratio = if total == 0 {
834 0.0
835 } else {
836 hits as f64 / total as f64
837 };
838 CacheStats {
839 hits,
840 misses,
841 hit_ratio,
842 }
843 }
844
845 /// Resolve a dotted path to a cached `Arc<Value>`.
846 ///
847 /// `get_arc` is the cache-backed thread-safe accessor introduced
848 /// in v0.9.9. The first lookup of a given path walks the value
849 /// tree, allocates an `Arc<Value>` containing a clone of the
850 /// resolved node, and inserts it into the resolved-path cache.
851 /// Subsequent lookups of the same path hit the cache and return
852 /// a cheap refcount-bump clone of the `Arc<Value>`.
853 ///
854 /// This is the recommended accessor for:
855 ///
856 /// - **Multi-threaded reads.** `Arc<Value>` is `Send + Sync` and
857 /// independent of `&self`'s lifetime, so the value can be
858 /// handed off to other threads.
859 /// - **Hot loops.** Cache hits avoid the tree walk; the
860 /// refcount bump is a single relaxed atomic.
861 ///
862 /// The existing `Config::get(&self, path) -> Option<&Value>` is
863 /// still the right choice for single-threaded reads that just
864 /// peek and drop the borrow — no clone, no Arc bump.
865 ///
866 /// The cache is invalidated wholesale on any `set` / `remove` /
867 /// `merge`. The runtime knob [`ConfigOptions::cache_enabled`]
868 /// (default `true`) toggles the cache layer; with it disabled,
869 /// every `get_arc` call walks the tree and allocates a fresh
870 /// `Arc<Value>`.
871 pub fn get_arc(&self, path: &str) -> Option<Arc<Value>> {
872 if self.options.cache_enabled {
873 if let Some(entry) = self.cache.get(path) {
874 self.cache_hits.fetch_add(1, Ordering::Relaxed);
875 return Some(Arc::clone(entry.value()));
876 }
877 self.cache_misses.fetch_add(1, Ordering::Relaxed);
878 let resolved = self.values.get(path)?.clone();
879 let arc = Arc::new(resolved);
880 self.cache.insert(path.into(), Arc::clone(&arc));
881 Some(arc)
882 } else {
883 self.cache_misses.fetch_add(1, Ordering::Relaxed);
884 Some(Arc::new(self.values.get(path)?.clone()))
885 }
886 }
887
888 /// Clear the resolved-path cache.
889 ///
890 /// Idempotent; safe to call from any thread. Useful when an
891 /// out-of-band actor (e.g. a hot-reload watcher) has changed
892 /// the underlying value tree and the cache snapshot is now stale.
893 pub fn clear_cache(&self) {
894 self.cache.clear();
895 }
896
897 /// Set a default value for the given path.
898 ///
899 /// Defaults are an operator-supplied fallback table consulted by
900 /// [`Config::get_or_default`] when the requested path is missing
901 /// from the main value tree. Defaults are independent of the
902 /// `read_only` flag — a read-only configuration can still have
903 /// its defaults table populated (defaults are deployment-time
904 /// declarations, not user-supplied data).
905 ///
906 /// Calls to `set_default` do **not** invalidate the cache; the
907 /// cache is keyed on observed value-tree resolutions, not on
908 /// defaults-table membership.
909 ///
910 /// # Errors
911 ///
912 /// Returns an error if the defaults-table lock has been poisoned.
913 pub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()> {
914 let mut defaults = self
915 .defaults
916 .write()
917 .map_err(|_| Error::concurrency("defaults table lock poisoned"))?;
918 defaults.insert(path.to_string(), value.into());
919 Ok(())
920 }
921
922 /// Resolve a path against the main value tree, falling back to the
923 /// defaults table when not found.
924 ///
925 /// Returns `None` only when neither the value tree nor the defaults
926 /// table contains an entry for `path`. The return type is owned
927 /// (`Option<Value>`) because the defaults table sits behind an
928 /// `Arc<RwLock<_>>` and producing a borrowed reference would
929 /// require holding the lock guard across the caller's use.
930 pub fn get_or_default(&self, path: &str) -> Option<Value> {
931 if let Some(v) = self.values.get(path) {
932 return Some(v.clone());
933 }
934 let defaults = self.defaults.read().ok()?;
935 defaults.get(path).cloned()
936 }
937
938 /// Toggle this configuration into read-only mode at runtime.
939 ///
940 /// Equivalent to constructing with
941 /// `ConfigOptions::new().read_only(true)` but available as a
942 /// post-construction switch. Subsequent calls to `set` / `remove`
943 /// / `merge` return `Err(Error::general("Configuration is
944 /// read-only"))`.
945 ///
946 /// The toggle is **one-way** by design — there is no
947 /// `make_writable()` companion. A configuration that has been
948 /// declared immutable should not become mutable again; if you
949 /// need that flexibility, keep two `Config` handles instead.
950 pub fn make_read_only(&mut self) {
951 self.options.read_only = true;
952 }
953}
954
955// =========================================================================
956// CacheStats — read-only snapshot of cache performance counters
957// =========================================================================
958
959/// Snapshot of a [`Config`]'s cache-hit / cache-miss counters.
960///
961/// Returned by [`Config::cache_stats`]. The struct is `#[non_exhaustive]`
962/// so the v1.x SemVer contract can add new counter fields (e.g.
963/// `evictions`, `insertions`, per-shard breakdowns) in MINOR releases
964/// without breaking user code.
965///
966/// # Stability note for v0.9.5
967///
968/// In v0.9.5 every `CacheStats` returned by [`Config::cache_stats`]
969/// has `hits = 0`, `misses = 0`, `hit_ratio = 0.0`. The lock-free
970/// cache layer that populates these counters lands in a follow-up
971/// v0.9.5 implementation release. The struct is shipping now so the
972/// API surface is locked in ahead of the implementation.
973///
974/// # Examples
975///
976/// ```rust
977/// use config_lib::Config;
978///
979/// let cfg = Config::new();
980/// let stats = cfg.cache_stats();
981/// assert_eq!(stats.hits, 0);
982/// assert_eq!(stats.misses, 0);
983/// assert_eq!(stats.hit_ratio, 0.0);
984/// ```
985#[derive(Debug, Clone, Copy)]
986#[non_exhaustive]
987pub struct CacheStats {
988 /// Number of cache lookups that resolved to a cached value.
989 pub hits: u64,
990 /// Number of cache lookups that did not find a cached value and
991 /// fell through to the canonical storage.
992 pub misses: u64,
993 /// `hits / (hits + misses)` as an f64 in `[0.0, 1.0]`. Returns
994 /// `0.0` when no lookups have happened yet.
995 pub hit_ratio: f64,
996}
997
998/// Ergonomic wrapper for accessing configuration values
999pub struct ConfigValue<'a> {
1000 value: Option<&'a Value>,
1001}
1002
1003impl<'a> ConfigValue<'a> {
1004 fn new(value: Option<&'a Value>) -> Self {
1005 Self { value }
1006 }
1007
1008 /// Get as string with default fallback
1009 pub fn as_string(&self) -> Result<String> {
1010 match self.value {
1011 Some(v) => v.as_string().map(|s| s.to_string()),
1012 None => Err(Error::key_not_found("value not found")),
1013 }
1014 }
1015
1016 /// Get as string with custom default
1017 pub fn as_string_or(&self, default: &str) -> String {
1018 self.value
1019 .and_then(|v| v.as_string().ok())
1020 .map(|s| s.to_string())
1021 .unwrap_or_else(|| default.to_string())
1022 }
1023
1024 /// Get as integer with default fallback
1025 pub fn as_integer(&self) -> Result<i64> {
1026 match self.value {
1027 Some(v) => v.as_integer(),
1028 None => Err(Error::key_not_found("value not found")),
1029 }
1030 }
1031
1032 /// Get as integer with custom default
1033 pub fn as_integer_or(&self, default: i64) -> i64 {
1034 self.value
1035 .and_then(|v| v.as_integer().ok())
1036 .unwrap_or(default)
1037 }
1038
1039 /// Get as boolean with default fallback
1040 pub fn as_bool(&self) -> Result<bool> {
1041 match self.value {
1042 Some(v) => v.as_bool(),
1043 None => Err(Error::key_not_found("value not found")),
1044 }
1045 }
1046
1047 /// Get as boolean with custom default
1048 pub fn as_bool_or(&self, default: bool) -> bool {
1049 self.value.and_then(|v| v.as_bool().ok()).unwrap_or(default)
1050 }
1051
1052 /// Check if the value exists
1053 pub fn exists(&self) -> bool {
1054 self.value.is_some()
1055 }
1056
1057 /// Get the underlying Value reference if it exists
1058 pub fn value(&self) -> Option<&'a Value> {
1059 self.value
1060 }
1061}
1062
1063/// Builder pattern for Config creation
1064pub struct ConfigBuilder {
1065 format: Option<String>,
1066 #[cfg(feature = "validation")]
1067 validation_rules: Option<ValidationRuleSet>,
1068}
1069
1070impl ConfigBuilder {
1071 /// Create a new ConfigBuilder
1072 pub fn new() -> Self {
1073 Self {
1074 format: None,
1075 #[cfg(feature = "validation")]
1076 validation_rules: None,
1077 }
1078 }
1079
1080 /// Set the configuration format
1081 pub fn format<S: Into<String>>(mut self, format: S) -> Self {
1082 self.format = Some(format.into());
1083 self
1084 }
1085
1086 /// Set validation rules
1087 #[cfg(feature = "validation")]
1088 pub fn validation_rules(mut self, rules: ValidationRuleSet) -> Self {
1089 self.validation_rules = Some(rules);
1090 self
1091 }
1092
1093 /// Build Config from string
1094 pub fn from_string(self, source: &str) -> Result<Config> {
1095 #[cfg(feature = "validation")]
1096 let mut config = Config::from_string(source, self.format.as_deref())?;
1097 #[cfg(not(feature = "validation"))]
1098 let config = Config::from_string(source, self.format.as_deref())?;
1099
1100 #[cfg(feature = "validation")]
1101 if let Some(rules) = self.validation_rules {
1102 config.set_validation_rules(rules);
1103 }
1104
1105 Ok(config)
1106 }
1107
1108 /// Build Config from file
1109 pub fn from_file<P: AsRef<Path>>(self, path: P) -> Result<Config> {
1110 #[cfg(feature = "validation")]
1111 let mut config = Config::from_file(path)?;
1112 #[cfg(not(feature = "validation"))]
1113 let config = Config::from_file(path)?;
1114
1115 #[cfg(feature = "validation")]
1116 if let Some(rules) = self.validation_rules {
1117 config.set_validation_rules(rules);
1118 }
1119
1120 Ok(config)
1121 }
1122}
1123
1124impl Default for ConfigBuilder {
1125 fn default() -> Self {
1126 Self::new()
1127 }
1128}
1129
1130/// Convert Value to Config
1131impl From<Value> for Config {
1132 fn from(value: Value) -> Self {
1133 Self {
1134 values: value,
1135 file_path: None,
1136 format: "conf".to_string(),
1137 modified: false,
1138 options: ConfigOptions::default(),
1139 cache_hits: AtomicU64::new(0),
1140 cache_misses: AtomicU64::new(0),
1141 cache: DashMap::new(),
1142 defaults: Arc::new(RwLock::new(BTreeMap::new())),
1143 #[cfg(feature = "noml")]
1144 noml_document: None,
1145 #[cfg(feature = "validation")]
1146 validation_rules: None,
1147 }
1148 }
1149}
1150
1151/// TOML text output for TOML and modified NOML configurations
1152#[cfg(any(feature = "toml", feature = "noml"))]
1153mod toml_writer {
1154 use crate::error::{Error, Result};
1155 use crate::value::Value;
1156 use std::collections::BTreeMap;
1157 use std::fmt::Write;
1158
1159 fn is_table_array(value: &Value) -> bool {
1160 matches!(value, Value::Array(items)
1161 if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Table(_))))
1162 }
1163
1164 /// Write plain keys first, then `[table]` and `[[array]]` sections
1165 pub(super) fn write_table(
1166 out: &mut String,
1167 table: &BTreeMap<String, Value>,
1168 path: &mut Vec<String>,
1169 noml: bool,
1170 ) -> Result<()> {
1171 for (key, value) in table {
1172 if !matches!(value, Value::Table(_)) && !is_table_array(value) {
1173 write_key(out, key);
1174 out.push_str(" = ");
1175 write_value(out, value, path, key, noml)?;
1176 out.push('\n');
1177 }
1178 }
1179 for (key, value) in table {
1180 path.push(key.clone());
1181 match value {
1182 Value::Table(inner) => {
1183 header(out, path, false);
1184 write_table(out, inner, path, noml)?;
1185 }
1186 Value::Array(items) if is_table_array(value) => {
1187 for item in items {
1188 header(out, path, true);
1189 if let Value::Table(inner) = item {
1190 write_table(out, inner, path, noml)?;
1191 }
1192 }
1193 }
1194 _ => {}
1195 }
1196 path.pop();
1197 }
1198 Ok(())
1199 }
1200
1201 fn header(out: &mut String, path: &[String], array: bool) {
1202 if !out.is_empty() {
1203 out.push('\n');
1204 }
1205 out.push_str(if array { "[[" } else { "[" });
1206 for (i, key) in path.iter().enumerate() {
1207 if i > 0 {
1208 out.push('.');
1209 }
1210 write_key(out, key);
1211 }
1212 out.push_str(if array { "]]\n" } else { "]\n" });
1213 }
1214
1215 fn write_key(out: &mut String, key: &str) {
1216 let bare = key.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
1217 && key
1218 .bytes()
1219 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
1220 if bare {
1221 out.push_str(key);
1222 } else {
1223 write_string(out, key, false);
1224 }
1225 }
1226
1227 fn write_string(out: &mut String, s: &str, noml: bool) {
1228 out.push('"');
1229 let mut chars = s.chars().peekable();
1230 while let Some(c) = chars.next() {
1231 match c {
1232 '"' => out.push_str("\\\""),
1233 '\\' => out.push_str("\\\\"),
1234 '\n' => out.push_str("\\n"),
1235 '\t' => out.push_str("\\t"),
1236 '\r' => out.push_str("\\r"),
1237 '$' if noml && chars.peek() == Some(&'{') => out.push_str("$$"),
1238 c if c.is_control() => {
1239 let _ = write!(out, "\\u{:04X}", c as u32);
1240 }
1241 c => out.push(c),
1242 }
1243 }
1244 out.push('"');
1245 }
1246
1247 fn write_value(
1248 out: &mut String,
1249 value: &Value,
1250 path: &[String],
1251 key: &str,
1252 noml: bool,
1253 ) -> Result<()> {
1254 match value {
1255 Value::Null if noml => out.push_str("null"),
1256 Value::Null => {
1257 let mut full = path.join(".");
1258 if !full.is_empty() {
1259 full.push('.');
1260 }
1261 full.push_str(key);
1262 return Err(Error::serialize(format!(
1263 "TOML has no null value; cannot write '{full}'"
1264 )));
1265 }
1266 Value::Bool(b) => {
1267 let _ = write!(out, "{b}");
1268 }
1269 Value::Integer(i) => {
1270 let _ = write!(out, "{i}");
1271 }
1272 Value::Float(f) => {
1273 if f.is_nan() {
1274 out.push_str("nan");
1275 } else if f.is_infinite() {
1276 out.push_str(if *f > 0.0 { "inf" } else { "-inf" });
1277 } else {
1278 // Debug always keeps a '.' or exponent, so it reads back as a float
1279 let _ = write!(out, "{f:?}");
1280 }
1281 }
1282 Value::String(s) => write_string(out, s, noml),
1283 Value::Array(items) => {
1284 out.push('[');
1285 for (i, item) in items.iter().enumerate() {
1286 if i > 0 {
1287 out.push_str(", ");
1288 }
1289 write_value(out, item, path, key, noml)?;
1290 }
1291 out.push(']');
1292 }
1293 Value::Table(table) => {
1294 out.push('{');
1295 for (i, (k, v)) in table.iter().enumerate() {
1296 out.push_str(if i > 0 { ", " } else { " " });
1297 write_key(out, k);
1298 out.push_str(" = ");
1299 write_value(out, v, path, key, noml)?;
1300 }
1301 out.push_str(if table.is_empty() { "}" } else { " }" });
1302 }
1303 #[cfg(feature = "chrono")]
1304 Value::DateTime(dt) => write_string(out, &dt.to_rfc3339(), noml),
1305 }
1306 Ok(())
1307 }
1308}
1309
1310#[cfg(test)]
1311mod tests {
1312 use super::*;
1313
1314 #[test]
1315 fn test_config_creation() {
1316 let config = Config::new();
1317 assert!(!config.is_modified());
1318 assert_eq!(config.format(), "conf");
1319 }
1320
1321 #[test]
1322 fn test_config_from_string() {
1323 let config = Config::from_string("key = value\nport = 8080", Some("conf")).unwrap();
1324
1325 assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
1326 assert_eq!(config.get("port").unwrap().as_integer().unwrap(), 8080);
1327 }
1328
1329 #[test]
1330 fn test_config_modification() {
1331 let mut config = Config::new();
1332 assert!(!config.is_modified());
1333
1334 config.set("key", "value").unwrap();
1335 assert!(config.is_modified());
1336
1337 config.mark_clean();
1338 assert!(!config.is_modified());
1339 }
1340
1341 #[test]
1342 fn test_config_merge() {
1343 let mut config1 = Config::new();
1344 config1.set("a", 1).unwrap();
1345 config1.set("b.x", 2).unwrap();
1346
1347 let mut config2 = Config::new();
1348 config2.set("b.y", 3).unwrap();
1349 config2.set("c", 4).unwrap();
1350
1351 config1.merge(&config2).unwrap();
1352
1353 assert_eq!(config1.get("a").unwrap().as_integer().unwrap(), 1);
1354 assert_eq!(config1.get("b.x").unwrap().as_integer().unwrap(), 2);
1355 assert_eq!(config1.get("b.y").unwrap().as_integer().unwrap(), 3);
1356 assert_eq!(config1.get("c").unwrap().as_integer().unwrap(), 4);
1357 }
1358
1359 #[cfg(feature = "toml")]
1360 #[test]
1361 fn modified_toml_serializes_current_values() {
1362 let source = "# comment\nname = \"app\"\n\n[server]\nport = 80\n";
1363 let mut config = Config::from_string(source, Some("toml")).unwrap();
1364
1365 // Unchanged: the original text is kept when the document is preserved
1366 #[cfg(feature = "noml")]
1367 assert_eq!(config.serialize().unwrap(), source);
1368
1369 config.set("server.port", 8080).unwrap();
1370 config.set("path", "C:\\dir \"q\"").unwrap();
1371 let text = config.serialize().unwrap();
1372 let reloaded = Config::from_string(&text, Some("toml")).unwrap();
1373 assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1374
1375 config.set("nothing", Value::Null).unwrap();
1376 assert!(config.serialize().is_err(), "TOML has no null");
1377 }
1378
1379 #[cfg(feature = "noml")]
1380 #[test]
1381 fn modified_noml_serializes_current_values() {
1382 let source = "name = \"app\"\nlog = \"/var/log/${name}.log\"\n";
1383 let mut config = Config::from_string(source, Some("noml")).unwrap();
1384 assert_eq!(
1385 config.get("log").unwrap().as_string().unwrap(),
1386 "/var/log/app.log"
1387 );
1388
1389 config.set("template", "${not_a_reference}").unwrap();
1390 config.set("nothing", Value::Null).unwrap();
1391 let text = config.serialize().unwrap();
1392 let reloaded = Config::from_string(&text, Some("noml")).unwrap();
1393 assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1394 }
1395}