Skip to main content

microrti_client/
types.rs

1//! Value types of the federate API: sets and maps of handles, enumerations and the small records that
2//! services take or return. They mirror `datatypes.proto` with Rust types; the conversions to and from the
3//! protobuf messages live in `wire.rs`.
4
5use std::collections::{BTreeMap, BTreeSet};
6use std::fmt;
7use std::path::PathBuf;
8
9use bytes::Bytes;
10use microrti_core::{ExceptionKind, LogicalTime, RtiError, RtiResult, TimeKind};
11use microrti_proto as proto;
12
13use crate::handles::{
14    AttributeHandle, DimensionHandle, FederateHandle, InteractionClassHandle, MessageRetractionHandle,
15    ParameterHandle, RegionHandle,
16};
17use crate::wire::{FromWire, ToWire, WireCx, malformed};
18
19/// Set of federate handles.
20pub type FederateHandleSet = BTreeSet<FederateHandle>;
21/// Set of attribute handles.
22pub type AttributeHandleSet = BTreeSet<AttributeHandle>;
23/// Set of interaction class handles.
24pub type InteractionClassHandleSet = BTreeSet<InteractionClassHandle>;
25/// Set of dimension handles.
26pub type DimensionHandleSet = BTreeSet<DimensionHandle>;
27/// Set of region handles.
28pub type RegionHandleSet = BTreeSet<RegionHandle>;
29/// Attribute values keyed by attribute handle. A value is the encoded bytes of the attribute's datatype.
30pub type AttributeHandleValueMap = BTreeMap<AttributeHandle, Bytes>;
31/// Parameter values keyed by parameter handle. A value is the encoded bytes of the parameter's datatype.
32pub type ParameterHandleValueMap = BTreeMap<ParameterHandle, Bytes>;
33/// Collection of attribute set / region set pairs used by the DDM services of clause 9.
34pub type AttributeSetRegionSetPairList = Vec<AttributeSetRegionSetPair>;
35/// The ranges of one region as conveyed with a reflected update or a received interaction (9.1.7).
36pub type ConveyedRegion = BTreeMap<DimensionHandle, RangeBounds>;
37/// The regions conveyed with a reflected update or a received interaction.
38pub type ConveyedRegionSet = BTreeSet<ConveyedRegion>;
39
40macro_rules! wire_enums {
41    ($(
42        $(#[$doc:meta])*
43        $name:ident { $( $(#[$vdoc:meta])* $variant:ident ),+ $(,)? }
44    )+) => {$(
45        $(#[$doc])*
46        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
47        pub enum $name {
48            $( $(#[$vdoc])* $variant, )+
49        }
50
51        impl $name {
52            /// Every value, in the order of the standard's enumeration.
53            pub const ALL: &'static [$name] = &[$($name::$variant),+];
54
55            pub(crate) fn to_i32(self) -> i32 {
56                match self {
57                    $($name::$variant => proto::$name::$variant as i32,)+
58                }
59            }
60
61            pub(crate) fn from_i32(value: i32) -> RtiResult<Self> {
62                match proto::$name::try_from(value) {
63                    $(Ok(proto::$name::$variant) => Ok($name::$variant),)+
64                    Err(_) => Err(malformed(format!(concat!("unknown ", stringify!($name), " value {}"), value))),
65                }
66            }
67        }
68
69        impl ToWire<i32> for $name {
70            fn to_wire(self, _: &WireCx) -> RtiResult<i32> {
71                Ok(self.to_i32())
72            }
73        }
74
75        impl FromWire<i32> for $name {
76            fn from_wire(wire: i32, _: &WireCx) -> RtiResult<Self> {
77                Self::from_i32(wire)
78            }
79        }
80    )+};
81}
82
83wire_enums! {
84    /// How callbacks reach the federate ambassador (4.2, 10.57 to 10.60).
85    CallbackModel {
86        /// Callbacks wait until the federate calls Evoke Callback or Evoke Multiple Callbacks.
87        Evoked,
88        /// Callbacks are delivered as they arrive, on a thread owned by the RTI ambassador.
89        Immediate,
90    }
91
92    /// Outcome of the additional settings passed to Connect (4.2).
93    AdditionalSettingsResultCode {
94        /// The RTI did not look at the settings.
95        SettingsIgnored,
96        /// The RTI could not parse the settings; the connection was made anyway.
97        SettingsFailedToParse,
98        /// The RTI applied the settings.
99        SettingsApplied,
100    }
101
102    /// What the RTI does with a federate's objects and attributes when it resigns (4.12).
103    ResignAction {
104        /// Give up ownership of every owned instance attribute.
105        UnconditionallyDivestAttributes,
106        /// Delete every object instance whose deletion privilege the federate holds.
107        DeleteObjects,
108        /// Cancel the ownership acquisitions the federate has pending.
109        CancelPendingOwnershipAcquisitions,
110        /// Delete the objects, then divest what remains.
111        DeleteObjectsThenDivest,
112        /// Cancel pending acquisitions, delete the objects, then divest what remains.
113        CancelThenDeleteThenDivest,
114        /// Do none of the above.
115        NoAction,
116    }
117
118    /// Why a synchronization point could not be registered (4.15).
119    SynchronizationPointFailureReason {
120        /// The label is already in use in the federation execution.
121        SynchronizationPointLabelNotUnique,
122        /// A federate of the synchronization set is not joined.
123        SynchronizationSetMemberNotJoined,
124    }
125
126    /// Why a federation save did not complete (4.23).
127    SaveFailureReason {
128        /// The RTI could not save its own state.
129        RtiUnableToSave,
130        /// A federate reported that its save failed.
131        FederateReportedFailureDuringSave,
132        /// A federate resigned while the save was in progress.
133        FederateResignedDuringSave,
134        /// The RTI detected a failure of a federate.
135        RtiDetectedFailureDuringSave,
136        /// The requested save time could not be honored.
137        SaveTimeCannotBeHonored,
138        /// The save was aborted on request.
139        SaveAborted,
140    }
141
142    /// Why a federation restore did not complete (4.32).
143    RestoreFailureReason {
144        /// The RTI could not restore its own state.
145        RtiUnableToRestore,
146        /// A federate reported that its restore failed.
147        FederateReportedFailureDuringRestore,
148        /// A federate resigned while the restore was in progress.
149        FederateResignedDuringRestore,
150        /// The RTI detected a failure of a federate.
151        RtiDetectedFailureDuringRestore,
152        /// The restore was aborted on request.
153        RestoreAborted,
154    }
155
156    /// Progress of a federate in a federation save (4.26).
157    SaveStatus {
158        /// No save is in progress.
159        NoSaveInProgress,
160        /// The federate was told to save and has not started.
161        FederateInstructedToSave,
162        /// The federate is saving.
163        FederateSaving,
164        /// The federate is done and waits for the rest of the federation.
165        FederateWaitingForFederationToSave,
166    }
167
168    /// Progress of a federate in a federation restore (4.35).
169    RestoreStatus {
170        /// No restore is in progress.
171        NoRestoreInProgress,
172        /// A restore was requested and is not confirmed yet.
173        FederateRestoreRequestPending,
174        /// The federate waits for the restore to begin.
175        FederateWaitingForRestoreToBegin,
176        /// The federate is ready to restore.
177        FederatePreparedToRestore,
178        /// The federate is restoring.
179        FederateRestoring,
180        /// The federate is done and waits for the rest of the federation.
181        FederateWaitingForFederationToRestore,
182    }
183
184    /// Message ordering (8.1).
185    OrderType {
186        /// Receive order.
187        Receive,
188        /// Timestamp order.
189        Timestamp,
190    }
191
192    /// The service groups of clauses 4 to 10, as used by Normalize Service Group (10.29).
193    ServiceGroup {
194        /// Clause 4.
195        FederationManagement,
196        /// Clause 5.
197        DeclarationManagement,
198        /// Clause 6.
199        ObjectManagement,
200        /// Clause 7.
201        OwnershipManagement,
202        /// Clause 8.
203        TimeManagement,
204        /// Clause 9.
205        DataDistributionManagement,
206        /// Clause 10.
207        SupportServices,
208    }
209}
210
211/// `CallbackModel` values arriving from configuration files or other languages are validated here: anything
212/// else than the two standard models is an `UnsupportedCallbackModel`.
213impl TryFrom<i32> for CallbackModel {
214    type Error = RtiError;
215
216    fn try_from(value: i32) -> RtiResult<Self> {
217        Self::from_i32(value).map_err(|_| {
218            RtiError::new(
219                ExceptionKind::UnsupportedCallbackModel,
220                format!("callback model {value} is not supported"),
221            )
222        })
223    }
224}
225
226/// Lower and upper bound of a range on one dimension (9.1).
227#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
228pub struct RangeBounds {
229    /// Lower bound.
230    pub lower: u32,
231    /// Upper bound.
232    pub upper: u32,
233}
234
235impl RangeBounds {
236    /// Creates range bounds.
237    pub const fn new(lower: u32, upper: u32) -> Self {
238        Self { lower, upper }
239    }
240}
241
242/// A set of attributes together with the set of regions used for them.
243#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
244pub struct AttributeSetRegionSetPair {
245    /// The attributes.
246    pub attributes: AttributeHandleSet,
247    /// The regions associated with each of these attributes.
248    pub regions: RegionHandleSet,
249}
250
251impl AttributeSetRegionSetPair {
252    /// Creates a pair.
253    pub fn new(attributes: AttributeHandleSet, regions: RegionHandleSet) -> Self {
254        Self { attributes, regions }
255    }
256}
257
258/// The optional arguments of Connect that select and tune the RTI (4.2). Built with the `with_*` methods.
259#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
260pub struct RtiConfiguration {
261    configuration_name: String,
262    rti_address: String,
263    additional_settings: String,
264}
265
266impl RtiConfiguration {
267    /// A configuration with every part empty, which selects the defaults.
268    pub fn new() -> Self {
269        Self::default()
270    }
271
272    /// Sets the name of a configuration known to the RTI.
273    pub fn with_configuration_name(mut self, configuration_name: impl Into<String>) -> Self {
274        self.configuration_name = configuration_name.into();
275        self
276    }
277
278    /// Sets the address used to locate the RTI. Its scheme selects the connector (see
279    /// [`Connectors`](crate::Connectors)).
280    pub fn with_rti_address(mut self, rti_address: impl Into<String>) -> Self {
281        self.rti_address = rti_address.into();
282        self
283    }
284
285    /// Sets implementation specific settings; the RTI reports what it did with them in the
286    /// [`ConfigurationResult`].
287    pub fn with_additional_settings(mut self, additional_settings: impl Into<String>) -> Self {
288        self.additional_settings = additional_settings.into();
289        self
290    }
291
292    /// Name of the configuration, empty for the default.
293    pub fn configuration_name(&self) -> &str {
294        &self.configuration_name
295    }
296
297    /// Address of the RTI, empty for the default.
298    pub fn rti_address(&self) -> &str {
299        &self.rti_address
300    }
301
302    /// Implementation specific settings, possibly empty.
303    pub fn additional_settings(&self) -> &str {
304        &self.additional_settings
305    }
306}
307
308/// What the RTI did with the [`RtiConfiguration`] passed to Connect (4.2).
309#[derive(Clone, Debug, PartialEq, Eq, Hash)]
310pub struct ConfigurationResult {
311    /// The named configuration was found and used.
312    pub configuration_used: bool,
313    /// The RTI address was used.
314    pub address_used: bool,
315    /// What happened to the additional settings.
316    pub additional_settings_result_code: AdditionalSettingsResultCode,
317    /// Human readable details, possibly empty.
318    pub message: String,
319}
320
321/// Credentials presented to the RTI's authorization service by Connect (12.5).
322#[derive(Clone, PartialEq, Eq, Hash)]
323pub struct Credentials {
324    credentials_type: String,
325    data: Bytes,
326}
327
328impl Credentials {
329    /// Type name of the predefined empty credentials.
330    pub const NO_CREDENTIALS: &'static str = "HLAnoCredentials";
331    /// Type name of the predefined plain text password credentials (12.6).
332    pub const PLAIN_TEXT_PASSWORD: &'static str = "HLAplainTextPassword";
333
334    /// Credentials of any type, with the data the authorization service of the RTI expects for it.
335    pub fn new(credentials_type: impl Into<String>, data: impl Into<Bytes>) -> Self {
336        Self { credentials_type: credentials_type.into(), data: data.into() }
337    }
338
339    /// The predefined `HLAnoCredentials`: no data.
340    pub fn no_credentials() -> Self {
341        Self::new(Self::NO_CREDENTIALS, Bytes::new())
342    }
343
344    /// The predefined `HLAplainTextPassword`: the data is the password encoded as an `HLAunicodeString`.
345    pub fn plain_text_password(password: &str) -> Self {
346        Self::new(Self::PLAIN_TEXT_PASSWORD, encode_hla_unicode_string(password))
347    }
348
349    /// Name of the credentials type.
350    pub fn credentials_type(&self) -> &str {
351        &self.credentials_type
352    }
353
354    /// The credentials data.
355    pub fn data(&self) -> &[u8] {
356        &self.data
357    }
358
359    pub(crate) fn data_bytes(&self) -> Bytes {
360        self.data.clone()
361    }
362}
363
364/// The data may be a secret: only its length is printed.
365impl fmt::Debug for Credentials {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        f.debug_struct("Credentials")
368            .field("credentials_type", &self.credentials_type)
369            .field("data_length", &self.data.len())
370            .finish()
371    }
372}
373
374/// Encodes text as an `HLAunicodeString`: a 32-bit big-endian count of UTF-16 code units followed by the
375/// code units, big endian.
376pub fn encode_hla_unicode_string(text: &str) -> Bytes {
377    let units: Vec<u16> = text.encode_utf16().collect();
378    let mut encoded = Vec::with_capacity(4 + 2 * units.len());
379    encoded.extend_from_slice(&u32::try_from(units.len()).unwrap_or(u32::MAX).to_be_bytes());
380    for unit in units {
381        encoded.extend_from_slice(&unit.to_be_bytes());
382    }
383    Bytes::from(encoded)
384}
385
386/// Decodes an `HLAunicodeString`. Fails with `CouldNotDecode` when the bytes are truncated, too long or
387/// not valid UTF-16.
388pub fn decode_hla_unicode_string(encoded: &[u8]) -> RtiResult<String> {
389    let could_not_decode =
390        |what: &str| RtiError::new(ExceptionKind::CouldNotDecode, format!("HLAunicodeString: {what}"));
391    let (count, units) =
392        encoded.split_first_chunk::<4>().ok_or_else(|| could_not_decode("missing length"))?;
393    let count = u32::from_be_bytes(*count) as usize;
394    if units.len() != count.saturating_mul(2) {
395        return Err(could_not_decode("length does not match the data"));
396    }
397    let units: Vec<u16> = units.as_chunks::<2>().0.iter().map(|pair| u16::from_be_bytes(*pair)).collect();
398    String::from_utf16(&units).map_err(|_| could_not_decode("invalid UTF-16"))
399}
400
401/// One entry of the Report Federation Executions callback (4.8).
402#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
403pub struct FederationExecutionInformation {
404    /// Name of the federation execution.
405    pub federation_execution_name: String,
406    /// Name of its logical time implementation, for example `HLAfloat64Time`.
407    pub logical_time_implementation_name: String,
408}
409
410/// One entry of the Report Federation Execution Members callback (4.10).
411#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
412pub struct FederationExecutionMemberInformation {
413    /// Name of the joined federate.
414    pub federate_name: String,
415    /// Type of the joined federate.
416    pub federate_type: String,
417}
418
419/// Save status of one federate, from the Federation Save Status Response callback (4.26).
420#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
421pub struct FederateHandleSaveStatusPair {
422    /// The federate.
423    pub federate: FederateHandle,
424    /// Its progress in the save.
425    pub save_status: SaveStatus,
426}
427
428/// Restore status of one federate, from the Federation Restore Status Response callback (4.35).
429#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
430pub struct FederateRestoreStatus {
431    /// Handle of the federate before the restore.
432    pub pre_restore_handle: FederateHandle,
433    /// Handle of the federate after the restore; `None` (the null designator of 4.35) for a federate
434    /// that takes no part in a restore.
435    pub post_restore_handle: Option<FederateHandle>,
436    /// Its progress in the restore.
437    pub restore_status: RestoreStatus,
438}
439
440/// Result of the timestamped sending services (6.10, 6.12, 6.14, 6.16): the retraction handle, if the
441/// message can be retracted.
442#[derive(Clone, Debug, PartialEq, Eq, Hash)]
443pub struct MessageRetractionReturn {
444    /// The handle to pass to Retract (8.22); `None` when the message cannot be retracted.
445    pub handle: Option<MessageRetractionHandle>,
446}
447
448impl MessageRetractionReturn {
449    /// True when a retraction handle was returned.
450    pub fn retraction_handle_is_valid(&self) -> bool {
451        self.handle.is_some()
452    }
453}
454
455/// Result of Query GALT and Query LITS (8.17, 8.19): a logical time, if one is defined.
456#[derive(Clone, Copy, Debug, PartialEq, Eq)]
457pub struct TimeQueryReturn {
458    /// The queried time; `None` when it is not defined.
459    pub time: Option<LogicalTime>,
460}
461
462impl TimeQueryReturn {
463    /// True when a time was returned.
464    pub fn time_is_valid(&self) -> bool {
465        self.time.is_some()
466    }
467}
468
469/// The producing federate and the conveyed regions of a Reflect Attribute Values callback (6.11), grouped.
470///
471/// The 2025 callbacks pass both parts as separate arguments; see
472/// [`Callback::supplemental_reflect_info`](crate::Callback::supplemental_reflect_info).
473#[derive(Clone, Debug, PartialEq, Eq, Hash)]
474pub struct SupplementalReflectInfo {
475    /// The federate that sent the update.
476    pub producing_federate: FederateHandle,
477    /// The update regions, when the RTI conveys them (9.1.7).
478    pub sent_regions: Option<ConveyedRegionSet>,
479}
480
481/// The producing federate and the conveyed regions of a Receive Interaction callback (6.13), grouped.
482///
483/// See [`Callback::supplemental_receive_info`](crate::Callback::supplemental_receive_info).
484#[derive(Clone, Debug, PartialEq, Eq, Hash)]
485pub struct SupplementalReceiveInfo {
486    /// The federate that sent the interaction.
487    pub producing_federate: FederateHandle,
488    /// The regions used for sending, when the RTI conveys them (9.1.7).
489    pub sent_regions: Option<ConveyedRegionSet>,
490}
491
492/// Result of Join Federation Execution (4.11).
493#[derive(Clone, Debug, PartialEq, Eq, Hash)]
494pub struct JoinResult {
495    /// Handle of the joined federate.
496    pub federate_handle: FederateHandle,
497    /// Name of the logical time implementation of the federation execution.
498    pub logical_time_implementation_name: String,
499    /// The same information as a [`TimeKind`]; the RTI ambassador uses it to encode and decode times.
500    pub time_kind: TimeKind,
501}
502
503/// Designator of a FOM module or MIM for Create and Join Federation Execution (12.13.3.3 a).
504#[derive(Clone, Debug, PartialEq, Eq, Hash)]
505pub enum FomModule {
506    /// A local file. It is read when the service is invoked; its file name and content are sent.
507    File(PathBuf),
508    /// A module given by name and full content.
509    Content {
510        /// File name of the module.
511        name: String,
512        /// The OMT DIF XML document.
513        content: Bytes,
514    },
515    /// A module compressed as a ZIP archive.
516    Compressed(Bytes),
517    /// A URL from which the RTI fetches the module.
518    Url(String),
519}
520
521impl FomModule {
522    /// A module read from a local file when the service is invoked.
523    pub fn file(path: impl Into<PathBuf>) -> Self {
524        FomModule::File(path.into())
525    }
526
527    /// A module given by name and full content.
528    pub fn content(name: impl Into<String>, content: impl Into<Bytes>) -> Self {
529        FomModule::Content { name: name.into(), content: content.into() }
530    }
531
532    /// A module compressed as a ZIP archive (ISO/IEC 21320-1).
533    pub fn compressed(archive: impl Into<Bytes>) -> Self {
534        FomModule::Compressed(archive.into())
535    }
536
537    /// A module the RTI fetches from a URL.
538    pub fn url(url: impl Into<String>) -> Self {
539        FomModule::Url(url.into())
540    }
541
542    /// Builds the wire form. A file that cannot be read raises `unreadable` (`CouldNotOpenFOM` or
543    /// `CouldNotOpenMIM`, depending on the argument the module is used for).
544    pub(crate) fn to_proto(&self, unreadable: ExceptionKind) -> RtiResult<proto::FomModule> {
545        use proto::fom_module::FomModule as Wire;
546        let module = match self {
547            FomModule::File(path) => {
548                let content = std::fs::read(path)
549                    .map_err(|error| RtiError::new(unreadable, format!("{}: {error}", path.display())))?;
550                let name = match path.file_name() {
551                    Some(name) => name.to_string_lossy().into_owned(),
552                    None => path.display().to_string(),
553                };
554                Wire::File(proto::FileFomModule { name, content: Bytes::from(content) })
555            }
556            FomModule::Content { name, content } => {
557                Wire::File(proto::FileFomModule { name: name.clone(), content: content.clone() })
558            }
559            FomModule::Compressed(archive) => Wire::CompressedModule(archive.clone()),
560            FomModule::Url(url) => Wire::Url(url.clone()),
561        };
562        Ok(proto::FomModule { fom_module: Some(module) })
563    }
564}