Skip to main content

datex_core/network/com_hub/
metadata.rs

1use log::info;
2
3use crate::{
4    collections::HashMap,
5    network::{
6        com_hub::{
7            ComHub, managers::socket_manager::DynamicEndpointProperties,
8        },
9        com_interfaces::com_interface::ComInterfaceUUID,
10    },
11};
12
13use crate::{
14    network::com_interfaces::com_interface::properties::{
15        ComInterfaceProperties, InterfaceDirection,
16    },
17    values::core_values::endpoint::Endpoint,
18};
19
20use crate::{
21    network::com_hub::managers::com_interface_manager::InterfaceInfo,
22    prelude::*,
23};
24use core::fmt::Display;
25use datex_macros_internal::Datex;
26use itertools::Itertools;
27use serde::{Deserialize, Serialize};
28
29#[derive(Datex, Debug, Clone)]
30#[datex(structural)]
31pub struct ComHubMetadataInterfaceSocket {
32    pub uuid: String,
33    pub direction: InterfaceDirection,
34    pub endpoint: Option<Endpoint>,
35    pub properties: Option<DynamicEndpointProperties>,
36}
37
38#[derive(Serialize, Deserialize, Clone)]
39
40pub struct ComHubMetadataInterfaceSocketWithoutEndpoint {
41    pub uuid: String,
42    pub direction: InterfaceDirection,
43}
44
45#[derive(Datex, Debug, Clone)]
46#[datex(structural)]
47pub struct ComHubMetadataInterface {
48    pub uuid: String,
49    pub properties: ComInterfaceProperties,
50    pub sockets: Vec<ComHubMetadataInterfaceSocket>,
51    pub is_waiting_for_socket_connections: bool,
52}
53
54#[derive(Datex, Debug, Clone)]
55#[datex(structural)]
56pub struct ComHubMetadata {
57    pub endpoint: Endpoint,
58    pub interfaces: Vec<ComHubMetadataInterface>,
59    pub reconnecting_interfaces: Vec<ComHubMetadataInterface>,
60}
61
62impl Display for ComHubMetadata {
63    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
64        writeln!(f, "ComHub ({})", self.endpoint)?;
65
66        // print interfaces
67        for interface in &self.interfaces {
68            writeln!(
69                f,
70                "  {}/{}{}{}:",
71                interface.properties.interface_type,
72                interface.properties.channel,
73                if interface.is_waiting_for_socket_connections {
74                    " [accepting connections]"
75                } else {
76                    ""
77                },
78                interface
79                    .properties
80                    .name
81                    .clone()
82                    .map(|n| format!(" ({n})"))
83                    .unwrap_or("".to_string()),
84            )?;
85
86            // print sockets
87            let sorted_sockets = interface.sockets.iter().sorted_by_key(|s| {
88                match &s.properties {
89                    Some(properties) => properties.distance,
90                    None => i8::MAX,
91                }
92            });
93
94            for socket in sorted_sockets {
95                writeln!(
96                    f,
97                    "   {} {}{} (distance: {}, uuid: {})",
98                    match socket.direction {
99                        InterfaceDirection::In => "──▶".to_string(),
100                        InterfaceDirection::Out => "◀──".to_string(),
101                        InterfaceDirection::InOut => "◀──▶".to_string(),
102                    },
103                    match &socket.properties {
104                        Some(properties) => match properties.is_direct {
105                            true => "".to_string(),
106                            false => "[INDIRECT] ".to_string(),
107                        },
108                        None => "".to_string(),
109                    },
110                    match &socket.endpoint {
111                        Some(endpoint) => endpoint.to_string(),
112                        None => "unknown".to_string(),
113                    },
114                    match &socket.properties {
115                        Some(properties) => properties.distance.to_string(),
116                        None => "unknown".to_string(),
117                    },
118                    socket.uuid
119                )?;
120            }
121        }
122
123        Ok(())
124    }
125}
126
127impl ComHub {
128    /// Generates metadata about the ComHub, its interfaces and sockets.
129    pub fn get_metadata(&self) -> ComHubMetadata {
130        let mut metadata = ComHubMetadata {
131            endpoint: self.endpoint().clone(),
132            interfaces: Vec::new(),
133            reconnecting_interfaces: Vec::new(),
134        };
135
136        let mut sockets_by_com_interface_uuid: HashMap<
137            ComInterfaceUUID,
138            Vec<ComHubMetadataInterfaceSocket>,
139        > = HashMap::new();
140
141        for (endpoint, sockets) in
142            self.socket_manager.endpoint_sockets.borrow().iter()
143        {
144            for (socket_uuid, properties) in sockets {
145                let socket = self
146                    .socket_manager
147                    .get_socket_by_uuid(socket_uuid)
148                    .unwrap();
149                let com_interface_uuid = socket.interface_uuid.clone();
150                if !sockets_by_com_interface_uuid
151                    .contains_key(&com_interface_uuid)
152                {
153                    sockets_by_com_interface_uuid
154                        .insert(com_interface_uuid.clone(), Vec::new());
155                }
156                sockets_by_com_interface_uuid
157                    .get_mut(&com_interface_uuid)
158                    .unwrap()
159                    .push(ComHubMetadataInterfaceSocket {
160                        uuid: socket_uuid.to_string(),
161                        endpoint: Some(endpoint.clone()),
162                        direction: socket.socket_properties.direction.clone(),
163                        properties: Some(properties.clone()),
164                    });
165            }
166        }
167
168        for (socket_uuid, socket) in self.socket_manager.sockets.borrow().iter()
169        {
170            // if no endpoints are registered, we consider it a socket without an endpoint
171            if socket.endpoints.is_empty() {
172                let com_interface_uuid = socket.interface_uuid.clone();
173                if !sockets_by_com_interface_uuid
174                    .contains_key(&com_interface_uuid)
175                {
176                    sockets_by_com_interface_uuid
177                        .insert(com_interface_uuid.clone(), Vec::new());
178                }
179                sockets_by_com_interface_uuid
180                    .get_mut(&com_interface_uuid)
181                    .unwrap()
182                    .push(ComHubMetadataInterfaceSocket {
183                        uuid: socket_uuid.to_string(),
184                        direction: socket.socket_properties.direction.clone(),
185                        endpoint: None,
186                        properties: None,
187                    });
188                continue;
189            }
190        }
191
192        for (uuid, info) in self.interfaces_manager.interfaces.borrow().iter() {
193            metadata.interfaces.push(interface_info_to_metadata(
194                uuid,
195                info,
196                &mut sockets_by_com_interface_uuid,
197            ));
198        }
199
200        for (uuid, info) in self.reconnecting_interfaces.borrow().iter() {
201            metadata
202                .reconnecting_interfaces
203                .push(interface_info_to_metadata(
204                    uuid,
205                    info,
206                    &mut sockets_by_com_interface_uuid,
207                ));
208        }
209
210        metadata
211    }
212
213    /// Prints the ComHub metadata to the log.
214    pub fn print_metadata(&self) {
215        let metadata = self.get_metadata();
216        info!("ComHub Metadata:\n{metadata}");
217    }
218}
219
220fn interface_info_to_metadata(
221    uuid: &ComInterfaceUUID,
222    info: &InterfaceInfo,
223    sockets_by_com_interface_uuid: &mut HashMap<
224        ComInterfaceUUID,
225        Vec<ComHubMetadataInterfaceSocket>,
226    >,
227) -> ComHubMetadataInterface {
228    let InterfaceInfo {
229        properties,
230        is_waiting_for_socket_connections,
231        ..
232    } = info;
233
234    ComHubMetadataInterface {
235        uuid: uuid.to_string(),
236        properties: properties.as_ref().clone(),
237        sockets: sockets_by_com_interface_uuid
238            .remove(uuid)
239            .unwrap_or_default(),
240        is_waiting_for_socket_connections: *is_waiting_for_socket_connections,
241    }
242}