microrti-client 0.1.2

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
//! Test support, exported with the cargo feature `test-util`: a scripted in-memory [`RtiLink`].
//!
//! [`MockLink`] records every request, answers from a script (or with a plausible default response of the
//! right alternative), lets a test inject callback requests and faults, and records the callback responses.
//!
//! ```
//! use microrti_client::testing::MockLink;
//! use microrti_client::{CallbackModel, ExceptionKind, NullFederateAmbassador, RtiAmbassador};
//!
//! let link = MockLink::new();
//! let rti = RtiAmbassador::with_link(link.clone());
//! rti.connect(NullFederateAmbassador, CallbackModel::Evoked).unwrap();
//! link.push_exception("FederationExecutionDoesNotExist", "no such federation");
//! let error = rti.destroy_federation_execution("Lunch").unwrap_err();
//! assert_eq!(error.kind, ExceptionKind::FederationExecutionDoesNotExist);
//! assert_eq!(link.requests().len(), 2);
//! ```

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

use microrti_proto as proto;
use proto::call_request::CallRequest as Call;
use proto::call_response::CallResponse as Reply;
use proto::callback_request::CallbackRequest as WireCallback;
use proto::callback_response::CallbackResponse as CallbackReply;

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

mod replies;

pub use replies::default_reply;

/// Computes the response to a request the script has no entry for. `None` falls back to [`default_reply`].
pub type Responder = dyn Fn(&Call) -> Option<Reply> + Send + Sync;

enum Step {
    Reply(Reply),
    Raw(proto::CallResponse),
    Fail(LinkError),
}

struct Inner {
    state: LinkState,
    requests: Vec<Call>,
    script: VecDeque<Step>,
    responder: Option<Arc<Responder>>,
    callbacks: VecDeque<LinkCallback>,
    next_callback_id: u64,
    responses: Vec<(u64, CallbackReply)>,
}

/// A scripted in-memory [`RtiLink`].
///
/// A call is answered, in this order of preference, by the oldest scripted step ([`MockLink::push_reply`],
/// [`MockLink::push_exception`], [`MockLink::push_failure`]), by the responder ([`MockLink::set_responder`]),
/// or by [`default_reply`]. The responder runs without any lock held, so calls from several threads overlap.
pub struct MockLink {
    inner: Mutex<Inner>,
    changed: Condvar,
}

impl MockLink {
    /// Creates an open link with an empty script.
    pub fn new() -> Arc<Self> {
        Arc::new(MockLink {
            inner: Mutex::new(Inner {
                state: LinkState::Open,
                requests: Vec::new(),
                script: VecDeque::new(),
                responder: None,
                callbacks: VecDeque::new(),
                next_callback_id: 1,
                responses: Vec::new(),
            }),
            changed: Condvar::new(),
        })
    }

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

    /// Scripts the response to the next unscripted call.
    pub fn push_reply(&self, reply: Reply) {
        self.lock().script.push_back(Step::Reply(reply));
    }

    /// Scripts an exception as the response to the next unscripted call.
    pub fn push_exception(&self, exception_name: &str, details: &str) {
        self.push_reply(Reply::ExceptionData(proto::ExceptionData {
            exception_name: exception_name.to_owned(),
            details: details.to_owned(),
        }));
    }

    /// Scripts a complete response message for the next unscripted call, including one without any
    /// alternative.
    pub fn push_raw_reply(&self, response: proto::CallResponse) {
        self.lock().script.push_back(Step::Raw(response));
    }

    /// Scripts a link failure for the next unscripted call. The link itself stays open.
    pub fn push_failure(&self, error: LinkError) {
        self.lock().script.push_back(Step::Fail(error));
    }

    /// Installs the function that answers calls once the script is empty.
    pub fn set_responder(&self, responder: impl Fn(&Call) -> Option<Reply> + Send + Sync + 'static) {
        self.lock().responder = Some(Arc::new(responder));
    }

    /// Every request received so far, oldest first.
    pub fn requests(&self) -> Vec<Call> {
        self.lock().requests.clone()
    }

    /// The most recent request.
    pub fn last_request(&self) -> Option<Call> {
        self.lock().requests.last().cloned()
    }

    /// Removes and returns the recorded requests.
    pub fn take_requests(&self) -> Vec<Call> {
        std::mem::take(&mut self.lock().requests)
    }

    /// Queues a callback request as if the RTI had sent it; returns the identifier its response will carry.
    pub fn push_callback(&self, request: WireCallback) -> u64 {
        self.push_raw_callback(proto::CallbackRequest { callback_request: Some(request) })
    }

    /// Like [`MockLink::push_callback`] for a complete message, including one without any alternative.
    pub fn push_raw_callback(&self, request: proto::CallbackRequest) -> u64 {
        let mut inner = self.lock();
        let id = inner.next_callback_id;
        inner.next_callback_id += 1;
        inner.callbacks.push_back(LinkCallback { id, request });
        self.changed.notify_all();
        id
    }

    /// Number of callback requests nobody has pulled yet.
    pub fn queued_callbacks(&self) -> usize {
        self.lock().callbacks.len()
    }

    /// The callback responses received so far, with the identifiers of their requests.
    pub fn callback_responses(&self) -> Vec<(u64, CallbackReply)> {
        self.lock().responses.clone()
    }

    /// Waits until at least `count` callback responses have arrived. Returns false on timeout.
    pub fn wait_for_callback_responses(&self, count: usize, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;
        let mut inner = self.lock();
        while inner.responses.len() < count {
            let now = Instant::now();
            if now >= deadline {
                return false;
            }
            inner =
                self.changed.wait_timeout(inner, deadline - now).unwrap_or_else(PoisonError::into_inner).0;
        }
        true
    }

    /// Simulates a fault: callbacks already queued are still handed out, then the link reports the loss.
    pub fn lose_connection(&self, fault_description: &str) {
        let mut inner = self.lock();
        if inner.state == LinkState::Open {
            inner.state = LinkState::Lost(fault_description.to_owned());
        }
        self.changed.notify_all();
    }

    /// True once [`RtiLink::close`] was called.
    pub fn is_closed(&self) -> bool {
        self.lock().state == LinkState::Closed
    }
}

impl std::fmt::Debug for MockLink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let inner = self.lock();
        f.debug_struct("MockLink")
            .field("state", &inner.state)
            .field("requests", &inner.requests.len())
            .field("queued_callbacks", &inner.callbacks.len())
            .finish()
    }
}

impl RtiLink for MockLink {
    fn call(&self, request: proto::CallRequest) -> Result<proto::CallResponse, LinkError> {
        let Some(request) = request.call_request else {
            return Err(LinkError::Failed("call request without an alternative".to_owned()));
        };
        let (step, responder) = {
            let mut inner = self.lock();
            match &inner.state {
                LinkState::Open => {}
                LinkState::Closed => return Err(LinkError::Closed),
                LinkState::Lost(reason) => return Err(LinkError::Lost(reason.clone())),
            }
            inner.requests.push(request.clone());
            (inner.script.pop_front(), inner.responder.clone())
        };
        let reply = match step {
            Some(Step::Fail(error)) => return Err(error),
            Some(Step::Raw(response)) => return Ok(response),
            Some(Step::Reply(reply)) => reply,
            None => {
                responder.and_then(|responder| responder(&request)).unwrap_or_else(|| default_reply(&request))
            }
        };
        Ok(proto::CallResponse { call_response: Some(reply) })
    }

    fn next_callback(&self, timeout: Option<Duration>) -> Result<Option<LinkCallback>, LinkError> {
        let deadline = timeout.map(|timeout| Instant::now() + timeout);
        let mut inner = self.lock();
        loop {
            if inner.state == LinkState::Closed {
                return Err(LinkError::Closed);
            }
            if let Some(callback) = inner.callbacks.pop_front() {
                return Ok(Some(callback));
            }
            if let LinkState::Lost(reason) = &inner.state {
                return Err(LinkError::Lost(reason.clone()));
            }
            inner = match deadline {
                None => self.changed.wait(inner).unwrap_or_else(PoisonError::into_inner),
                Some(deadline) => {
                    let now = Instant::now();
                    if now >= deadline {
                        return Ok(None);
                    }
                    self.changed.wait_timeout(inner, deadline - now).unwrap_or_else(PoisonError::into_inner).0
                }
            };
        }
    }

    fn respond(&self, id: u64, response: proto::CallbackResponse) -> Result<(), LinkError> {
        let Some(response) = response.callback_response else {
            return Err(LinkError::Failed("callback response without an alternative".to_owned()));
        };
        let mut inner = self.lock();
        inner.responses.push((id, response));
        self.changed.notify_all();
        Ok(())
    }

    fn state(&self) -> LinkState {
        self.lock().state.clone()
    }

    fn close(&self) {
        let mut inner = self.lock();
        inner.state = LinkState::Closed;
        self.changed.notify_all();
    }
}