Skip to main content

datex_core/runtime/
config.rs

1use crate::{
2    network::com_hub::InterfacePriority,
3    prelude::*,
4    random::RandomState,
5    traits::datex_native_structural::DatexNativeStructural,
6    values::{core_values::endpoint::Endpoint, value::Value},
7};
8use datex_macros_internal::Datex;
9use indexmap::IndexMap;
10
11pub fn is_priority_none(v: &InterfacePriority) -> bool {
12    matches!(v, InterfacePriority::None)
13}
14
15#[derive(Datex, Debug, Clone, PartialEq, Eq)]
16#[datex(structural)]
17/// A generic interface configuration to setup a runtime interface.
18pub struct RuntimeConfigInterface {
19    #[datex(rename = "type")]
20    pub interface_type: String,
21    pub config: Value,
22    pub priority: InterfacePriority,
23}
24
25impl RuntimeConfigInterface {
26    pub fn new<T: DatexNativeStructural>(
27        interface_type: &str,
28        setup_data: T,
29    ) -> Result<RuntimeConfigInterface, String> {
30        Ok(RuntimeConfigInterface {
31            interface_type: interface_type.to_string(),
32            priority: InterfacePriority::default(),
33            config: Value::native(setup_data),
34        })
35    }
36
37    pub fn new_from_map(
38        interface_type: &str,
39        config: Value,
40    ) -> RuntimeConfigInterface {
41        RuntimeConfigInterface {
42            priority: InterfacePriority::default(),
43            interface_type: interface_type.to_string(),
44            config,
45        }
46    }
47}
48
49#[derive(Datex, Debug, Default, Clone, PartialEq, Eq)]
50#[datex(structural)]
51pub struct RuntimeConfig {
52    pub endpoint: Endpoint,
53    pub name: Option<String>,
54    pub interfaces: Option<Vec<RuntimeConfigInterface>>,
55    pub env: Option<IndexMap<String, String, RandomState>>,
56}
57
58impl RuntimeConfig {
59    pub fn new_with_endpoint(endpoint: Endpoint) -> Self {
60        RuntimeConfig {
61            endpoint,
62            name: None,
63            interfaces: None,
64            env: None,
65        }
66    }
67
68    pub fn add_interface<T: DatexNativeStructural>(
69        &mut self,
70        interface_type: String,
71        config: T,
72        priority: InterfacePriority,
73    ) {
74        let config = Value::native(config);
75        let interface = RuntimeConfigInterface {
76            interface_type,
77            config,
78            priority,
79        };
80        if let Some(interfaces) = &mut self.interfaces {
81            interfaces.push(interface);
82        } else {
83            self.interfaces = Some(vec![interface]);
84        }
85    }
86
87    /// Adds a single environment variable to the runtime's custom environment variables.
88    pub fn add_env_var(&mut self, key: String, value: String) {
89        self.env
90            .get_or_insert_with(IndexMap::default)
91            .insert(key, value);
92    }
93
94    /// Adds multiple environment variables to the runtime's custom environment variables.
95    pub fn add_env_vars(
96        &mut self,
97        vars: IndexMap<String, String, RandomState>,
98    ) {
99        self.env.get_or_insert_with(IndexMap::default).extend(vars);
100    }
101
102    #[cfg(feature = "target_native")]
103    /// Adds all host environment variables to the runtime's custom environment variables.
104    pub fn load_host_env_vars(&mut self) {
105        // add all host environment variables to the runtime's custom environment variables
106        for (key, value) in std::env::vars() {
107            self.env
108                .get_or_insert_with(IndexMap::new)
109                .insert(key, value);
110        }
111    }
112
113    #[cfg(feature = "target_native")]
114    /// Adds all environment variables from a .env file to the runtime's custom environment variables.
115    pub fn add_env_vars_from_file(
116        &mut self,
117        path: &std::path::PathBuf,
118    ) -> Result<(), dotenvy::Error> {
119        let loader1 = dotenvy::from_path_iter(path)?;
120        for item in loader1 {
121            let (key, val) = item?;
122            self.env.get_or_insert_with(IndexMap::new).insert(key, val);
123        }
124        Ok(())
125    }
126}
127
128#[cfg(test)]
129pub mod tests {
130    use crate::{
131        network::com_hub::InterfacePriority,
132        prelude::*,
133        runtime::{Runtime, RuntimeConfig, RuntimeConfigInterface},
134        traits::{
135            convert_value_container::ConvertValueContainer, try_clone::TryClone,
136        },
137        values::{
138            core_values::{endpoint::Endpoint, map::Map},
139            value::Value,
140            value_container::ValueContainer,
141        },
142    };
143    use datex_macros_internal::Datex;
144
145    #[derive(Datex, Clone)]
146    #[datex(structural)]
147    struct MySetupData {
148        field1: String,
149        field2: i32,
150    }
151
152    #[test]
153    fn add_env_var() {
154        let mut config = RuntimeConfig::default();
155        config.add_env_var("KEY1".to_string(), "VALUE1".to_string());
156        let env_vars = config.env.unwrap();
157        assert_eq!(env_vars.get("KEY1"), Some(&"VALUE1".to_string()));
158    }
159
160    #[test]
161    fn datex_proxy_runtime_config_interface() {
162        let config_interface = RuntimeConfigInterface::new(
163            "test",
164            MySetupData {
165                field1: "value".to_string(),
166                field2: 42,
167            },
168        )
169        .unwrap();
170
171        assert_eq!(config_interface.interface_type, "test");
172        let setup_data = config_interface.config.try_clone().unwrap();
173        let map: Map = setup_data.try_convert_into_value().unwrap();
174        assert_eq!(
175            map.try_get(&ValueContainer::from("field1"))
176                .unwrap()
177                .clone()
178                .try_into_value::<String>()
179                .unwrap(),
180            "value".to_string()
181        );
182        assert_eq!(
183            map.try_get(&ValueContainer::from("field2"))
184                .unwrap()
185                .clone()
186                .try_into_value::<i32>()
187                .unwrap(),
188            42
189        );
190
191        let value_container = Value::native(config_interface);
192        let parsed_config_interface: RuntimeConfigInterface =
193            value_container.try_into_value().unwrap();
194        assert_eq!(parsed_config_interface.interface_type, "test");
195    }
196
197    #[test]
198    fn datex_proxy_runtime_config() {
199        let config = RuntimeConfig::new_with_endpoint(Endpoint::new("@test"));
200        let value_container = Value::native(config);
201        let parsed_config: RuntimeConfig =
202            value_container.try_into_value().unwrap();
203        assert_eq!(parsed_config.endpoint, Endpoint::new("@test"));
204    }
205
206    #[test]
207    #[cfg(feature = "compiler")]
208    fn read_interface_priority_from_datex_source() {
209        let priority_source = "#Priority(5u16)";
210
211        let priority = InterfacePriority::try_from_script(
212            priority_source,
213            &Runtime::stub(),
214        );
215        assert_eq!(priority, Ok(InterfacePriority::Priority(5)));
216    }
217
218    #[test]
219    #[cfg(feature = "compiler")]
220    fn read_interface_configs_from_datex_source() {
221        let interface_config_source = r#"[
222            {
223                type: "websocket-client",
224                config: {url:"wss://example.unyt.land"},
225                priority: #Priority(0u16)
226            }
227        ]"#;
228
229        let config = <Vec<RuntimeConfigInterface>>::try_from_script(
230            interface_config_source,
231            &Runtime::stub(),
232        );
233
234        assert_eq!(
235            config,
236            Ok(vec![RuntimeConfigInterface {
237                interface_type: "websocket-client".to_string(),
238                config: Map::from(vec![(
239                    "url",
240                    "wss://example.unyt.land".into()
241                )])
242                .into(),
243                priority: InterfacePriority::Priority(0),
244            }])
245        );
246    }
247
248    #[test]
249    #[cfg(feature = "compiler")]
250    fn read_runtime_config_from_datex_source() {
251        let config_source = r#"{
252            endpoint: @test,
253            name: "Example",
254            interfaces: [
255                {
256                    type: "websocket-client",
257                    config: {url:"wss://example.unyt.land"},
258                    priority: #Priority(0u16)
259                }
260            ],
261            env: null
262        }"#;
263
264        let config =
265            RuntimeConfig::try_from_script(config_source, &Runtime::stub());
266
267        assert_eq!(
268            config,
269            Ok(RuntimeConfig {
270                endpoint: Endpoint::new("@test"),
271                name: Some("Example".to_string()),
272                interfaces: Some(vec![RuntimeConfigInterface {
273                    interface_type: "websocket-client".to_string(),
274                    config: Map::from(vec![(
275                        "url",
276                        "wss://example.unyt.land".into()
277                    )])
278                    .into(),
279                    priority: InterfacePriority::Priority(0),
280                }]),
281                env: None,
282            })
283        );
284    }
285}