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
//! Conversions between the typed API values and the protobuf messages of Annex D.
//!
//! [`ToWire`] turns an argument into the type of a request field, [`FromWire`] turns a response or callback
//! field into the API type. Both get a [`WireCx`], which knows the time representation of the federation
//! execution the federate is joined to.

use std::collections::{BTreeMap, BTreeSet};

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

use crate::handles::{
    AttributeHandle, DimensionHandle, FederateHandle, InteractionClassHandle, MessageRetractionHandle,
    ParameterHandle, RegionHandle,
};
use crate::types::{
    AdditionalSettingsResultCode, AttributeHandleValueMap, AttributeSetRegionSetPair, ConfigurationResult,
    ConveyedRegionSet, Credentials, FederateHandleSaveStatusPair, FederateRestoreStatus,
    FederationExecutionInformation, FederationExecutionMemberInformation, FomModule, MessageRetractionReturn,
    ParameterHandleValueMap, RangeBounds, RestoreStatus, RtiConfiguration, SaveStatus,
    SupplementalReceiveInfo, SupplementalReflectInfo, TimeQueryReturn,
};

/// What a conversion needs to know about the federate's situation.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct WireCx {
    /// Time representation of the federation execution; `None` while not joined.
    pub(crate) time: Option<TimeKind>,
}

/// Converts an API argument into the type of a request field.
pub(crate) trait ToWire<W> {
    /// Performs the conversion; fails when the argument cannot be sent (wrong time type, unreadable file).
    fn to_wire(self, cx: &WireCx) -> RtiResult<W>;
}

/// Converts a response or callback field into the API type.
pub(crate) trait FromWire<W>: Sized {
    /// Performs the conversion; fails with `RTIinternalError` on messages no conforming RTI sends.
    fn from_wire(wire: W, cx: &WireCx) -> RtiResult<Self>;
}

/// The error for a message that does not have the shape Annex D requires.
pub(crate) fn malformed(what: impl AsRef<str>) -> RtiError {
    RtiError::internal(format!("malformed message from the RTI: {}", what.as_ref()))
}

macro_rules! identity {
    ($($ty:ty),+) => {$(
        impl ToWire<$ty> for $ty {
            fn to_wire(self, _: &WireCx) -> RtiResult<$ty> {
                Ok(self)
            }
        }

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

identity!(bool, u32, f64, String, Bytes);

impl ToWire<String> for &str {
    fn to_wire(self, _: &WireCx) -> RtiResult<String> {
        Ok(self.to_owned())
    }
}

impl ToWire<Bytes> for &[u8] {
    fn to_wire(self, _: &WireCx) -> RtiResult<Bytes> {
        Ok(Bytes::copy_from_slice(self))
    }
}

impl ToWire<Vec<String>> for &BTreeSet<String> {
    fn to_wire(self, _: &WireCx) -> RtiResult<Vec<String>> {
        Ok(self.iter().cloned().collect())
    }
}

impl FromWire<Vec<String>> for BTreeSet<String> {
    fn from_wire(wire: Vec<String>, _: &WireCx) -> RtiResult<Self> {
        Ok(wire.into_iter().collect())
    }
}

macro_rules! handle_sets {
    ($($handle:ident => $set:ident . $field:ident;)+) => {$(
        impl ToWire<Option<proto::$set>> for &BTreeSet<$handle> {
            fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::$set>> {
                let handles = self.iter().map(|handle| proto::$handle { data: handle.encode() }).collect();
                Ok(Some(proto::$set { $field: handles }))
            }
        }

        /// An absent set message is read as the empty set.
        impl FromWire<Option<proto::$set>> for BTreeSet<$handle> {
            fn from_wire(wire: Option<proto::$set>, _: &WireCx) -> RtiResult<Self> {
                let handles = wire.map(|set| set.$field).unwrap_or_default();
                Ok(handles.into_iter().map(|handle| $handle::from_encoded(handle.data)).collect())
            }
        }
    )+};
}

handle_sets! {
    FederateHandle => FederateHandleSet.federate_handle;
    AttributeHandle => AttributeHandleSet.attribute_handle;
    InteractionClassHandle => InteractionClassHandleSet.interaction_class_handle;
    DimensionHandle => DimensionHandleSet.dimension_handle;
    RegionHandle => RegionHandleSet.region_handle;
}

macro_rules! value_maps {
    ($($map:ident : $handle:ident => $entry:ident . $list:ident . $key:ident;)+) => {$(
        impl ToWire<Option<proto::$map>> for &$map {
            fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::$map>> {
                let entries = self
                    .iter()
                    .map(|(handle, value)| proto::$entry {
                        $key: Some(proto::$handle { data: handle.encode() }),
                        value: value.clone(),
                    })
                    .collect();
                Ok(Some(proto::$map { $list: entries }))
            }
        }

        /// An absent map message is read as the empty map.
        impl FromWire<Option<proto::$map>> for $map {
            fn from_wire(wire: Option<proto::$map>, cx: &WireCx) -> RtiResult<Self> {
                let mut map = BTreeMap::new();
                for entry in wire.map(|map| map.$list).unwrap_or_default() {
                    map.insert($handle::from_wire(entry.$key, cx)?, entry.value);
                }
                Ok(map)
            }
        }
    )+};
}

value_maps! {
    AttributeHandleValueMap: AttributeHandle => AttributeHandleValue.attribute_handle_value.attribute_handle;
    ParameterHandleValueMap: ParameterHandle => ParameterHandleValue.parameter_handle_value.parameter_handle;
}

impl ToWire<Option<proto::AttributeSetRegionSetPairList>> for &[AttributeSetRegionSetPair] {
    fn to_wire(self, cx: &WireCx) -> RtiResult<Option<proto::AttributeSetRegionSetPairList>> {
        let mut pairs = Vec::with_capacity(self.len());
        for pair in self {
            pairs.push(proto::AttributeSetRegionSetPair {
                attribute_set: (&pair.attributes).to_wire(cx)?,
                region_set: (&pair.regions).to_wire(cx)?,
            });
        }
        Ok(Some(proto::AttributeSetRegionSetPairList { attribute_set_region_set_pair: pairs }))
    }
}

/// A time of the wrong representation never reaches the RTI: it would be misread there.
impl ToWire<Option<proto::LogicalTime>> for LogicalTime {
    fn to_wire(self, cx: &WireCx) -> RtiResult<Option<proto::LogicalTime>> {
        if let Some(kind) = cx.time.filter(|kind| *kind != self.kind()) {
            return Err(RtiError::new(
                ExceptionKind::InvalidLogicalTime,
                format!("the federation execution uses {kind}, not {}", self.kind()),
            ));
        }
        Ok(Some(proto::LogicalTime { data: Bytes::copy_from_slice(&self.encode()) }))
    }
}

impl FromWire<Option<proto::LogicalTime>> for LogicalTime {
    fn from_wire(wire: Option<proto::LogicalTime>, cx: &WireCx) -> RtiResult<Self> {
        let wire = wire.ok_or_else(|| malformed("missing logical time"))?;
        let kind = cx.time.ok_or_else(|| malformed("logical time received while not joined"))?;
        kind.decode_time(&wire.data).map_err(|error| malformed(error.message))
    }
}

/// The only services taking an interval are the two that set the lookahead (8.2, 8.20).
impl ToWire<Option<proto::LogicalTimeInterval>> for LogicalTimeInterval {
    fn to_wire(self, cx: &WireCx) -> RtiResult<Option<proto::LogicalTimeInterval>> {
        if let Some(kind) = cx.time.filter(|kind| *kind != self.kind()) {
            return Err(RtiError::new(
                ExceptionKind::InvalidLookahead,
                format!("the federation execution uses {kind}, not {}", self.kind()),
            ));
        }
        Ok(Some(proto::LogicalTimeInterval { data: Bytes::copy_from_slice(&self.encode()) }))
    }
}

impl FromWire<Option<proto::LogicalTimeInterval>> for LogicalTimeInterval {
    fn from_wire(wire: Option<proto::LogicalTimeInterval>, cx: &WireCx) -> RtiResult<Self> {
        let wire = wire.ok_or_else(|| malformed("missing logical time interval"))?;
        let kind = cx.time.ok_or_else(|| malformed("logical time interval received while not joined"))?;
        kind.decode_interval(&wire.data).map_err(|error| malformed(error.message))
    }
}

impl ToWire<Option<proto::RangeBounds>> for RangeBounds {
    fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::RangeBounds>> {
        Ok(Some(proto::RangeBounds { lower: self.lower, upper: self.upper }))
    }
}

impl FromWire<Option<proto::RangeBounds>> for RangeBounds {
    fn from_wire(wire: Option<proto::RangeBounds>, _: &WireCx) -> RtiResult<Self> {
        let wire = wire.ok_or_else(|| malformed("missing range bounds"))?;
        Ok(RangeBounds { lower: wire.lower, upper: wire.upper })
    }
}

impl ToWire<Option<proto::FomModule>> for &FomModule {
    fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::FomModule>> {
        self.to_proto(ExceptionKind::CouldNotOpenFOM).map(Some)
    }
}

/// A FOM module designator used for the MIM argument: reading it fails with `CouldNotOpenMIM`.
pub(crate) struct Mim<'a>(pub(crate) &'a FomModule);

impl ToWire<Option<proto::FomModule>> for Mim<'_> {
    fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::FomModule>> {
        self.0.to_proto(ExceptionKind::CouldNotOpenMIM).map(Some)
    }
}

impl ToWire<Option<proto::FomModuleSet>> for &[FomModule] {
    fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::FomModuleSet>> {
        let mut modules = Vec::with_capacity(self.len());
        for module in self {
            modules.push(module.to_proto(ExceptionKind::CouldNotOpenFOM)?);
        }
        Ok(Some(proto::FomModuleSet { fom_module: modules }))
    }
}

impl ToWire<Option<proto::RtiConfiguration>> for &RtiConfiguration {
    fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::RtiConfiguration>> {
        Ok(Some(proto::RtiConfiguration {
            configuration_name: self.configuration_name().to_owned(),
            rti_address: self.rti_address().to_owned(),
            additional_settings: self.additional_settings().to_owned(),
        }))
    }
}

impl ToWire<Option<proto::Credentials>> for &Credentials {
    fn to_wire(self, _: &WireCx) -> RtiResult<Option<proto::Credentials>> {
        Ok(Some(proto::Credentials { r#type: self.credentials_type().to_owned(), data: self.data_bytes() }))
    }
}

impl FromWire<Option<proto::ConfigurationResult>> for ConfigurationResult {
    fn from_wire(wire: Option<proto::ConfigurationResult>, cx: &WireCx) -> RtiResult<Self> {
        let wire = wire.ok_or_else(|| malformed("missing configuration result"))?;
        Ok(ConfigurationResult {
            configuration_used: wire.configuration_used,
            address_used: wire.address_used,
            additional_settings_result_code: AdditionalSettingsResultCode::from_wire(
                wire.additional_settings_result_code,
                cx,
            )?,
            message: wire.message,
        })
    }
}

impl FromWire<Option<proto::MessageRetractionReturn>> for MessageRetractionReturn {
    fn from_wire(wire: Option<proto::MessageRetractionReturn>, cx: &WireCx) -> RtiResult<Self> {
        let wire = wire.ok_or_else(|| malformed("missing message retraction return"))?;
        if !wire.retraction_handle_is_valid {
            return Ok(MessageRetractionReturn { handle: None });
        }
        let handle = MessageRetractionHandle::from_wire(wire.message_retraction_handle, cx)?;
        Ok(MessageRetractionReturn { handle: Some(handle) })
    }
}

impl FromWire<Option<proto::TimeQueryReturn>> for TimeQueryReturn {
    fn from_wire(wire: Option<proto::TimeQueryReturn>, cx: &WireCx) -> RtiResult<Self> {
        let wire = wire.ok_or_else(|| malformed("missing time query return"))?;
        if !wire.logical_time_is_valid {
            return Ok(TimeQueryReturn { time: None });
        }
        Ok(TimeQueryReturn { time: Some(LogicalTime::from_wire(wire.logical_time, cx)?) })
    }
}

/// An absent set of conveyed regions is "no value" (12.10).
impl FromWire<Option<proto::ConveyedRegionSet>> for Option<ConveyedRegionSet> {
    fn from_wire(wire: Option<proto::ConveyedRegionSet>, cx: &WireCx) -> RtiResult<Self> {
        let Some(wire) = wire else {
            return Ok(None);
        };
        let mut regions = BTreeSet::new();
        for region in wire.conveyed_regions {
            let mut ranges = BTreeMap::new();
            for entry in region.dimension_and_range {
                let dimension = DimensionHandle::from_wire(entry.dimension_handle, cx)?;
                ranges.insert(dimension, RangeBounds::from_wire(entry.range_bounds, cx)?);
            }
            regions.insert(ranges);
        }
        Ok(Some(regions))
    }
}

macro_rules! supplemental {
    ($($name:ident),+) => {$(
        impl FromWire<Option<proto::$name>> for $name {
            fn from_wire(wire: Option<proto::$name>, cx: &WireCx) -> RtiResult<Self> {
                let wire = wire.ok_or_else(|| malformed(concat!("missing ", stringify!($name))))?;
                let regions = if wire.conveyed_regions_is_valid { wire.conveyed_regions } else { None };
                Ok($name {
                    producing_federate: FederateHandle::from_wire(wire.producing_federate, cx)?,
                    sent_regions: FromWire::from_wire(regions, cx)?,
                })
            }
        }
    )+};
}

supplemental!(SupplementalReflectInfo, SupplementalReceiveInfo);

impl FromWire<Option<proto::FederationExecutionInformationSet>> for BTreeSet<FederationExecutionInformation> {
    fn from_wire(wire: Option<proto::FederationExecutionInformationSet>, _: &WireCx) -> RtiResult<Self> {
        let entries = wire.map(|set| set.federation_execution_information).unwrap_or_default();
        Ok(entries
            .into_iter()
            .map(|entry| FederationExecutionInformation {
                federation_execution_name: entry.federation_execution_name,
                logical_time_implementation_name: entry.logical_time_implementation_name,
            })
            .collect())
    }
}

impl FromWire<Option<proto::FederationExecutionMemberInformationSet>>
    for BTreeSet<FederationExecutionMemberInformation>
{
    fn from_wire(
        wire: Option<proto::FederationExecutionMemberInformationSet>,
        _: &WireCx,
    ) -> RtiResult<Self> {
        let entries = wire.map(|set| set.federation_execution_member_information).unwrap_or_default();
        Ok(entries
            .into_iter()
            .map(|entry| FederationExecutionMemberInformation {
                federate_name: entry.federate_name,
                federate_type: entry.federate_type,
            })
            .collect())
    }
}

impl FromWire<Option<proto::FederateHandleSaveStatusPairArray>> for Vec<FederateHandleSaveStatusPair> {
    fn from_wire(wire: Option<proto::FederateHandleSaveStatusPairArray>, cx: &WireCx) -> RtiResult<Self> {
        let mut pairs = Vec::new();
        for entry in wire.map(|array| array.federate_handle_save_status_pair).unwrap_or_default() {
            pairs.push(FederateHandleSaveStatusPair {
                federate: FederateHandle::from_wire(entry.federate_handle, cx)?,
                save_status: SaveStatus::from_wire(entry.save_status, cx)?,
            });
        }
        Ok(pairs)
    }
}

impl FromWire<Option<proto::FederateRestoreStatusArray>> for Vec<FederateRestoreStatus> {
    fn from_wire(wire: Option<proto::FederateRestoreStatusArray>, cx: &WireCx) -> RtiResult<Self> {
        let mut statuses = Vec::new();
        for entry in wire.map(|array| array.federate_restore_status).unwrap_or_default() {
            statuses.push(FederateRestoreStatus {
                pre_restore_handle: FederateHandle::from_wire(entry.pre_restore_handle, cx)?,
                post_restore_handle: Option::<FederateHandle>::from_wire(entry.post_restore_handle, cx)?,
                restore_status: RestoreStatus::from_wire(entry.restore_status, cx)?,
            });
        }
        Ok(statuses)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ConveyedRegion;

    fn handle(byte: u8) -> Bytes {
        Bytes::from(vec![byte])
    }

    #[test]
    fn a_restore_status_without_restore_has_no_post_restore_handle() {
        // 4.35: the descriptor of a federate that takes no part in a restore has a null post-restore
        // designator, which is an absent field on the wire.
        let cx = WireCx::default();
        let wire = proto::FederateRestoreStatusArray {
            federate_restore_status: vec![
                proto::FederateRestoreStatus {
                    pre_restore_handle: Some(proto::FederateHandle { data: handle(1) }),
                    post_restore_handle: None,
                    restore_status: proto::RestoreStatus::NoRestoreInProgress as i32,
                },
                proto::FederateRestoreStatus {
                    pre_restore_handle: Some(proto::FederateHandle { data: handle(2) }),
                    post_restore_handle: Some(proto::FederateHandle { data: handle(9) }),
                    restore_status: proto::RestoreStatus::FederateRestoring as i32,
                },
            ],
        };
        let statuses = Vec::<FederateRestoreStatus>::from_wire(Some(wire), &cx).unwrap();
        assert_eq!(statuses[0].pre_restore_handle, FederateHandle::from_encoded(handle(1)));
        assert_eq!(statuses[0].post_restore_handle, None);
        assert_eq!(statuses[0].restore_status, RestoreStatus::NoRestoreInProgress);
        assert_eq!(statuses[1].post_restore_handle, Some(FederateHandle::from_encoded(handle(9))));
    }

    #[test]
    fn supplemental_info_records_of_the_datatypes_file() {
        let cx = WireCx::default();
        let regions = proto::ConveyedRegionSet {
            conveyed_regions: vec![proto::ConveyedRegion {
                dimension_and_range: vec![proto::DimensionAndRange {
                    dimension_handle: Some(proto::DimensionHandle { data: handle(7) }),
                    range_bounds: Some(proto::RangeBounds { lower: 1, upper: 5 }),
                }],
            }],
        };
        let wire = proto::SupplementalReflectInfo {
            producing_federate: Some(proto::FederateHandle { data: handle(1) }),
            conveyed_regions_is_valid: true,
            conveyed_regions: Some(regions.clone()),
        };
        let info = SupplementalReflectInfo::from_wire(Some(wire.clone()), &cx).unwrap();
        assert_eq!(info.producing_federate, FederateHandle::from_encoded(handle(1)));
        let region =
            ConveyedRegion::from([(DimensionHandle::from_encoded(handle(7)), RangeBounds::new(1, 5))]);
        assert_eq!(info.sent_regions, Some(ConveyedRegionSet::from([region])));

        // The validity flag decides, whatever the optional field holds.
        let invalid = proto::SupplementalReflectInfo { conveyed_regions_is_valid: false, ..wire };
        assert_eq!(SupplementalReflectInfo::from_wire(Some(invalid), &cx).unwrap().sent_regions, None);

        let wire = proto::SupplementalReceiveInfo {
            producing_federate: Some(proto::FederateHandle { data: handle(2) }),
            conveyed_regions_is_valid: false,
            conveyed_regions: None,
        };
        let info = SupplementalReceiveInfo::from_wire(Some(wire), &cx).unwrap();
        assert_eq!(info.producing_federate, FederateHandle::from_encoded(handle(2)));
        assert_eq!(info.sent_regions, None);
        assert_eq!(
            SupplementalReceiveInfo::from_wire(None, &cx).unwrap_err().kind,
            ExceptionKind::RTIinternalError
        );
    }

    #[test]
    fn a_region_without_bounds_is_malformed() {
        let regions = proto::ConveyedRegionSet {
            conveyed_regions: vec![proto::ConveyedRegion {
                dimension_and_range: vec![proto::DimensionAndRange {
                    dimension_handle: Some(proto::DimensionHandle { data: handle(7) }),
                    range_bounds: None,
                }],
            }],
        };
        let decoded: RtiResult<Option<ConveyedRegionSet>> =
            FromWire::from_wire(Some(regions), &WireCx::default());
        assert_eq!(decoded.unwrap_err().kind, ExceptionKind::RTIinternalError);
    }
}