Skip to main content

quokka_config/
lib.rs

1#[derive(Clone, Debug, thiserror::Error)]
2pub enum Error {
3    #[error("Unable to get config module {0:?}")]
4    ModuleNotFound(String),
5    #[error("Unable to build config struct from module {0:?}")]
6    ModuleStructNotMatching(String),
7}
8
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// The configuration file for all modules
12#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
13pub struct Config {
14    pub modules: Vec<Module>,
15}
16
17/// Defines how a module configuration should look like.
18/// The [Self::config] field might be converted to a state specific
19/// config within the [TryFromConfig] or [TryManyFromConfig] using
20/// the [toml::Value::try_into] function.
21#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
22pub struct Module {
23    pub module: String,
24    pub config: toml::Value,
25}
26
27/// Creates a state from a config module.
28/// This is for a single state, which is required to be built. For multiple states see [TryManyFromConfig].
29/// This does not disallow for defining the module multiple times. In such a case the first module that is
30/// sorted into the [Vec] of the config or the provided [Vec] will be the winner.
31pub trait TryFromConfig {
32    type Error: std::error::Error + std::fmt::Display;
33
34    /// Simplifies building from the root config struct
35    ///
36    /// # Return
37    ///
38    /// - The built module
39    ///
40    /// # Errors
41    ///
42    /// - Forwards for whatever reason the module could not be made
43    fn try_from_config(
44        config: &Config,
45    ) -> impl std::future::Future<Output = std::result::Result<Self, Self::Error>>
46    where
47        Self: Sized;
48}
49
50impl<T: TryFromConfig> TryFromConfig for Option<T> {
51    type Error = T::Error;
52
53    async fn try_from_config(config: &Config) -> std::result::Result<Self, Self::Error>
54    where
55        Self: Sized,
56    {
57        Ok(T::try_from_config(config).await.ok())
58    }
59}
60
61impl Module {
62    pub fn build_config<C: serde::de::DeserializeOwned>(&self) -> crate::Result<C> {
63        self.config
64            .clone()
65            .try_into()
66            .inspect_err(|error| {
67                tracing::error!(
68                    ?error,
69                    config = std::any::type_name::<C>(),
70                    "Unable to build config module"
71                )
72            })
73            .map_err(|_| Error::ModuleStructNotMatching(std::any::type_name::<C>().to_string()))
74    }
75}
76
77impl Config {
78    pub fn get_module<T: serde::de::DeserializeOwned>(&self, name: &str) -> Result<T> {
79        self.get_module_optional(name)?
80            .ok_or(Error::ModuleNotFound(name.to_string()))
81            .inspect_err(|error| {
82                tracing::error!(
83                    ?error,
84                    module = name,
85                    config = std::any::type_name::<T>(),
86                    "Unable to build config for module"
87                )
88            })
89    }
90    pub fn get_module_optional<T: serde::de::DeserializeOwned>(
91        &self,
92        name: &str,
93    ) -> Result<Option<T>> {
94        let Some(module) = self.modules.iter().find(|module| module.module.eq(name)) else {
95            return Ok(None);
96        };
97
98        module.build_config().map(Some)
99    }
100}