microrti-client 0.1.2

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
//! The embedded link: an RTI that lives inside the federate's process (cargo feature `embedded`).
//!
//! [`EmbeddedRti`] hosts one `microrti-engine` RTI and gives every [`RtiAmbassador`] that connects to it
//! a link of its own; a background thread drives the wall-clock work of the RTI. No network is involved:
//! a service invocation is a function call. The federates of one process share federation executions
//! through it exactly as they would through a server.
//!
//! ```
//! use microrti_client::embedded::{EmbeddedRti, RtiConfig};
//! use microrti_client::{CallbackModel, NullFederateAmbassador};
//!
//! let embedded = EmbeddedRti::new(RtiConfig::default());
//! let rti = embedded.ambassador();
//! rti.connect(NullFederateAmbassador, CallbackModel::Evoked)?;
//! assert!(rti.is_connected());
//! rti.disconnect()?;
//! # Ok::<(), microrti_client::RtiError>(())
//! ```
//!
//! An [`EmbeddedRti`] is also a connector: register it for an address scheme and
//! [`RtiAmbassador::new`] reaches it through the RTI address (see [`EmbeddedRti::register`]).

use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

pub use microrti_engine::{AuthorizationConfig, Rti, RtiConfig};
use microrti_proto::{CallRequest, CallResponse, CallbackRequest, CallbackResponse};

use crate::ambassador::RtiAmbassador;
use crate::link::{LinkError, LinkFactory, RtiLink};
use crate::local::{LocalRti, LocalRtiHub};
use crate::types::RtiConfiguration;

/// Default period of the background thread that calls [`Rti::tick`].
pub const DEFAULT_TICK_PERIOD: Duration = Duration::from_millis(100);

impl LocalRti for Rti {
    fn open_connection(&mut self) -> u64 {
        let connection = Rti::open_connection(self);
        // The link tells the outcome of every callback (MOM service reports, 11.5).
        Rti::expect_callback_responses(self, connection);
        connection
    }

    fn callback_response(&mut self, connection: u64, callback: u64, response: CallbackResponse) {
        Rti::callback_response(self, connection, callback, response);
    }

    fn call(&mut self, connection: u64, request: CallRequest) -> CallResponse {
        Rti::call(self, connection, request)
    }

    fn take_callbacks(&mut self, connection: u64) -> Vec<CallbackRequest> {
        Rti::take_callbacks(self, connection)
    }

    fn close_connection(&mut self, connection: u64) {
        Rti::close_connection(self, connection);
    }
}

/// Tells the tick thread to end.
struct StopSignal {
    stopped: Mutex<bool>,
    wake: Condvar,
}

struct Inner {
    hub: LocalRtiHub<Rti>,
    stop: Arc<StopSignal>,
    ticker: Mutex<Option<JoinHandle<()>>>,
}

impl Drop for Inner {
    fn drop(&mut self) {
        *self.stop.stopped.lock().unwrap_or_else(PoisonError::into_inner) = true;
        self.stop.wake.notify_all();
        let ticker = self.ticker.lock().unwrap_or_else(PoisonError::into_inner).take();
        if let Some(ticker) = ticker
            && ticker.thread().id() != thread::current().id()
        {
            let _ = ticker.join();
        }
    }
}

/// An RTI in the federate's process, shared by any number of RTI ambassadors.
///
/// Cloning gives another handle of the same RTI. The RTI and its tick thread end when the last handle is
/// dropped; links that are still open then stay usable but nothing drives the wall-clock work any more.
#[derive(Clone)]
pub struct EmbeddedRti {
    inner: Arc<Inner>,
}

impl std::fmt::Debug for EmbeddedRti {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("EmbeddedRti")
    }
}

impl EmbeddedRti {
    /// Creates an RTI with the given settings, ticking every [`DEFAULT_TICK_PERIOD`].
    pub fn new(config: RtiConfig) -> Self {
        Self::from_rti(Rti::new(config), DEFAULT_TICK_PERIOD)
    }

    /// Creates an RTI with the given settings and tick period.
    pub fn with_tick_period(config: RtiConfig, tick_period: Duration) -> Self {
        Self::from_rti(Rti::new(config), tick_period)
    }

    /// Shares an RTI the application has built itself (for example with its own authorization service).
    ///
    /// If the tick thread cannot be started the RTI still works, without its wall-clock driven work; the
    /// failure is logged.
    pub fn from_rti(rti: Rti, tick_period: Duration) -> Self {
        let hub = LocalRtiHub::new(rti);
        let stop = Arc::new(StopSignal { stopped: Mutex::new(false), wake: Condvar::new() });
        let period = tick_period.max(Duration::from_millis(1));
        let ticker = {
            let hub = hub.clone();
            let stop = Arc::clone(&stop);
            thread::Builder::new().name("microrti-embedded-tick".to_owned()).spawn(move || {
                let mut stopped = stop.stopped.lock().unwrap_or_else(PoisonError::into_inner);
                while !*stopped {
                    stopped =
                        stop.wake.wait_timeout(stopped, period).unwrap_or_else(PoisonError::into_inner).0;
                    if !*stopped {
                        hub.with_rti(|rti| rti.tick(Instant::now()));
                    }
                }
            })
        };
        let ticker = match ticker {
            Ok(ticker) => Some(ticker),
            Err(error) => {
                tracing::error!(%error, "cannot start the tick thread of the embedded RTI");
                None
            }
        };
        EmbeddedRti { inner: Arc::new(Inner { hub, stop, ticker: Mutex::new(ticker) }) }
    }

    /// Opens a connection on the RTI and returns its link, for
    /// [`RtiAmbassador::with_link`](crate::RtiAmbassador::with_link).
    pub fn link(&self) -> Arc<dyn RtiLink> {
        self.inner.hub.link()
    }

    /// An RTI ambassador whose Connect reaches this RTI, whatever RTI address it is given. The ambassador
    /// can connect, disconnect and connect again.
    pub fn ambassador(&self) -> RtiAmbassador {
        RtiAmbassador::with_connector(self.clone())
    }

    /// Registers this RTI as the process-wide connector of an address scheme, so that
    /// [`RtiAmbassador::new`](crate::RtiAmbassador::new) reaches it with an RTI address such as
    /// `embedded:` when `scheme` is `embedded`. The registration keeps the RTI alive.
    pub fn register(&self, scheme: &str) {
        crate::link::register_connector(scheme, self.clone());
    }

    /// Runs `action` on the RTI, then wakes the links since it may have produced callbacks.
    pub fn with_rti<T>(&self, action: impl FnOnce(&mut Rti) -> T) -> T {
        self.inner.hub.with_rti(action)
    }
}

impl LinkFactory for EmbeddedRti {
    fn open(&self, _: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
        Ok(self.link())
    }
}

#[cfg(test)]
mod tests {
    use microrti_core::ExceptionKind;

    use super::*;
    use crate::{CallbackModel, Credentials, LinkState, NullFederateAmbassador, ServiceGroup};

    #[test]
    fn ambassadors_connect_to_the_one_rti() {
        let embedded = EmbeddedRti::with_tick_period(RtiConfig::default(), Duration::from_millis(5));
        let first = embedded.ambassador();
        let second = embedded.ambassador();
        // Before Connect the ambassador answers itself; after it, the engine does.
        let unconnected = first.normalize_service_group(ServiceGroup::ObjectManagement).unwrap_err();
        assert_eq!(unconnected.kind, ExceptionKind::NotConnected);
        first.connect(NullFederateAmbassador, CallbackModel::Evoked).unwrap();
        second.connect(NullFederateAmbassador, CallbackModel::Immediate).unwrap();
        for ambassador in [&first, &second] {
            for group in ServiceGroup::ALL {
                let not_joined = ambassador.normalize_service_group(*group).unwrap_err();
                assert_eq!(not_joined.kind, ExceptionKind::FederateNotExecutionMember, "{not_joined}");
            }
        }
        // Each ambassador has its own connection of the engine.
        first.disconnect().unwrap();
        assert!(!first.is_connected());
        assert!(second.is_connected());
        assert_eq!(first.evoke_callback(Duration::ZERO), Ok(false));
        // The same ambassador connects again: the connector opens a new link.
        first.connect(NullFederateAmbassador, CallbackModel::Evoked).unwrap();
        assert!(first.is_connected());
    }

    #[test]
    fn authorization_settings_reach_the_engine() {
        let embedded = EmbeddedRti::new(RtiConfig::with_password("open sesame"));
        let rti = embedded.ambassador();
        let refused = rti.connect(NullFederateAmbassador, CallbackModel::Evoked).unwrap_err();
        assert_eq!(refused.kind, ExceptionKind::Unauthorized);
        assert!(!rti.is_connected());
        let credentials = Credentials::plain_text_password("open sesame");
        rti.connect_with_credentials(NullFederateAmbassador, CallbackModel::Evoked, &credentials).unwrap();
        assert!(rti.is_connected());
    }

    #[test]
    fn links_close_their_connection_and_the_tick_thread_ends_with_the_last_handle() {
        let embedded = EmbeddedRti::with_tick_period(RtiConfig::default(), Duration::from_millis(1));
        let link = embedded.link();
        assert_eq!(link.state(), LinkState::Open);
        link.close();
        assert_eq!(link.state(), LinkState::Closed);
        assert_eq!(link.next_callback(Some(Duration::ZERO)), Err(LinkError::Closed));
        let stop = Arc::clone(&embedded.inner.stop);
        let other = embedded.clone();
        drop(embedded);
        assert!(!*stop.stopped.lock().unwrap(), "a clone keeps the RTI running");
        drop(other);
        assert!(*stop.stopped.lock().unwrap());
    }
}