datex-core 0.0.14

The DATEX Core Rust implementation
Documentation
use log::info;

use crate::{
    collections::HashMap,
    network::{
        com_hub::{
            ComHub, managers::socket_manager::DynamicEndpointProperties,
        },
        com_interfaces::com_interface::ComInterfaceUUID,
    },
};

use crate::{
    network::com_interfaces::com_interface::properties::{
        ComInterfaceProperties, InterfaceDirection,
    },
    values::core_values::endpoint::Endpoint,
};

use crate::{
    network::com_hub::managers::com_interface_manager::InterfaceInfo,
    prelude::*,
};
use core::fmt::Display;
use datex_macros_internal::Datex;
use itertools::Itertools;
use serde::{Deserialize, Serialize};

#[derive(Datex, Debug, Clone)]
#[datex(structural)]
pub struct ComHubMetadataInterfaceSocket {
    pub uuid: String,
    pub direction: InterfaceDirection,
    pub endpoint: Option<Endpoint>,
    pub properties: Option<DynamicEndpointProperties>,
}

#[derive(Serialize, Deserialize, Clone)]

pub struct ComHubMetadataInterfaceSocketWithoutEndpoint {
    pub uuid: String,
    pub direction: InterfaceDirection,
}

#[derive(Datex, Debug, Clone)]
#[datex(structural)]
pub struct ComHubMetadataInterface {
    pub uuid: String,
    pub properties: ComInterfaceProperties,
    pub sockets: Vec<ComHubMetadataInterfaceSocket>,
    pub is_waiting_for_socket_connections: bool,
}

#[derive(Datex, Debug, Clone)]
#[datex(structural)]
pub struct ComHubMetadata {
    pub endpoint: Endpoint,
    pub interfaces: Vec<ComHubMetadataInterface>,
    pub reconnecting_interfaces: Vec<ComHubMetadataInterface>,
}

impl Display for ComHubMetadata {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        writeln!(f, "ComHub ({})", self.endpoint)?;

        // print interfaces
        for interface in &self.interfaces {
            writeln!(
                f,
                "  {}/{}{}{}:",
                interface.properties.interface_type,
                interface.properties.channel,
                if interface.is_waiting_for_socket_connections {
                    " [accepting connections]"
                } else {
                    ""
                },
                interface
                    .properties
                    .name
                    .clone()
                    .map(|n| format!(" ({n})"))
                    .unwrap_or("".to_string()),
            )?;

            // print sockets
            let sorted_sockets = interface.sockets.iter().sorted_by_key(|s| {
                match &s.properties {
                    Some(properties) => properties.distance,
                    None => i8::MAX,
                }
            });

            for socket in sorted_sockets {
                writeln!(
                    f,
                    "   {} {}{} (distance: {}, uuid: {})",
                    match socket.direction {
                        InterfaceDirection::In => "──▶".to_string(),
                        InterfaceDirection::Out => "◀──".to_string(),
                        InterfaceDirection::InOut => "◀──▶".to_string(),
                    },
                    match &socket.properties {
                        Some(properties) => match properties.is_direct {
                            true => "".to_string(),
                            false => "[INDIRECT] ".to_string(),
                        },
                        None => "".to_string(),
                    },
                    match &socket.endpoint {
                        Some(endpoint) => endpoint.to_string(),
                        None => "unknown".to_string(),
                    },
                    match &socket.properties {
                        Some(properties) => properties.distance.to_string(),
                        None => "unknown".to_string(),
                    },
                    socket.uuid
                )?;
            }
        }

        Ok(())
    }
}

impl ComHub {
    /// Generates metadata about the ComHub, its interfaces and sockets.
    pub fn get_metadata(&self) -> ComHubMetadata {
        let mut metadata = ComHubMetadata {
            endpoint: self.endpoint().clone(),
            interfaces: Vec::new(),
            reconnecting_interfaces: Vec::new(),
        };

        let mut sockets_by_com_interface_uuid: HashMap<
            ComInterfaceUUID,
            Vec<ComHubMetadataInterfaceSocket>,
        > = HashMap::new();

        for (endpoint, sockets) in
            self.socket_manager.endpoint_sockets.borrow().iter()
        {
            for (socket_uuid, properties) in sockets {
                let socket = self
                    .socket_manager
                    .get_socket_by_uuid(socket_uuid)
                    .unwrap();
                let com_interface_uuid = socket.interface_uuid.clone();
                if !sockets_by_com_interface_uuid
                    .contains_key(&com_interface_uuid)
                {
                    sockets_by_com_interface_uuid
                        .insert(com_interface_uuid.clone(), Vec::new());
                }
                sockets_by_com_interface_uuid
                    .get_mut(&com_interface_uuid)
                    .unwrap()
                    .push(ComHubMetadataInterfaceSocket {
                        uuid: socket_uuid.to_string(),
                        endpoint: Some(endpoint.clone()),
                        direction: socket.socket_properties.direction.clone(),
                        properties: Some(properties.clone()),
                    });
            }
        }

        for (socket_uuid, socket) in self.socket_manager.sockets.borrow().iter()
        {
            // if no endpoints are registered, we consider it a socket without an endpoint
            if socket.endpoints.is_empty() {
                let com_interface_uuid = socket.interface_uuid.clone();
                if !sockets_by_com_interface_uuid
                    .contains_key(&com_interface_uuid)
                {
                    sockets_by_com_interface_uuid
                        .insert(com_interface_uuid.clone(), Vec::new());
                }
                sockets_by_com_interface_uuid
                    .get_mut(&com_interface_uuid)
                    .unwrap()
                    .push(ComHubMetadataInterfaceSocket {
                        uuid: socket_uuid.to_string(),
                        direction: socket.socket_properties.direction.clone(),
                        endpoint: None,
                        properties: None,
                    });
                continue;
            }
        }

        for (uuid, info) in self.interfaces_manager.interfaces.borrow().iter() {
            metadata.interfaces.push(interface_info_to_metadata(
                uuid,
                info,
                &mut sockets_by_com_interface_uuid,
            ));
        }

        for (uuid, info) in self.reconnecting_interfaces.borrow().iter() {
            metadata
                .reconnecting_interfaces
                .push(interface_info_to_metadata(
                    uuid,
                    info,
                    &mut sockets_by_com_interface_uuid,
                ));
        }

        metadata
    }

    /// Prints the ComHub metadata to the log.
    pub fn print_metadata(&self) {
        let metadata = self.get_metadata();
        info!("ComHub Metadata:\n{metadata}");
    }
}

fn interface_info_to_metadata(
    uuid: &ComInterfaceUUID,
    info: &InterfaceInfo,
    sockets_by_com_interface_uuid: &mut HashMap<
        ComInterfaceUUID,
        Vec<ComHubMetadataInterfaceSocket>,
    >,
) -> ComHubMetadataInterface {
    let InterfaceInfo {
        properties,
        is_waiting_for_socket_connections,
        ..
    } = info;

    ComHubMetadataInterface {
        uuid: uuid.to_string(),
        properties: properties.as_ref().clone(),
        sockets: sockets_by_com_interface_uuid
            .remove(uuid)
            .unwrap_or_default(),
        is_waiting_for_socket_connections: *is_waiting_for_socket_connections,
    }
}