use std::collections::VecDeque;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak};
use std::thread::{self, JoinHandle, ThreadId};
use std::time::{Duration, Instant};
use microrti_core::{ExceptionKind, HLA_VERSION, RtiError, RtiResult, TimeKind};
use microrti_proto as proto;
pub(crate) use proto::call_request::CallRequest as Call;
pub(crate) use proto::call_response::CallResponse as Reply;
use proto::callback_response::CallbackResponse as CallbackReply;
use crate::callback::{Callback, FederateAmbassador};
use crate::federate::{CallbackResult, FederateInternalError};
use crate::handles::FederateHandle;
use crate::link::{Connectors, LinkCallback, LinkError, LinkFactory, LinkState, RtiLink, global_connectors};
use crate::types::{
CallbackModel, ConfigurationResult, Credentials, FomModule, JoinResult, ResignAction, RtiConfiguration,
};
use crate::wire::{FromWire, ToWire, WireCx, malformed};
macro_rules! service {
(
$(#[$doc:meta])*
fn $name:ident($($arg:ident : $ty:ty),* $(,)?) -> $ret:ty;
$request:ident { $($field:ident : $value:expr),* $(,)? } => $response:ident $(. $result:ident)?
) => {
$(#[$doc])*
pub fn $name(&self, $($arg: $ty),*) -> $crate::RtiResult<$ret> {
let cx = self.wire_cx();
let request = $crate::proto::$request { $($field: $crate::wire::ToWire::to_wire($value, &cx)?),* };
match self.invoke($crate::ambassador::Call::$request(request))? {
$crate::ambassador::Reply::$response(response) => {
$crate::ambassador::service!(@result response, cx $(, $result)?)
}
_ => Err($crate::ambassador::unexpected_response(stringify!($request))),
}
}
};
(@result $response:ident, $cx:ident) => {{
let _ = ($response, $cx);
Ok(())
}};
(@result $response:ident, $cx:ident, $result:ident) => {
$crate::wire::FromWire::from_wire($response.$result, &$cx)
};
}
pub(crate) use service;
pub(crate) fn unexpected_response(request: &str) -> RtiError {
RtiError::internal(format!("the RTI answered {request} with a response of another service"))
}
fn not_allowed(service: &str) -> RtiError {
RtiError::new(
ExceptionKind::CallNotAllowedFromWithinCallback,
format!("{service} cannot be invoked from within a callback"),
)
}
const POLL_INTERVAL: Duration = Duration::from_millis(50);
const JOIN_WAIT: Duration = Duration::from_secs(5);
type BoxedFederate = Box<dyn FederateAmbassador + Send>;
enum LinkSource {
Global,
Connectors(Connectors),
Factory(Box<dyn LinkFactory>),
Link(Mutex<Option<Arc<dyn RtiLink>>>),
}
impl LinkSource {
fn open(&self, configuration: &RtiConfiguration) -> Result<Arc<dyn RtiLink>, LinkError> {
match self {
LinkSource::Global => global_connectors().open(configuration),
LinkSource::Connectors(connectors) => connectors.open(configuration),
LinkSource::Factory(factory) => factory.open(configuration),
LinkSource::Link(slot) => {
slot.lock().unwrap_or_else(PoisonError::into_inner).take().ok_or_else(|| {
LinkError::Unreachable(
"the link given to RtiAmbassador::with_link was already used".to_owned(),
)
})
}
}
}
}
struct State {
link: Option<Arc<dyn RtiLink>>,
connecting: bool,
generation: u64,
model: CallbackModel,
callbacks_enabled: bool,
time_kind: Option<TimeKind>,
callback_time: Option<TimeKind>,
joining: u32,
in_callback: Option<ThreadId>,
lost: Option<String>,
pending: VecDeque<LinkCallback>,
thread: Option<JoinHandle<()>>,
save_in_progress: bool,
restore_in_progress: bool,
}
impl State {
fn within_callback(&self) -> bool {
self.in_callback == Some(thread::current().id())
}
fn leave_federation(&mut self) {
self.time_kind = None;
self.save_in_progress = false;
self.restore_in_progress = false;
}
fn leave_connection(&mut self) -> Option<Arc<dyn RtiLink>> {
self.leave_federation();
self.callback_time = None;
self.pending.clear();
self.link.take()
}
fn check_save_restore(&self) -> RtiResult<()> {
if self.save_in_progress {
return Err(RtiError::new(ExceptionKind::SaveInProgress, "a federate save is in progress"));
}
if self.restore_in_progress {
return Err(RtiError::new(ExceptionKind::RestoreInProgress, "a federate restore is in progress"));
}
Ok(())
}
}
enum Item {
Lost(String),
Callback(Box<LinkCallback>),
}
enum After {
Nothing,
Resigned,
Severed,
}
struct Shared {
source: LinkSource,
state: Mutex<State>,
changed: Condvar,
federate: Mutex<Option<BoxedFederate>>,
}
impl Shared {
fn new(source: LinkSource) -> Self {
Shared {
source,
state: Mutex::new(State {
link: None,
connecting: false,
generation: 0,
model: CallbackModel::Evoked,
callbacks_enabled: true,
time_kind: None,
callback_time: None,
joining: 0,
in_callback: None,
lost: None,
pending: VecDeque::new(),
thread: None,
save_in_progress: false,
restore_in_progress: false,
}),
changed: Condvar::new(),
federate: Mutex::new(None),
}
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn lock_federate(&self) -> MutexGuard<'_, Option<BoxedFederate>> {
self.federate.lock().unwrap_or_else(PoisonError::into_inner)
}
fn mark_lost(&self, link: &Arc<dyn RtiLink>, reason: String) {
{
let mut state = self.lock();
if !state.link.as_ref().is_some_and(|current| Arc::ptr_eq(current, link)) {
return;
}
state.leave_connection();
state.lost = Some(reason);
self.changed.notify_all();
}
link.close();
}
fn sever(&self, link: &Arc<dyn RtiLink>) {
{
let mut state = self.lock();
if !state.link.as_ref().is_some_and(|current| Arc::ptr_eq(current, link)) {
return;
}
state.leave_connection();
self.changed.notify_all();
}
link.close();
}
fn release(&self) {
let (link, thread, on_callback_thread) = {
let mut state = self.lock();
state.generation += 1;
state.lost = None;
state.callbacks_enabled = true;
let link = state.leave_connection();
let thread = state.thread.take();
self.changed.notify_all();
(link, thread, state.within_callback())
};
if let Some(link) = link {
link.close();
}
if let Some(thread) = thread
&& thread.thread().id() != thread::current().id()
{
let _ = thread.join();
}
if !on_callback_thread {
let federate = self.lock_federate().take();
drop(federate);
}
}
fn take_deliverable(&self, generation: u64, wait: Duration) -> Option<Item> {
let deadline = Instant::now() + wait;
loop {
let link = {
let mut state = self.lock();
loop {
if state.generation != generation {
return None;
}
if state.callbacks_enabled {
if let Some(reason) = state.lost.take() {
state.in_callback = Some(thread::current().id());
return Some(Item::Lost(reason));
}
if let Some(callback) = state.pending.pop_front() {
state.in_callback = Some(thread::current().id());
return Some(Item::Callback(Box::new(callback)));
}
if let Some(link) = state.link.clone() {
break link;
}
}
let now = Instant::now();
if now >= deadline {
return None;
}
state = self
.changed
.wait_timeout(state, deadline - now)
.unwrap_or_else(PoisonError::into_inner)
.0;
}
};
let remaining = deadline.saturating_duration_since(Instant::now());
match link.next_callback(Some(remaining.min(POLL_INTERVAL))) {
Ok(Some(callback)) => {
let mut state = self.lock();
if state.generation == generation {
state.pending.push_back(callback);
}
}
Ok(None) => {
if Instant::now() >= deadline {
return None;
}
}
Err(LinkError::Lost(reason)) => self.mark_lost(&link, reason),
Err(error) => self.mark_lost(&link, error.to_string()),
}
}
}
fn has_pending(&self, generation: u64) -> bool {
let link = {
let state = self.lock();
if state.generation != generation {
return false;
}
if !state.pending.is_empty() || state.lost.is_some() {
return true;
}
match state.link.clone() {
Some(link) => link,
None => return false,
}
};
match link.next_callback(Some(Duration::ZERO)) {
Ok(Some(callback)) => {
let mut state = self.lock();
if state.generation == generation {
state.pending.push_back(callback);
}
true
}
Ok(None) => false,
Err(LinkError::Lost(reason)) => {
self.mark_lost(&link, reason);
true
}
Err(error) => {
self.mark_lost(&link, error.to_string());
true
}
}
}
fn deliver(&self, federate: &mut Option<BoxedFederate>, item: Item) {
match item {
Item::Lost(fault_description) => {
if let Some(federate) = federate.as_mut()
&& let Err(error) = run(federate, Callback::ConnectionLost { fault_description })
{
tracing::warn!(%error, "the Connection Lost callback failed");
}
}
Item::Callback(delivery) => self.deliver_request(federate, *delivery),
}
self.lock().in_callback = None;
self.changed.notify_all();
}
fn deliver_request(&self, federate: &mut Option<BoxedFederate>, delivery: LinkCallback) {
let (link, cx) = {
let mut state = self.lock();
let deadline = Instant::now() + JOIN_WAIT;
while state.joining > 0 {
let now = Instant::now();
if now >= deadline {
break;
}
state = self
.changed
.wait_timeout(state, deadline - now)
.unwrap_or_else(PoisonError::into_inner)
.0;
}
(state.link.clone(), WireCx { time: state.callback_time })
};
let decoded = match delivery.request.callback_request {
Some(wire) => Callback::from_wire(wire, &cx)
.map_err(|error| FederateInternalError::new(format!("cannot decode the callback: {error}"))),
None => Err(FederateInternalError::new("callback request without a known alternative")),
};
let mut after = After::Nothing;
let outcome = match decoded {
Ok(callback) => {
after = self.note(&callback);
match federate.as_mut() {
Some(federate) => run(federate, callback),
None => Ok(()),
}
}
Err(error) => Err(error),
};
let response = match outcome {
Ok(()) => CallbackReply::CallbackSucceeded(proto::CallbackSucceeded {}),
Err(error) => {
tracing::warn!(%error, "a callback failed");
CallbackReply::CallbackFailed(proto::ExceptionData {
exception_name: FederateInternalError::NAME.to_owned(),
details: error.message,
})
}
};
if let Some(link) = &link {
let response = proto::CallbackResponse { callback_response: Some(response) };
if let Err(error) = link.respond(delivery.id, response) {
tracing::debug!(%error, "could not send a callback response");
}
}
match after {
After::Nothing => {}
After::Resigned => self.lock().leave_federation(),
After::Severed => {
if let Some(link) = &link {
self.sever(link);
}
}
}
}
fn note(&self, callback: &Callback) -> After {
let mut state = self.lock();
match callback {
Callback::InitiateFederateSave { .. } | Callback::InitiateFederateSaveWithTime { .. } => {
state.save_in_progress = true;
}
Callback::FederationSaved | Callback::FederationNotSaved { .. } => state.save_in_progress = false,
Callback::FederationRestoreBegun => state.restore_in_progress = true,
Callback::FederationRestored | Callback::FederationNotRestored { .. } => {
state.restore_in_progress = false;
}
Callback::FederateResigned { .. } => return After::Resigned,
Callback::ConnectionLost { .. } => return After::Severed,
_ => {}
}
After::Nothing
}
}
fn run(federate: &mut BoxedFederate, callback: Callback) -> CallbackResult {
match catch_unwind(AssertUnwindSafe(|| federate.handle_callback(callback))) {
Ok(result) => result,
Err(_) => Err(FederateInternalError::new("the federate ambassador panicked")),
}
}
fn immediate_loop(shared: &Shared, generation: u64) {
loop {
{
let state = shared.lock();
if state.generation != generation || (state.link.is_none() && state.lost.is_none()) {
return;
}
}
let mut federate = shared.lock_federate();
if let Some(item) = shared.take_deliverable(generation, POLL_INTERVAL) {
shared.deliver(&mut federate, item);
}
}
}
struct Owner {
shared: Arc<Shared>,
}
impl Drop for Owner {
fn drop(&mut self) {
self.shared.release();
}
}
#[derive(Clone)]
pub struct RtiAmbassador {
owner: Arc<Owner>,
}
#[derive(Clone)]
pub struct WeakRtiAmbassador {
owner: Weak<Owner>,
}
impl WeakRtiAmbassador {
pub fn upgrade(&self) -> Option<RtiAmbassador> {
self.owner.upgrade().map(|owner| RtiAmbassador { owner })
}
}
impl std::fmt::Debug for WeakRtiAmbassador {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("WeakRtiAmbassador")
}
}
impl Default for RtiAmbassador {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for RtiAmbassador {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let state = self.shared().lock();
f.debug_struct("RtiAmbassador")
.field("connected", &state.link.is_some())
.field("callback_model", &state.model)
.field("callbacks_enabled", &state.callbacks_enabled)
.field("time_kind", &state.time_kind)
.finish()
}
}
impl RtiAmbassador {
fn from_source(source: LinkSource) -> Self {
RtiAmbassador { owner: Arc::new(Owner { shared: Arc::new(Shared::new(source)) }) }
}
pub fn new() -> Self {
Self::from_source(LinkSource::Global)
}
pub fn with_connectors(connectors: Connectors) -> Self {
Self::from_source(LinkSource::Connectors(connectors))
}
pub fn with_connector(factory: impl LinkFactory + 'static) -> Self {
Self::from_source(LinkSource::Factory(Box::new(factory)))
}
pub fn with_link(link: Arc<dyn RtiLink>) -> Self {
Self::from_source(LinkSource::Link(Mutex::new(Some(link))))
}
pub fn downgrade(&self) -> WeakRtiAmbassador {
WeakRtiAmbassador { owner: Arc::downgrade(&self.owner) }
}
fn shared(&self) -> &Arc<Shared> {
&self.owner.shared
}
pub fn hla_version(&self) -> &'static str {
HLA_VERSION
}
pub fn is_connected(&self) -> bool {
let Some(link) = self.shared().lock().link.clone() else {
return false;
};
match link.state() {
LinkState::Open => true,
LinkState::Lost(reason) => {
self.shared().mark_lost(&link, reason);
false
}
LinkState::Closed => {
self.shared().mark_lost(&link, "the link to the RTI was closed".to_owned());
false
}
}
}
pub fn callback_model(&self) -> Option<CallbackModel> {
let state = self.shared().lock();
state.link.as_ref().map(|_| state.model)
}
pub fn time_kind(&self) -> RtiResult<TimeKind> {
let state = self.shared().lock();
if state.link.is_none() {
return Err(RtiError::new(ExceptionKind::NotConnected, "not connected to an RTI"));
}
state.time_kind.ok_or_else(|| {
RtiError::new(ExceptionKind::FederateNotExecutionMember, "not joined to a federation execution")
})
}
pub(crate) fn wire_cx(&self) -> WireCx {
WireCx { time: self.shared().lock().time_kind }
}
pub(crate) fn invoke(&self, request: Call) -> RtiResult<Reply> {
let Some(link) = self.shared().lock().link.clone() else {
return Err(RtiError::new(ExceptionKind::NotConnected, "not connected to an RTI"));
};
match link.call(proto::CallRequest { call_request: Some(request) }) {
Ok(response) => match response.call_response {
Some(Reply::ExceptionData(data)) => Err(RtiError::from_exception_data(&data)),
Some(reply) => Ok(reply),
None => Err(malformed("call response without a known alternative")),
},
Err(LinkError::Lost(reason)) => {
let error = RtiError::new(ExceptionKind::NotConnected, format!("connection lost: {reason}"));
self.shared().mark_lost(&link, reason);
Err(error)
}
Err(LinkError::Closed) => {
Err(RtiError::new(ExceptionKind::NotConnected, "the link to the RTI is closed"))
}
Err(error) => Err(RtiError::internal(error.to_string())),
}
}
fn forbid_within_callback(&self, service: &str) -> RtiResult<()> {
if self.shared().lock().within_callback() { Err(not_allowed(service)) } else { Ok(()) }
}
pub fn connect(
&self,
federate_ambassador: impl FederateAmbassador + Send + 'static,
callback_model: CallbackModel,
) -> RtiResult<ConfigurationResult> {
self.connect_impl(Box::new(federate_ambassador), callback_model, None, None)
}
pub fn connect_with_credentials(
&self,
federate_ambassador: impl FederateAmbassador + Send + 'static,
callback_model: CallbackModel,
credentials: &Credentials,
) -> RtiResult<ConfigurationResult> {
self.connect_impl(Box::new(federate_ambassador), callback_model, None, Some(credentials))
}
pub fn connect_with_configuration(
&self,
federate_ambassador: impl FederateAmbassador + Send + 'static,
callback_model: CallbackModel,
configuration: &RtiConfiguration,
) -> RtiResult<ConfigurationResult> {
self.connect_impl(Box::new(federate_ambassador), callback_model, Some(configuration), None)
}
pub fn connect_with_configuration_and_credentials(
&self,
federate_ambassador: impl FederateAmbassador + Send + 'static,
callback_model: CallbackModel,
configuration: &RtiConfiguration,
credentials: &Credentials,
) -> RtiResult<ConfigurationResult> {
self.connect_impl(
Box::new(federate_ambassador),
callback_model,
Some(configuration),
Some(credentials),
)
}
fn connect_impl(
&self,
federate: BoxedFederate,
model: CallbackModel,
configuration: Option<&RtiConfiguration>,
credentials: Option<&Credentials>,
) -> RtiResult<ConfigurationResult> {
let shared = self.shared();
let stale_thread = {
let mut state = shared.lock();
if state.within_callback() {
return Err(not_allowed("Connect"));
}
if state.link.is_some() || state.connecting {
return Err(RtiError::new(
ExceptionKind::AlreadyConnected,
"this RTI ambassador is already connected",
));
}
state.connecting = true;
state.lost = None;
state.thread.take()
};
if let Some(thread) = stale_thread {
let _ = thread.join();
}
let opened = self.open(configuration, credentials);
let mut federate_slot = shared.lock_federate();
let mut state = shared.lock();
state.connecting = false;
let (link, result) = opened?;
state.generation += 1;
state.model = model;
state.callbacks_enabled = true;
state.lost = None;
state.leave_connection();
if model == CallbackModel::Immediate {
let generation = state.generation;
let thread_shared = Arc::clone(shared);
let spawned = thread::Builder::new()
.name("microrti-callbacks".to_owned())
.spawn(move || immediate_loop(&thread_shared, generation));
match spawned {
Ok(thread) => state.thread = Some(thread),
Err(error) => {
drop(state);
link.close();
return Err(RtiError::internal(format!("cannot start the callback thread: {error}")));
}
}
}
state.link = Some(link);
*federate_slot = Some(federate);
shared.changed.notify_all();
Ok(result)
}
fn open(
&self,
configuration: Option<&RtiConfiguration>,
credentials: Option<&Credentials>,
) -> RtiResult<(Arc<dyn RtiLink>, ConfigurationResult)> {
let cx = WireCx::default();
let request = match (configuration, credentials) {
(None, None) => Call::ConnectRequest(proto::ConnectRequest {}),
(None, Some(credentials)) => {
Call::ConnectWithCredentialsRequest(proto::ConnectWithCredentialsRequest {
credentials: credentials.to_wire(&cx)?,
})
}
(Some(configuration), None) => {
Call::ConnectWithConfigurationRequest(proto::ConnectWithConfigurationRequest {
rti_configuration: configuration.to_wire(&cx)?,
})
}
(Some(configuration), Some(credentials)) => Call::ConnectWithConfigurationAndCredentialsRequest(
proto::ConnectWithConfigurationAndCredentialsRequest {
rti_configuration: configuration.to_wire(&cx)?,
credentials: credentials.to_wire(&cx)?,
},
),
};
let connection_failed =
|error: LinkError| RtiError::new(ExceptionKind::ConnectionFailed, error.to_string());
let default_configuration = RtiConfiguration::default();
let link = self
.shared()
.source
.open(configuration.unwrap_or(&default_configuration))
.map_err(connection_failed)?;
let outcome = match link.call(proto::CallRequest { call_request: Some(request) }) {
Ok(response) => match (configuration.is_some(), credentials.is_some(), response.call_response) {
(_, _, Some(Reply::ExceptionData(data))) => Err(RtiError::from_exception_data(&data)),
(false, false, Some(Reply::ConnectResponse(response))) => Ok(response.configuration_result),
(false, true, Some(Reply::ConnectWithCredentialsResponse(response))) => {
Ok(response.configuration_result)
}
(true, false, Some(Reply::ConnectWithConfigurationResponse(response))) => {
Ok(response.configuration_result)
}
(true, true, Some(Reply::ConnectWithConfigurationAndCredentialsResponse(response))) => {
Ok(response.configuration_result)
}
_ => Err(unexpected_response("Connect")),
},
Err(error) => Err(connection_failed(error)),
};
match outcome.and_then(|result| ConfigurationResult::from_wire(result, &cx)) {
Ok(result) => Ok((link, result)),
Err(error) => {
link.close();
Err(error)
}
}
}
pub fn disconnect(&self) -> RtiResult<()> {
let shared = self.shared();
let link = {
let state = shared.lock();
if state.within_callback() {
return Err(not_allowed("Disconnect"));
}
state.link.clone()
};
if let Some(link) = &link {
let request = Call::DisconnectRequest(proto::DisconnectRequest {});
match link.call(proto::CallRequest { call_request: Some(request) }) {
Ok(response) => match response.call_response {
Some(Reply::DisconnectResponse(_)) => {}
Some(Reply::ExceptionData(data)) => return Err(RtiError::from_exception_data(&data)),
_ => return Err(unexpected_response("DisconnectRequest")),
},
Err(LinkError::Lost(_) | LinkError::Closed) => {}
Err(error) => return Err(RtiError::internal(error.to_string())),
}
}
shared.release();
Ok(())
}
pub fn join_federation_execution(
&self,
federate_type: &str,
federation_name: &str,
) -> RtiResult<JoinResult> {
let cx = self.wire_cx();
self.join(Call::JoinFederationExecutionRequest(proto::JoinFederationExecutionRequest {
federate_type: federate_type.to_wire(&cx)?,
federation_name: federation_name.to_wire(&cx)?,
}))
}
pub fn join_federation_execution_with_modules(
&self,
federate_type: &str,
federation_name: &str,
additional_fom_modules: &[FomModule],
) -> RtiResult<JoinResult> {
let cx = self.wire_cx();
self.join(Call::JoinFederationExecutionWithModulesRequest(
proto::JoinFederationExecutionWithModulesRequest {
federate_type: federate_type.to_wire(&cx)?,
federation_name: federation_name.to_wire(&cx)?,
additional_fom_modules: additional_fom_modules.to_wire(&cx)?,
},
))
}
pub fn join_federation_execution_with_name(
&self,
federate_name: &str,
federate_type: &str,
federation_name: &str,
) -> RtiResult<JoinResult> {
let cx = self.wire_cx();
self.join(Call::JoinFederationExecutionWithNameRequest(
proto::JoinFederationExecutionWithNameRequest {
federate_name: federate_name.to_wire(&cx)?,
federate_type: federate_type.to_wire(&cx)?,
federation_name: federation_name.to_wire(&cx)?,
},
))
}
pub fn join_federation_execution_with_name_and_modules(
&self,
federate_name: &str,
federate_type: &str,
federation_name: &str,
additional_fom_modules: &[FomModule],
) -> RtiResult<JoinResult> {
let cx = self.wire_cx();
self.join(Call::JoinFederationExecutionWithNameAndModulesRequest(
proto::JoinFederationExecutionWithNameAndModulesRequest {
federate_name: federate_name.to_wire(&cx)?,
federate_type: federate_type.to_wire(&cx)?,
federation_name: federation_name.to_wire(&cx)?,
additional_fom_modules: additional_fom_modules.to_wire(&cx)?,
},
))
}
fn join(&self, request: Call) -> RtiResult<JoinResult> {
self.forbid_within_callback("Join Federation Execution")?;
let shared = self.shared();
shared.lock().joining += 1;
let outcome = self.exchange_join(request);
let mut state = shared.lock();
state.joining -= 1;
if let Ok(joined) = &outcome {
state.leave_federation();
state.time_kind = Some(joined.time_kind);
state.callback_time = Some(joined.time_kind);
}
shared.changed.notify_all();
drop(state);
outcome
}
fn exchange_join(&self, request: Call) -> RtiResult<JoinResult> {
let result = match self.invoke(request)? {
Reply::JoinFederationExecutionResponse(response) => response.result,
Reply::JoinFederationExecutionWithModulesResponse(response) => response.result,
Reply::JoinFederationExecutionWithNameResponse(response) => response.result,
Reply::JoinFederationExecutionWithNameAndModulesResponse(response) => response.result,
_ => return Err(unexpected_response("JoinFederationExecution")),
};
decode_join_result(result).inspect_err(|_| {
let undo =
proto::ResignFederationExecutionRequest { resign_action: ResignAction::NoAction.to_i32() };
if let Err(resign_error) = self.invoke(Call::ResignFederationExecutionRequest(undo)) {
tracing::warn!(error = %resign_error, "could not resign after a join that cannot be used");
}
})
}
pub fn resign_federation_execution(&self, resign_action: ResignAction) -> RtiResult<()> {
self.forbid_within_callback("Resign Federation Execution")?;
let cx = self.wire_cx();
let request = proto::ResignFederationExecutionRequest { resign_action: resign_action.to_wire(&cx)? };
match self.invoke(Call::ResignFederationExecutionRequest(request))? {
Reply::ResignFederationExecutionResponse(_) => {
self.shared().lock().leave_federation();
Ok(())
}
_ => Err(unexpected_response("ResignFederationExecutionRequest")),
}
}
pub fn evoke_callback(&self, approximate_minimum_time: Duration) -> RtiResult<bool> {
self.evoke(approximate_minimum_time, None)
}
pub fn evoke_multiple_callbacks(
&self,
approximate_minimum_time: Duration,
approximate_maximum_time: Duration,
) -> RtiResult<bool> {
self.evoke(approximate_minimum_time, Some(approximate_maximum_time))
}
fn evoke(&self, minimum: Duration, maximum: Option<Duration>) -> RtiResult<bool> {
let shared = self.shared();
let generation = {
let state = shared.lock();
if state.within_callback() {
return Err(not_allowed("Evoke Callback"));
}
if state.link.is_some() && state.model == CallbackModel::Immediate {
return Ok(false);
}
state.generation
};
let start = Instant::now();
let minimum_deadline = start + minimum;
let mut federate = shared.lock_federate();
match maximum {
None => {
if let Some(item) = shared.take_deliverable(generation, minimum) {
shared.deliver(&mut federate, item);
}
}
Some(maximum) => {
let maximum_deadline = start + maximum.max(minimum);
loop {
let wait = minimum_deadline.saturating_duration_since(Instant::now());
match shared.take_deliverable(generation, wait) {
Some(item) => shared.deliver(&mut federate, item),
None => {
if Instant::now() >= minimum_deadline || shared.lock().generation != generation {
break;
}
}
}
if Instant::now() >= maximum_deadline {
break;
}
}
}
}
Ok(shared.has_pending(generation))
}
pub fn enable_callbacks(&self) -> RtiResult<()> {
let shared = self.shared();
let mut state = shared.lock();
state.check_save_restore()?;
state.callbacks_enabled = true;
shared.changed.notify_all();
Ok(())
}
pub fn disable_callbacks(&self) -> RtiResult<()> {
let shared = self.shared();
let mut state = shared.lock();
state.check_save_restore()?;
state.callbacks_enabled = false;
shared.changed.notify_all();
let current = thread::current().id();
while state.in_callback.is_some_and(|busy| busy != current) {
state = shared.changed.wait(state).unwrap_or_else(PoisonError::into_inner);
}
Ok(())
}
}
fn decode_join_result(result: Option<proto::JoinResult>) -> RtiResult<JoinResult> {
let result = result.ok_or_else(|| malformed("missing join result"))?;
let Some(time_kind) = TimeKind::from_name(&result.logical_time_implementation_name) else {
return Err(RtiError::new(
ExceptionKind::CouldNotCreateLogicalTimeFactory,
format!(
"the federation execution uses logical time implementation {:?}; this API provides {} and {}",
result.logical_time_implementation_name,
TimeKind::Integer64,
TimeKind::Float64
),
));
};
Ok(JoinResult {
federate_handle: FederateHandle::from_wire(result.federate_handle, &WireCx::default())?,
logical_time_implementation_name: result.logical_time_implementation_name,
time_kind,
})
}