Skip to main content

microrti_client/
federate.rs

1//! Hand-written companions of the generated [`Callback`] enum and [`FederateAmbassador`] trait.
2
3use crate::callback::{Callback, FederateAmbassador};
4use crate::types::{SupplementalReceiveInfo, SupplementalReflectInfo};
5
6/// The one exception a federate ambassador may raise: something went wrong inside the federate while it
7/// handled a callback.
8///
9/// The RTI ambassador reports it to the RTI as a failed callback response carrying the standard exception
10/// name `FederateInternalError` and this message.
11#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
12#[error("FederateInternalError: {message}")]
13pub struct FederateInternalError {
14    /// Free-form details for humans.
15    pub message: String,
16}
17
18impl FederateInternalError {
19    /// Standard name of the exception.
20    pub const NAME: &'static str = "FederateInternalError";
21
22    /// Creates the error.
23    pub fn new(message: impl Into<String>) -> Self {
24        Self { message: message.into() }
25    }
26}
27
28impl From<String> for FederateInternalError {
29    fn from(message: String) -> Self {
30        Self { message }
31    }
32}
33
34impl From<&str> for FederateInternalError {
35    fn from(message: &str) -> Self {
36        Self::new(message)
37    }
38}
39
40/// Result of every [`FederateAmbassador`] method.
41pub type CallbackResult = Result<(), FederateInternalError>;
42
43/// A federate ambassador that ignores every callback (the `NullFederateAmbassador` of the standard APIs).
44#[derive(Clone, Copy, Debug, Default)]
45pub struct NullFederateAmbassador;
46
47impl FederateAmbassador for NullFederateAmbassador {}
48
49/// Adapts a closure taking the [`Callback`] enum into a [`FederateAmbassador`], for federates that prefer
50/// one `match` over implementing trait methods.
51///
52/// ```
53/// use microrti_client::{Callback, CallbackFn};
54///
55/// let mut discovered = Vec::new();
56/// let _federate = CallbackFn::new(move |callback: Callback| {
57///     if let Callback::DiscoverObjectInstance { object_instance_name, .. } = callback {
58///         discovered.push(object_instance_name);
59///     }
60///     Ok(())
61/// });
62/// ```
63pub struct CallbackFn<F>(F);
64
65impl<F> CallbackFn<F>
66where
67    F: FnMut(Callback) -> CallbackResult,
68{
69    /// Wraps the closure.
70    pub fn new(handler: F) -> Self {
71        Self(handler)
72    }
73}
74
75impl<F> FederateAmbassador for CallbackFn<F>
76where
77    F: FnMut(Callback) -> CallbackResult,
78{
79    fn handle_callback(&mut self, callback: Callback) -> CallbackResult {
80        (self.0)(callback)
81    }
82}
83
84impl<F> std::fmt::Debug for CallbackFn<F> {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.write_str("CallbackFn")
87    }
88}
89
90impl Callback {
91    /// For the two Reflect Attribute Values callbacks (6.11): the producing federate and the conveyed
92    /// regions as one value. `None` for every other callback.
93    pub fn supplemental_reflect_info(&self) -> Option<SupplementalReflectInfo> {
94        match self {
95            Callback::ReflectAttributeValues { producing_federate, sent_regions, .. }
96            | Callback::ReflectAttributeValuesWithTime { producing_federate, sent_regions, .. } => {
97                Some(SupplementalReflectInfo {
98                    producing_federate: producing_federate.clone(),
99                    sent_regions: sent_regions.clone(),
100                })
101            }
102            _ => None,
103        }
104    }
105
106    /// For the Receive Interaction and Receive Directed Interaction callbacks (6.13, 6.15): the producing
107    /// federate and the conveyed regions as one value (directed interactions never convey regions). `None`
108    /// for every other callback.
109    pub fn supplemental_receive_info(&self) -> Option<SupplementalReceiveInfo> {
110        match self {
111            Callback::ReceiveInteraction { producing_federate, sent_regions, .. }
112            | Callback::ReceiveInteractionWithTime { producing_federate, sent_regions, .. } => {
113                Some(SupplementalReceiveInfo {
114                    producing_federate: producing_federate.clone(),
115                    sent_regions: sent_regions.clone(),
116                })
117            }
118            Callback::ReceiveDirectedInteraction { producing_federate, .. }
119            | Callback::ReceiveDirectedInteractionWithTime { producing_federate, .. } => {
120                Some(SupplementalReceiveInfo {
121                    producing_federate: producing_federate.clone(),
122                    sent_regions: None,
123                })
124            }
125            _ => None,
126        }
127    }
128}