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#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
13pub struct Config {
14 pub modules: Vec<Module>,
15}
16
17#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
22pub struct Module {
23 pub module: String,
24 pub config: toml::Value,
25}
26
27pub trait TryFromConfig {
32 type Error: std::error::Error + std::fmt::Display;
33
34 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}