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;
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);
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);
}
}
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();
}
}
}
#[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 {
pub fn new(config: RtiConfig) -> Self {
Self::from_rti(Rti::new(config), DEFAULT_TICK_PERIOD)
}
pub fn with_tick_period(config: RtiConfig, tick_period: Duration) -> Self {
Self::from_rti(Rti::new(config), tick_period)
}
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) }) }
}
pub fn link(&self) -> Arc<dyn RtiLink> {
self.inner.hub.link()
}
pub fn ambassador(&self) -> RtiAmbassador {
RtiAmbassador::with_connector(self.clone())
}
pub fn register(&self, scheme: &str) {
crate::link::register_connector(scheme, self.clone());
}
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();
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}");
}
}
first.disconnect().unwrap();
assert!(!first.is_connected());
assert!(second.is_connected());
assert_eq!(first.evoke_callback(Duration::ZERO), Ok(false));
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());
}
}