realme/
realme.rs

1//! This module contains the core `Realme` struct and its builder.
2
3pub mod api;
4pub mod builder;
5#[cfg(feature = "watch")]
6mod shared;
7#[cfg(feature = "watch")]
8use std::sync::{
9    Arc,
10    RwLock,
11};
12
13use serde::{
14    Deserialize,
15    Serialize,
16    de::DeserializeOwned,
17};
18
19use crate::{
20    Result,
21    prelude::*,
22};
23/// Represents a configuration realme with a cache for storing configuration
24/// values.
25#[derive(Deserialize, Clone)]
26pub struct Realme {
27    /// The cache storing configuration values.
28    cache:   Value,
29    /// The default configuration values.
30    #[serde(skip)]
31    default: Option<Value>,
32    /// The builder used to construct this Realme instance.
33    #[serde(skip)]
34    builder: RealmeBuilder,
35}
36
37/// Builder for constructing a `Realme` instance.
38#[derive(Default, Clone, Debug)]
39pub struct RealmeBuilder {
40    /// List of adaptors used to load configuration.
41    adaptors: Vec<Adaptor>,
42    /// Optional profile name for configuration.
43    profile:  Option<String>,
44}
45
46#[cfg(feature = "watch")]
47/// A thread-safe shared reference to a `Realme` instance.
48pub type SharedRealme = Arc<RwLock<Realme>>;
49
50impl std::fmt::Debug for Realme {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        write!(
53            f,
54            "Realme {{ cache: {:?}, default: {:?} }}",
55            self.cache, self.default
56        )
57    }
58}
59
60impl Realme {
61    /// Creates a new `RealmeBuilder` for constructing a `Realme`.
62    ///
63    /// # Returns
64    ///
65    /// Returns a `RealmeBuilder` which can be used to configure and build a
66    /// `Realme`.
67    ///
68    /// # Examples
69    ///
70    /// ```rust
71    /// use realme::Realme;
72    ///
73    /// let builder = Realme::builder();
74    /// ```
75    pub fn builder() -> RealmeBuilder {
76        RealmeBuilder::new()
77    }
78
79    /// Attempts to deserialize the realme's cache into a specified type.
80    ///
81    /// # Type Parameters
82    ///
83    /// * `T` - The type to which the cache should be deserialized. This type
84    ///   must implement `DeserializeOwned`.
85    ///
86    /// # Returns
87    ///
88    /// Returns a `Result<T, Error>` which is `Ok` containing the deserialized
89    /// type if successful, or an `Err` containing a `Error` if the
90    /// operation fails.
91    pub fn try_deserialize<T: DeserializeOwned>(&self) -> Result<T> {
92        self.cache.clone().try_deserialize()
93    }
94
95    /// Attempts to serialize a given object into a new `Realme` instance.
96    /// It is not recommended to use this method directly.
97    ///
98    /// # Arguments
99    ///
100    /// * `from` - A reference to the object to serialize.
101    ///
102    /// # Type Parameters
103    ///
104    /// * `T` - The type of the object to serialize. This type must implement
105    ///   `Serialize`.
106    ///
107    /// # Returns
108    ///
109    /// Returns a `Result<Self, Error>` which is `Ok` containing a new `Realme`
110    /// instance if successful, or an `Err` containing a `Error` if the
111    /// operation fails.
112    pub(crate) fn try_serialize<T: Serialize>(from: &T) -> Result<Self> {
113        let cache = Value::try_serialize(from)?;
114        Ok(Self {
115            cache:   cache.clone(),
116            default: Some(cache),
117            builder: RealmeBuilder::new(),
118        })
119    }
120
121    /// Reloads the Realme instance from its builder.
122    ///
123    /// This method rebuilds the Realme instance using the current builder
124    /// configuration, and merges any default values if they exist.
125    ///
126    /// # Returns
127    ///
128    /// Returns a `Result<(), Error>` which is `Ok(())` if the reload was
129    /// successful, or an `Err` containing a `Error` if the operation fails.
130    pub fn reload(&mut self) -> Result<()> {
131        let mut new_realme = self.builder.clone().build()?;
132        if let Some(default) = self.default.take() {
133            new_realme.cache.merge(&default);
134            new_realme.default = Some(default);
135        }
136        *self = new_realme;
137        Ok(())
138    }
139
140    // fn validate(&self) -> Result<()> {
141    //     self.cache.validate()
142    // }
143}