microrti-client 0.2.0

Federate side of HLA 4 (IEEE 1516.1-2025): RtiAmbassador and FederateAmbassador over an abstract RTI link.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Value types of the federate API: sets and maps of handles, enumerations and the small records that
//! services take or return. They mirror `datatypes.proto` with Rust types; the conversions to and from the
//! protobuf messages live in `wire.rs`.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::PathBuf;

use bytes::Bytes;
use microrti_core::{ExceptionKind, LogicalTime, RtiError, RtiResult, TimeKind};
use microrti_proto as proto;

use crate::handles::{
    AttributeHandle, DimensionHandle, FederateHandle, InteractionClassHandle, MessageRetractionHandle,
    ParameterHandle, RegionHandle,
};
use crate::wire::{FromWire, ToWire, WireCx, malformed};

/// Set of federate handles.
pub type FederateHandleSet = BTreeSet<FederateHandle>;
/// Set of attribute handles.
pub type AttributeHandleSet = BTreeSet<AttributeHandle>;
/// Set of interaction class handles.
pub type InteractionClassHandleSet = BTreeSet<InteractionClassHandle>;
/// Set of dimension handles.
pub type DimensionHandleSet = BTreeSet<DimensionHandle>;
/// Set of region handles.
pub type RegionHandleSet = BTreeSet<RegionHandle>;
/// Attribute values keyed by attribute handle. A value is the encoded bytes of the attribute's datatype.
pub type AttributeHandleValueMap = BTreeMap<AttributeHandle, Bytes>;
/// Parameter values keyed by parameter handle. A value is the encoded bytes of the parameter's datatype.
pub type ParameterHandleValueMap = BTreeMap<ParameterHandle, Bytes>;
/// Collection of attribute set / region set pairs used by the DDM services of clause 9.
pub type AttributeSetRegionSetPairList = Vec<AttributeSetRegionSetPair>;
/// The ranges of one region as conveyed with a reflected update or a received interaction (9.1.7).
pub type ConveyedRegion = BTreeMap<DimensionHandle, RangeBounds>;
/// The regions conveyed with a reflected update or a received interaction.
pub type ConveyedRegionSet = BTreeSet<ConveyedRegion>;

macro_rules! wire_enums {
    ($(
        $(#[$doc:meta])*
        $name:ident { $( $(#[$vdoc:meta])* $variant:ident ),+ $(,)? }
    )+) => {$(
        $(#[$doc])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub enum $name {
            $( $(#[$vdoc])* $variant, )+
        }

        impl $name {
            /// Every value, in the order of the standard's enumeration.
            pub const ALL: &'static [$name] = &[$($name::$variant),+];

            pub(crate) fn to_i32(self) -> i32 {
                match self {
                    $($name::$variant => proto::$name::$variant as i32,)+
                }
            }

            pub(crate) fn from_i32(value: i32) -> RtiResult<Self> {
                match proto::$name::try_from(value) {
                    $(Ok(proto::$name::$variant) => Ok($name::$variant),)+
                    Err(_) => Err(malformed(format!(concat!("unknown ", stringify!($name), " value {}"), value))),
                }
            }
        }

        impl ToWire<i32> for $name {
            fn to_wire(self, _: &WireCx) -> RtiResult<i32> {
                Ok(self.to_i32())
            }
        }

        impl FromWire<i32> for $name {
            fn from_wire(wire: i32, _: &WireCx) -> RtiResult<Self> {
                Self::from_i32(wire)
            }
        }
    )+};
}

wire_enums! {
    /// How callbacks reach the federate ambassador (4.2, 10.57 to 10.60).
    CallbackModel {
        /// Callbacks wait until the federate calls Evoke Callback or Evoke Multiple Callbacks.
        Evoked,
        /// Callbacks are delivered as they arrive, on a thread owned by the RTI ambassador.
        Immediate,
    }

    /// Outcome of the additional settings passed to Connect (4.2).
    AdditionalSettingsResultCode {
        /// The RTI did not look at the settings.
        SettingsIgnored,
        /// The RTI could not parse the settings; the connection was made anyway.
        SettingsFailedToParse,
        /// The RTI applied the settings.
        SettingsApplied,
    }

    /// What the RTI does with a federate's objects and attributes when it resigns (4.12).
    ResignAction {
        /// Give up ownership of every owned instance attribute.
        UnconditionallyDivestAttributes,
        /// Delete every object instance whose deletion privilege the federate holds.
        DeleteObjects,
        /// Cancel the ownership acquisitions the federate has pending.
        CancelPendingOwnershipAcquisitions,
        /// Delete the objects, then divest what remains.
        DeleteObjectsThenDivest,
        /// Cancel pending acquisitions, delete the objects, then divest what remains.
        CancelThenDeleteThenDivest,
        /// Do none of the above.
        NoAction,
    }

    /// Why a synchronization point could not be registered (4.15).
    SynchronizationPointFailureReason {
        /// The label is already in use in the federation execution.
        SynchronizationPointLabelNotUnique,
        /// A federate of the synchronization set is not joined.
        SynchronizationSetMemberNotJoined,
    }

    /// Why a federation save did not complete (4.23).
    SaveFailureReason {
        /// The RTI could not save its own state.
        RtiUnableToSave,
        /// A federate reported that its save failed.
        FederateReportedFailureDuringSave,
        /// A federate resigned while the save was in progress.
        FederateResignedDuringSave,
        /// The RTI detected a failure of a federate.
        RtiDetectedFailureDuringSave,
        /// The requested save time could not be honored.
        SaveTimeCannotBeHonored,
        /// The save was aborted on request.
        SaveAborted,
    }

    /// Why a federation restore did not complete (4.32).
    RestoreFailureReason {
        /// The RTI could not restore its own state.
        RtiUnableToRestore,
        /// A federate reported that its restore failed.
        FederateReportedFailureDuringRestore,
        /// A federate resigned while the restore was in progress.
        FederateResignedDuringRestore,
        /// The RTI detected a failure of a federate.
        RtiDetectedFailureDuringRestore,
        /// The restore was aborted on request.
        RestoreAborted,
    }

    /// Progress of a federate in a federation save (4.26).
    SaveStatus {
        /// No save is in progress.
        NoSaveInProgress,
        /// The federate was told to save and has not started.
        FederateInstructedToSave,
        /// The federate is saving.
        FederateSaving,
        /// The federate is done and waits for the rest of the federation.
        FederateWaitingForFederationToSave,
    }

    /// Progress of a federate in a federation restore (4.35).
    RestoreStatus {
        /// No restore is in progress.
        NoRestoreInProgress,
        /// A restore was requested and is not confirmed yet.
        FederateRestoreRequestPending,
        /// The federate waits for the restore to begin.
        FederateWaitingForRestoreToBegin,
        /// The federate is ready to restore.
        FederatePreparedToRestore,
        /// The federate is restoring.
        FederateRestoring,
        /// The federate is done and waits for the rest of the federation.
        FederateWaitingForFederationToRestore,
    }

    /// Message ordering (8.1).
    OrderType {
        /// Receive order.
        Receive,
        /// Timestamp order.
        Timestamp,
    }

    /// The service groups of clauses 4 to 10, as used by Normalize Service Group (10.29).
    ServiceGroup {
        /// Clause 4.
        FederationManagement,
        /// Clause 5.
        DeclarationManagement,
        /// Clause 6.
        ObjectManagement,
        /// Clause 7.
        OwnershipManagement,
        /// Clause 8.
        TimeManagement,
        /// Clause 9.
        DataDistributionManagement,
        /// Clause 10.
        SupportServices,
    }
}

/// `CallbackModel` values arriving from configuration files or other languages are validated here: anything
/// else than the two standard models is an `UnsupportedCallbackModel`.
impl TryFrom<i32> for CallbackModel {
    type Error = RtiError;

    fn try_from(value: i32) -> RtiResult<Self> {
        Self::from_i32(value).map_err(|_| {
            RtiError::new(
                ExceptionKind::UnsupportedCallbackModel,
                format!("callback model {value} is not supported"),
            )
        })
    }
}

/// Lower and upper bound of a range on one dimension (9.1).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RangeBounds {
    /// Lower bound.
    pub lower: u32,
    /// Upper bound.
    pub upper: u32,
}

impl RangeBounds {
    /// Creates range bounds.
    pub const fn new(lower: u32, upper: u32) -> Self {
        Self { lower, upper }
    }
}

/// A set of attributes together with the set of regions used for them.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AttributeSetRegionSetPair {
    /// The attributes.
    pub attributes: AttributeHandleSet,
    /// The regions associated with each of these attributes.
    pub regions: RegionHandleSet,
}

impl AttributeSetRegionSetPair {
    /// Creates a pair.
    pub fn new(attributes: AttributeHandleSet, regions: RegionHandleSet) -> Self {
        Self { attributes, regions }
    }
}

/// The optional arguments of Connect that select and tune the RTI (4.2). Built with the `with_*` methods.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct RtiConfiguration {
    configuration_name: String,
    rti_address: String,
    additional_settings: String,
}

impl RtiConfiguration {
    /// A configuration with every part empty, which selects the defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the name of a configuration known to the RTI.
    pub fn with_configuration_name(mut self, configuration_name: impl Into<String>) -> Self {
        self.configuration_name = configuration_name.into();
        self
    }

    /// Sets the address used to locate the RTI. Its scheme selects the connector (see
    /// [`Connectors`](crate::Connectors)).
    pub fn with_rti_address(mut self, rti_address: impl Into<String>) -> Self {
        self.rti_address = rti_address.into();
        self
    }

    /// Sets implementation specific settings; the RTI reports what it did with them in the
    /// [`ConfigurationResult`].
    pub fn with_additional_settings(mut self, additional_settings: impl Into<String>) -> Self {
        self.additional_settings = additional_settings.into();
        self
    }

    /// Name of the configuration, empty for the default.
    pub fn configuration_name(&self) -> &str {
        &self.configuration_name
    }

    /// Address of the RTI, empty for the default.
    pub fn rti_address(&self) -> &str {
        &self.rti_address
    }

    /// Implementation specific settings, possibly empty.
    pub fn additional_settings(&self) -> &str {
        &self.additional_settings
    }
}

/// What the RTI did with the [`RtiConfiguration`] passed to Connect (4.2).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ConfigurationResult {
    /// The named configuration was found and used.
    pub configuration_used: bool,
    /// The RTI address was used.
    pub address_used: bool,
    /// What happened to the additional settings.
    pub additional_settings_result_code: AdditionalSettingsResultCode,
    /// Human readable details, possibly empty.
    pub message: String,
}

/// Credentials presented to the RTI's authorization service by Connect (12.5).
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Credentials {
    credentials_type: String,
    data: Bytes,
}

impl Credentials {
    /// Type name of the predefined empty credentials.
    pub const NO_CREDENTIALS: &'static str = "HLAnoCredentials";
    /// Type name of the predefined plain text password credentials (12.6).
    pub const PLAIN_TEXT_PASSWORD: &'static str = "HLAplainTextPassword";

    /// Credentials of any type, with the data the authorization service of the RTI expects for it.
    pub fn new(credentials_type: impl Into<String>, data: impl Into<Bytes>) -> Self {
        Self { credentials_type: credentials_type.into(), data: data.into() }
    }

    /// The predefined `HLAnoCredentials`: no data.
    pub fn no_credentials() -> Self {
        Self::new(Self::NO_CREDENTIALS, Bytes::new())
    }

    /// The predefined `HLAplainTextPassword`: the data is the password encoded as an `HLAunicodeString`.
    pub fn plain_text_password(password: &str) -> Self {
        Self::new(Self::PLAIN_TEXT_PASSWORD, encode_hla_unicode_string(password))
    }

    /// Name of the credentials type.
    pub fn credentials_type(&self) -> &str {
        &self.credentials_type
    }

    /// The credentials data.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    pub(crate) fn data_bytes(&self) -> Bytes {
        self.data.clone()
    }
}

/// The data may be a secret: only its length is printed.
impl fmt::Debug for Credentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Credentials")
            .field("credentials_type", &self.credentials_type)
            .field("data_length", &self.data.len())
            .finish()
    }
}

/// Encodes text as an `HLAunicodeString`: a 32-bit big-endian count of UTF-16 code units followed by the
/// code units, big endian.
pub fn encode_hla_unicode_string(text: &str) -> Bytes {
    let units: Vec<u16> = text.encode_utf16().collect();
    let mut encoded = Vec::with_capacity(4 + 2 * units.len());
    encoded.extend_from_slice(&u32::try_from(units.len()).unwrap_or(u32::MAX).to_be_bytes());
    for unit in units {
        encoded.extend_from_slice(&unit.to_be_bytes());
    }
    Bytes::from(encoded)
}

/// Decodes an `HLAunicodeString`. Fails with `CouldNotDecode` when the bytes are truncated, too long or
/// not valid UTF-16.
pub fn decode_hla_unicode_string(encoded: &[u8]) -> RtiResult<String> {
    let could_not_decode =
        |what: &str| RtiError::new(ExceptionKind::CouldNotDecode, format!("HLAunicodeString: {what}"));
    let (count, units) =
        encoded.split_first_chunk::<4>().ok_or_else(|| could_not_decode("missing length"))?;
    let count = u32::from_be_bytes(*count) as usize;
    if units.len() != count.saturating_mul(2) {
        return Err(could_not_decode("length does not match the data"));
    }
    let units: Vec<u16> = units.as_chunks::<2>().0.iter().map(|pair| u16::from_be_bytes(*pair)).collect();
    String::from_utf16(&units).map_err(|_| could_not_decode("invalid UTF-16"))
}

/// One entry of the Report Federation Executions callback (4.8).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederationExecutionInformation {
    /// Name of the federation execution.
    pub federation_execution_name: String,
    /// Name of its logical time implementation, for example `HLAfloat64Time`.
    pub logical_time_implementation_name: String,
}

/// One entry of the Report Federation Execution Members callback (4.10).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederationExecutionMemberInformation {
    /// Name of the joined federate.
    pub federate_name: String,
    /// Type of the joined federate.
    pub federate_type: String,
}

/// Save status of one federate, from the Federation Save Status Response callback (4.26).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederateHandleSaveStatusPair {
    /// The federate.
    pub federate: FederateHandle,
    /// Its progress in the save.
    pub save_status: SaveStatus,
}

/// Restore status of one federate, from the Federation Restore Status Response callback (4.35).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederateRestoreStatus {
    /// Handle of the federate before the restore.
    pub pre_restore_handle: FederateHandle,
    /// Handle of the federate after the restore; `None` (the null designator of 4.35) for a federate
    /// that takes no part in a restore.
    pub post_restore_handle: Option<FederateHandle>,
    /// Its progress in the restore.
    pub restore_status: RestoreStatus,
}

/// Result of the timestamped sending services (6.10, 6.12, 6.14, 6.16): the retraction handle, if the
/// message can be retracted.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MessageRetractionReturn {
    /// The handle to pass to Retract (8.22); `None` when the message cannot be retracted.
    pub handle: Option<MessageRetractionHandle>,
}

impl MessageRetractionReturn {
    /// True when a retraction handle was returned.
    pub fn retraction_handle_is_valid(&self) -> bool {
        self.handle.is_some()
    }
}

/// Result of Query GALT and Query LITS (8.17, 8.19): a logical time, if one is defined.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TimeQueryReturn {
    /// The queried time; `None` when it is not defined.
    pub time: Option<LogicalTime>,
}

impl TimeQueryReturn {
    /// True when a time was returned.
    pub fn time_is_valid(&self) -> bool {
        self.time.is_some()
    }
}

/// The producing federate and the conveyed regions of a Reflect Attribute Values callback (6.11), grouped.
///
/// The 2025 callbacks pass both parts as separate arguments; see
/// [`Callback::supplemental_reflect_info`](crate::Callback::supplemental_reflect_info).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SupplementalReflectInfo {
    /// The federate that sent the update.
    pub producing_federate: FederateHandle,
    /// The update regions, when the RTI conveys them (9.1.7).
    pub sent_regions: Option<ConveyedRegionSet>,
}

/// The producing federate and the conveyed regions of a Receive Interaction callback (6.13), grouped.
///
/// See [`Callback::supplemental_receive_info`](crate::Callback::supplemental_receive_info).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SupplementalReceiveInfo {
    /// The federate that sent the interaction.
    pub producing_federate: FederateHandle,
    /// The regions used for sending, when the RTI conveys them (9.1.7).
    pub sent_regions: Option<ConveyedRegionSet>,
}

/// Result of Join Federation Execution (4.11).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct JoinResult {
    /// Handle of the joined federate.
    pub federate_handle: FederateHandle,
    /// Name of the logical time implementation of the federation execution.
    pub logical_time_implementation_name: String,
    /// The same information as a [`TimeKind`]; the RTI ambassador uses it to encode and decode times.
    pub time_kind: TimeKind,
}

/// Designator of a FOM module or MIM for Create and Join Federation Execution (12.13.3.3 a).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum FomModule {
    /// A local file. It is read when the service is invoked; its file name and content are sent.
    File(PathBuf),
    /// A module given by name and full content.
    Content {
        /// File name of the module.
        name: String,
        /// The OMT DIF XML document.
        content: Bytes,
    },
    /// A module compressed as a ZIP archive.
    Compressed(Bytes),
    /// A URL from which the RTI fetches the module.
    Url(String),
}

impl FomModule {
    /// A module read from a local file when the service is invoked.
    pub fn file(path: impl Into<PathBuf>) -> Self {
        FomModule::File(path.into())
    }

    /// A module given by name and full content.
    pub fn content(name: impl Into<String>, content: impl Into<Bytes>) -> Self {
        FomModule::Content { name: name.into(), content: content.into() }
    }

    /// A module compressed as a ZIP archive (ISO/IEC 21320-1).
    pub fn compressed(archive: impl Into<Bytes>) -> Self {
        FomModule::Compressed(archive.into())
    }

    /// A module the RTI fetches from a URL.
    pub fn url(url: impl Into<String>) -> Self {
        FomModule::Url(url.into())
    }

    /// Builds the wire form. A file that cannot be read raises `unreadable` (`CouldNotOpenFOM` or
    /// `CouldNotOpenMIM`, depending on the argument the module is used for).
    pub(crate) fn to_proto(&self, unreadable: ExceptionKind) -> RtiResult<proto::FomModule> {
        use proto::fom_module::FomModule as Wire;
        let module = match self {
            FomModule::File(path) => {
                let content = std::fs::read(path)
                    .map_err(|error| RtiError::new(unreadable, format!("{}: {error}", path.display())))?;
                let name = match path.file_name() {
                    Some(name) => name.to_string_lossy().into_owned(),
                    None => path.display().to_string(),
                };
                Wire::File(proto::FileFomModule { name, content: Bytes::from(content) })
            }
            FomModule::Content { name, content } => {
                Wire::File(proto::FileFomModule { name: name.clone(), content: content.clone() })
            }
            FomModule::Compressed(archive) => Wire::CompressedModule(archive.clone()),
            FomModule::Url(url) => Wire::Url(url.clone()),
        };
        Ok(proto::FomModule { fom_module: Some(module) })
    }
}