microrti-client 0.2.0

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
//! The seam between the RTI ambassador and whatever carries the service messages to an RTI.
//!
//! An [`RtiLink`] moves `CallRequest` / `CallResponse` and `CallbackRequest` / `CallbackResponse`
//! messages (12.13.3.1) and knows nothing about HLA semantics. Two kinds of links are expected: a Federate
//! Protocol session to any HLA 4 RTI, and an in-process RTI (see [`crate::local`]).
//!
//! A [`LinkFactory`] opens a link for the RTI address of an [`RtiConfiguration`]; [`Connectors`] selects the
//! factory by address scheme.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use microrti_proto::{CallRequest, CallResponse, CallbackRequest, CallbackResponse};

use crate::types::RtiConfiguration;

/// Failure of an [`RtiLink`] or of a [`LinkFactory`].
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum LinkError {
    /// The connection to the RTI broke; the text describes the fault. The RTI ambassador reports it to the
    /// federate with the Connection Lost callback (4.4).
    #[error("connection to the RTI lost: {0}")]
    Lost(String),
    /// The link was closed on purpose by [`RtiLink::close`].
    #[error("the link to the RTI is closed")]
    Closed,
    /// No link could be opened: no connector for the address, or the RTI cannot be reached.
    #[error("cannot reach the RTI: {0}")]
    Unreachable(String),
    /// Any other failure, for example a message that could not be encoded.
    #[error("link failure: {0}")]
    Failed(String),
}

/// Condition of an [`RtiLink`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LinkState {
    /// Messages can be exchanged.
    Open,
    /// [`RtiLink::close`] was called.
    Closed,
    /// The connection broke; the text describes the fault.
    Lost(String),
}

/// A callback request pulled from a link, with the token needed to answer it.
#[derive(Clone, Debug, PartialEq)]
pub struct LinkCallback {
    /// Opaque token chosen by the link (for a Federate Protocol session: the sequence number of the
    /// callback request message). Passed back to [`RtiLink::respond`].
    pub id: u64,
    /// The RTI-initiated service invocation.
    pub request: CallbackRequest,
}

/// Transport of service messages between one federate and its RTI.
///
/// All methods take `&self`: the RTI ambassador calls [`RtiLink::call`] from several threads at once
/// (12.8) while another thread waits in [`RtiLink::next_callback`]. The ambassador itself never calls
/// `next_callback` from two threads at the same time.
pub trait RtiLink: Send + Sync {
    /// Sends one federate-initiated service invocation and blocks until its response arrives.
    ///
    /// An exception raised by the RTI is a successful exchange: it comes back as the `ExceptionData`
    /// alternative of the response.
    fn call(&self, request: CallRequest) -> Result<CallResponse, LinkError>;

    /// Removes the oldest undelivered callback request, waiting for one if necessary.
    ///
    /// `None` waits without limit, `Some(Duration::ZERO)` only polls. Returns `Ok(None)` when the timeout
    /// expires. Callbacks that arrived before a fault are still handed out; after that the fault is
    /// reported as [`LinkError::Lost`]. A blocked call must return promptly once [`RtiLink::close`] is
    /// called (with [`LinkError::Closed`]).
    fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError>;

    /// Answers the callback request identified by `id` (the federate ambassador returned or failed).
    fn respond(&self, id: u64, response: CallbackResponse) -> Result<(), LinkError>;

    /// Current condition of the link.
    fn state(&self) -> LinkState;

    /// Releases the link. Idempotent; wakes every blocked [`RtiLink::next_callback`].
    fn close(&self);
}

/// Opens links: the connector abstraction used by the Connect service (4.2).
pub trait LinkFactory: Send + Sync {
    /// Opens a link to the RTI designated by `configuration` (usually by its RTI address).
    fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError>;
}

impl<F> LinkFactory for F
where
    F: Fn(&RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> + Send + Sync,
{
    fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
        self(configuration)
    }
}

/// A set of [`LinkFactory`] connectors selected by the scheme of the RTI address.
///
/// The scheme is the text before the first `:` of the address (`tcp://host:15164` has scheme `tcp`). An
/// address without a registered scheme, such as `host:15164` or the empty address, goes to the default
/// connector. An address of the form `scheme://...` whose scheme is not registered is an error.
#[derive(Clone, Default)]
pub struct Connectors {
    by_scheme: BTreeMap<String, Arc<dyn LinkFactory>>,
    fallback: Option<Arc<dyn LinkFactory>>,
}

impl Connectors {
    /// Creates an empty set.
    pub const fn new() -> Self {
        Self { by_scheme: BTreeMap::new(), fallback: None }
    }

    /// Registers (or replaces) the connector of an address scheme. Schemes are case insensitive.
    pub fn register(&mut self, scheme: &str, factory: impl LinkFactory + 'static) -> &mut Self {
        self.by_scheme.insert(scheme.to_ascii_lowercase(), Arc::new(factory));
        self
    }

    /// Registers (or replaces) the connector used for addresses without a registered scheme.
    pub fn register_default(&mut self, factory: impl LinkFactory + 'static) -> &mut Self {
        self.fallback = Some(Arc::new(factory));
        self
    }

    /// Registered schemes, sorted.
    pub fn schemes(&self) -> Vec<String> {
        self.by_scheme.keys().cloned().collect()
    }

    /// Selects the connector for an RTI address.
    pub fn resolve(&self, rti_address: &str) -> Option<Arc<dyn LinkFactory>> {
        if let Some((scheme, rest)) = rti_address.split_once(':')
            && is_scheme(scheme)
        {
            if let Some(factory) = self.by_scheme.get(&scheme.to_ascii_lowercase()) {
                return Some(Arc::clone(factory));
            }
            if rest.starts_with("//") {
                return None;
            }
        }
        self.fallback.clone()
    }

    /// Opens a link with the connector selected by the RTI address of `configuration`.
    pub fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
        let address = configuration.rti_address();
        match self.resolve(address) {
            Some(factory) => factory.open(configuration),
            None => {
                Err(LinkError::Unreachable(format!("no connector registered for RTI address {address:?}")))
            }
        }
    }
}

impl std::fmt::Debug for Connectors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Connectors")
            .field("schemes", &self.schemes())
            .field("default", &self.fallback.is_some())
            .finish()
    }
}

fn is_scheme(text: &str) -> bool {
    let mut chars = text.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}

static GLOBAL: Mutex<Connectors> = Mutex::new(Connectors::new());

/// The process-wide set. With the feature `fedpro` it starts out with the Federate Protocol connectors
/// for `tcp`, `tls`, `ws`, `wss` and for addresses without a scheme (see [`crate::fedpro`]); whatever the
/// application registers afterwards replaces them.
fn global() -> std::sync::MutexGuard<'static, Connectors> {
    #[cfg(feature = "fedpro")]
    {
        static BUILT_IN: std::sync::Once = std::sync::Once::new();
        BUILT_IN.call_once(|| {
            let mut connectors = GLOBAL.lock().unwrap_or_else(PoisonError::into_inner);
            crate::fedpro::FedProConnector::default().register(&mut connectors);
        });
    }
    GLOBAL.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Registers a connector for an address scheme in the process-wide set used by
/// [`RtiAmbassador::new`](crate::RtiAmbassador::new).
pub fn register_connector(scheme: &str, factory: impl LinkFactory + 'static) {
    global().register(scheme, factory);
}

/// Registers the process-wide connector for addresses without a registered scheme.
pub fn register_default_connector(factory: impl LinkFactory + 'static) {
    global().register_default(factory);
}

/// A snapshot of the process-wide connector set.
pub fn global_connectors() -> Connectors {
    global().clone()
}