microrti-client 0.2.0

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
//! An [`RtiLink`] to an RTI that lives in the same process.
//!
//! [`LocalRti`] is the shape of a synchronous in-process RTI: it executes one call at a time and queues the
//! callbacks it produces per connection. [`LocalRtiHub`] shares one such RTI between any number of
//! federates of the process and gives each of them a link; it is also a [`LinkFactory`], so it can be
//! registered as a connector.

use std::collections::{BTreeMap, VecDeque};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

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

use crate::link::{LinkCallback, LinkError, LinkFactory, LinkState, RtiLink};
use crate::types::RtiConfiguration;

/// A synchronous RTI in the same process.
pub trait LocalRti: Send {
    /// A federate session appears; returns the identifier used for it in the other methods.
    fn open_connection(&mut self) -> u64;

    /// Executes one federate-initiated service. Exceptions come back as the `ExceptionData` alternative.
    fn call(&mut self, connection: u64, request: CallRequest) -> CallResponse;

    /// Removes and returns the callbacks queued for a connection, in delivery order.
    fn take_callbacks(&mut self, connection: u64) -> Vec<CallbackRequest>;

    /// The federate answered a callback: `callback` is the position of the callback among all those
    /// [`LocalRti::take_callbacks`] has returned for the connection, from zero. An RTI that has no use
    /// for the outcome of a callback keeps the default, which ignores it.
    fn callback_response(&mut self, connection: u64, callback: u64, response: CallbackResponse) {
        let _ = (connection, callback, response);
    }

    /// The federate session ended.
    fn close_connection(&mut self, connection: u64);
}

struct Session {
    queue: VecDeque<CallbackRequest>,
    next_id: u64,
}

struct Hub<R> {
    rti: R,
    /// The open links, by connection identifier.
    sessions: BTreeMap<u64, Session>,
}

struct Inner<R> {
    hub: Mutex<Hub<R>>,
    /// Signalled whenever the RTI may have produced callbacks or a link was closed.
    wake: Condvar,
}

impl<R> Inner<R> {
    fn lock(&self) -> MutexGuard<'_, Hub<R>> {
        self.hub.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Shares one in-process RTI between the federates of this process.
pub struct LocalRtiHub<R: LocalRti> {
    inner: Arc<Inner<R>>,
}

impl<R: LocalRti> Clone for LocalRtiHub<R> {
    fn clone(&self) -> Self {
        Self { inner: Arc::clone(&self.inner) }
    }
}

impl<R: LocalRti + 'static> LocalRtiHub<R> {
    /// Wraps the RTI.
    pub fn new(rti: R) -> Self {
        Self {
            inner: Arc::new(Inner {
                hub: Mutex::new(Hub { rti, sessions: BTreeMap::new() }),
                wake: Condvar::new(),
            }),
        }
    }

    /// Opens a connection on the RTI and returns the link for it.
    pub fn link(&self) -> Arc<dyn RtiLink> {
        let mut hub = self.inner.lock();
        let connection = hub.rti.open_connection();
        hub.sessions.insert(connection, Session { queue: VecDeque::new(), next_id: 1 });
        Arc::new(LocalLink { inner: Arc::clone(&self.inner), connection })
    }

    /// Runs `action` on the RTI (for example its periodic tick) and wakes the links, since the action may
    /// have produced callbacks.
    pub fn with_rti<T>(&self, action: impl FnOnce(&mut R) -> T) -> T {
        let mut hub = self.inner.lock();
        let value = action(&mut hub.rti);
        self.inner.wake.notify_all();
        value
    }
}

impl<R: LocalRti + 'static> LinkFactory for LocalRtiHub<R> {
    fn open(&self, _: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
        Ok(self.link())
    }
}

struct LocalLink<R: LocalRti> {
    inner: Arc<Inner<R>>,
    connection: u64,
}

impl<R: LocalRti> RtiLink for LocalLink<R> {
    fn call(&self, request: CallRequest) -> Result<CallResponse, LinkError> {
        let mut hub = self.inner.lock();
        if !hub.sessions.contains_key(&self.connection) {
            return Err(LinkError::Closed);
        }
        let response = hub.rti.call(self.connection, request);
        // Any call may have produced callbacks for any federate.
        self.inner.wake.notify_all();
        Ok(response)
    }

    fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError> {
        let deadline = timeout.map(|timeout| Instant::now() + timeout);
        let mut hub = self.inner.lock();
        loop {
            if !hub.sessions.contains_key(&self.connection) {
                return Err(LinkError::Closed);
            }
            let fresh = hub.rti.take_callbacks(self.connection);
            if let Some(session) = hub.sessions.get_mut(&self.connection) {
                session.queue.extend(fresh);
                if let Some(request) = session.queue.pop_front() {
                    let id = session.next_id;
                    session.next_id += 1;
                    return Ok(Some(LinkCallback { id, request }));
                }
            }
            hub = match deadline {
                None => self.inner.wake.wait(hub).unwrap_or_else(PoisonError::into_inner),
                Some(deadline) => {
                    let now = Instant::now();
                    if now >= deadline {
                        return Ok(None);
                    }
                    self.inner
                        .wake
                        .wait_timeout(hub, deadline - now)
                        .unwrap_or_else(PoisonError::into_inner)
                        .0
                }
            };
        }
    }

    fn respond(&self, id: u64, response: CallbackResponse) -> Result<(), LinkError> {
        // A synchronous RTI does not wait for callback responses, but it is told the outcome.
        if let Some(microrti_proto::callback_response::CallbackResponse::CallbackFailed(failure)) =
            &response.callback_response
        {
            tracing::debug!(callback = id, exception = %failure.exception_name, details = %failure.details, "callback failed");
        }
        let mut hub = self.inner.lock();
        // The identifiers of a session count its callbacks from one, in the order they were taken.
        if hub.sessions.contains_key(&self.connection)
            && let Some(position) = id.checked_sub(1)
        {
            hub.rti.callback_response(self.connection, position, response);
            // The outcome may have produced callbacks for other federates (MOM service reports).
            self.inner.wake.notify_all();
        }
        Ok(())
    }

    fn state(&self) -> LinkState {
        if self.inner.lock().sessions.contains_key(&self.connection) {
            LinkState::Open
        } else {
            LinkState::Closed
        }
    }

    fn close(&self) {
        let mut hub = self.inner.lock();
        if hub.sessions.remove(&self.connection).is_some() {
            hub.rti.close_connection(self.connection);
            self.inner.wake.notify_all();
        }
    }
}

impl<R: LocalRti> Drop for LocalLink<R> {
    fn drop(&mut self) {
        self.close();
    }
}