summaryrefslogtreecommitdiffstats
path: root/crates/core/tedge_api/src/config.rs
blob: 4676dd1ba02d875c7a35300af3e9a9703e0f5ec6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::collections::HashMap;

use serde::Serialize;

/// Generic config that represents what kind of config a plugin wishes to accept
#[derive(Debug, Serialize, PartialEq)]
pub struct ConfigDescription {
    name: String,
    kind: ConfigKind,
    doc: Option<&'static str>,
}

impl ConfigDescription {
    /// Construct a new generic config explanation
    #[must_use]
    pub fn new(name: String, kind: ConfigKind, doc: Option<&'static str>) -> Self {
        Self { name, kind, doc }
    }

    /// Get a reference to the config's documentation.
    #[must_use]
    pub fn doc(&self) -> Option<&'static str> {
        self.doc
    }

    /// Get a reference to the config's kind.
    #[must_use]
    pub fn kind(&self) -> &ConfigKind {
        &self.kind
    }

    /// Set or replace the documentation of this [`ConfigDescription`]
    #[must_use]
    pub fn with_doc(mut self, doc: Option<&'static str>) -> Self {
        self.doc = doc;
        self
    }

    /// Get the config's name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// How an enum is represented
#[derive(Debug, Serialize, PartialEq)]
pub enum EnumVariantRepresentation {
    /// The enum is represented by a string
    ///
    /// This is the case with unit variants for example
    String(&'static str),
    /// The enum is represented by the value presented here
    Wrapped(Box<ConfigDescription>),
}

/// The kind of enum tagging used by the [`ConfigKind`]
#[derive(Debug, Serialize, PartialEq)]
pub enum ConfigEnumKind {
    /// An internal tag with the given tag name
    Tagged(&'static str),
    /// An untagged enum variant
    Untagged,
}

/// The specific kind a [`ConfigDescription`] represents
#[derive(Debug, Serialize, PartialEq)]
pub enum ConfigKind {
    /// Config represents a boolean `true`/`false`
    Bool,

    /// Config represents an integer `1, 10, 200, 10_000, ...`
    ///
    /// # Note
    ///
    /// The maximum value that can be represented is between [`i64::MIN`] and [`i64::MAX`]
    Integer,

    /// Config represents a floating point value `1.0, 20.235, 3.1419`
    ///
    /// # Note
    /// Integers are also accepted and converted to their floating point variant
    ///
    /// The maximum value that can be represented is between [`f64::MIN`] and [`f64::MAX`]
    Float,

    /// Config represents a string
    String,

    /// Wrap another config
    ///
    /// This is particularly useful if you want to restrict another kind. The common example is a
    /// `Port` config object which is represented as a `u16` but with an explanation of what it is
    /// meant to represent.
    Wrapped(Box<ConfigDescription>),

    /// Config represents an array of values of the given [`ConfigKind`]
    Array(Box<ConfigDescription>),

    /// Config represents a hashmap of named configurations of the same type
    ///
    /// # Note
    ///
    /// The key is always a [`String`] so this only holds the value config
    HashMap(Box<ConfigDescription>),

    /// Config represents a map of different configurations
    ///
    /// The tuple represent `(field_name, documentation, config_description)`
    Struct(Vec<(&'static str, Option<&'static str>, ConfigDescription)>),

    /// Config represents multiple choice of configurations
    Enum(
        ConfigEnumKind,
        Vec<(
            &'static str,
            Option<&'static str>,
            EnumVariantRepresentation,
        )>,
    ),
}

/// Turn a plugin configuration into a [`ConfigDescription`] object
///
/// Plugin authors are expected to implement this for their configurations to give users
pub trait AsConfig {
    /// Get a [`ConfigDescription`] object from the type
    fn as_config() -> ConfigDescription;
}

impl<T: AsConfig> AsConfig for Option<T> {
    fn as_config() -> ConfigDescription {
        ConfigDescription::new(
            format!("An optional '{}'", T::as_config().name()),
            ConfigKind::Wrapped(Box::new(T::as_config())),
            None,
        )
    }
}

impl<T: AsConfig> AsConfig for Vec<T> {
    fn as_config() -> ConfigDescription {
        ConfigDescription::new(
            format!("Array of '{}'s", T::as_config().name()),
            ConfigKind::Array(Box::new(T::as_config())),
            None,
        )
    }
}

impl<V: AsConfig> AsConfig for HashMap<String, V> {
    fn as_config() -> ConfigDescription {
        ConfigDescription::new(
            format!("Table of '{}'s", V::as_config().name()),
            ConfigKind::HashMap(Box::new(V::as_config())),
            None,
        )
    }
}

impl<V: AsConfig> AsConfig for HashMap<std::path::PathBuf, V> {
    fn as_config() -> ConfigDescription {
        ConfigDescription::new(
            format!("Table of '{}'s", V::as_config().name()),
            ConfigKind::HashMap(Box::new(V::as_config())),
            None,
        )
    }
}

macro_rules! impl_config_kind {
    ($kind:expr; $name:expr; $doc:expr => $($typ:ty),+) => {
        $(
            impl AsConfig for $typ {
                fn as_config() -> ConfigDescription {
                    ConfigDescription::new({$name}.into(), $kind, Some($doc))
                }
            }
        )+
    };
}

impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 64 bits" => i64);
impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 64 bits that cannot be zero" => std::num::NonZeroI64);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 64 bits" => u64);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 64 bits that cannot be zero" => std::num::NonZeroU64);

impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 32 bits" => i32);
impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 32 bits that cannot be zero" => std::num::NonZeroI32);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 32 bits" => u32);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 32 bits that cannot be zero" => std::num::NonZeroU32);

impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 16 bits" => i16);
impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 16 bits that cannot be zero" => std::num::NonZeroI16);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 16 bits" => u16);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 16 bits that cannot be zero" => std::num::NonZeroU16);

impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 8 bits" => i8);
impl_config_kind!(ConfigKind::Integer; "Integer"; "A signed integer with 8 bits that cannot be zero" => std::num::NonZeroI8);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 8 bits" => u8);
impl_config_kind!(ConfigKind::Integer; "Integer"; "An unsigned integer with 8 bits that cannot be zero" => std::num::NonZeroU8);

impl_config_kind!(ConfigKind::Float; "Float"; "A floating point value with 64 bits" => f64);
impl_config_kind!(ConfigKind::Float; "Float"; "A floating point value with 32 bits" => f32);

impl_config_kind!(ConfigKind::Bool; "Boolean"; "A boolean" => bool);
impl_config_kind!(ConfigKind::String; "String"; "An UTF-8 string" => String);

impl_config_kind!(ConfigKind::String; "String"; "A socket address" => std::net::SocketAddr);
impl_config_kind!(ConfigKind::String; "String"; "An IPv4 socket address" => std::net::SocketAddrV4);
impl_config_kind!(ConfigKind::String; "String"; "An IPv6 socket address" => std::net::SocketAddrV6);
impl_config_kind!(ConfigKind::String; "String"; "A Path" => std::path::PathBuf);

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use crate::config::{AsConfig, ConfigDescription, ConfigKind};

    #[test]
    fn verify_correct_config_kinds() {
        assert!(matches!(
            Vec::<f64>::as_config(),
            ConfigDescription {
                doc: None,
                kind: ConfigKind::Array(x),
                ..
            } if matches!(x.kind(), ConfigKind::Float)
        ));

        let complex_config = HashMap::<String, Vec<HashMap<String, String>>>::as_config();
        println!("Complex config: {:#?}", complex_config);

        assert!(
            matches!(complex_config.kind(), ConfigKind::HashMap(map) if matches!(map.kind(), ConfigKind::Array(arr) if matches!(arr.kind(), ConfigKind::HashMap(inner_map) if matches!(inner_map.kind(), ConfigKind::String))))
        );
    }
}