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};
pub type FederateHandleSet = BTreeSet<FederateHandle>;
pub type AttributeHandleSet = BTreeSet<AttributeHandle>;
pub type InteractionClassHandleSet = BTreeSet<InteractionClassHandle>;
pub type DimensionHandleSet = BTreeSet<DimensionHandle>;
pub type RegionHandleSet = BTreeSet<RegionHandle>;
pub type AttributeHandleValueMap = BTreeMap<AttributeHandle, Bytes>;
pub type ParameterHandleValueMap = BTreeMap<ParameterHandle, Bytes>;
pub type AttributeSetRegionSetPairList = Vec<AttributeSetRegionSetPair>;
pub type ConveyedRegion = BTreeMap<DimensionHandle, RangeBounds>;
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 {
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! {
CallbackModel {
Evoked,
Immediate,
}
AdditionalSettingsResultCode {
SettingsIgnored,
SettingsFailedToParse,
SettingsApplied,
}
ResignAction {
UnconditionallyDivestAttributes,
DeleteObjects,
CancelPendingOwnershipAcquisitions,
DeleteObjectsThenDivest,
CancelThenDeleteThenDivest,
NoAction,
}
SynchronizationPointFailureReason {
SynchronizationPointLabelNotUnique,
SynchronizationSetMemberNotJoined,
}
SaveFailureReason {
RtiUnableToSave,
FederateReportedFailureDuringSave,
FederateResignedDuringSave,
RtiDetectedFailureDuringSave,
SaveTimeCannotBeHonored,
SaveAborted,
}
RestoreFailureReason {
RtiUnableToRestore,
FederateReportedFailureDuringRestore,
FederateResignedDuringRestore,
RtiDetectedFailureDuringRestore,
RestoreAborted,
}
SaveStatus {
NoSaveInProgress,
FederateInstructedToSave,
FederateSaving,
FederateWaitingForFederationToSave,
}
RestoreStatus {
NoRestoreInProgress,
FederateRestoreRequestPending,
FederateWaitingForRestoreToBegin,
FederatePreparedToRestore,
FederateRestoring,
FederateWaitingForFederationToRestore,
}
OrderType {
Receive,
Timestamp,
}
ServiceGroup {
FederationManagement,
DeclarationManagement,
ObjectManagement,
OwnershipManagement,
TimeManagement,
DataDistributionManagement,
SupportServices,
}
}
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"),
)
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RangeBounds {
pub lower: u32,
pub upper: u32,
}
impl RangeBounds {
pub const fn new(lower: u32, upper: u32) -> Self {
Self { lower, upper }
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AttributeSetRegionSetPair {
pub attributes: AttributeHandleSet,
pub regions: RegionHandleSet,
}
impl AttributeSetRegionSetPair {
pub fn new(attributes: AttributeHandleSet, regions: RegionHandleSet) -> Self {
Self { attributes, regions }
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct RtiConfiguration {
configuration_name: String,
rti_address: String,
additional_settings: String,
}
impl RtiConfiguration {
pub fn new() -> Self {
Self::default()
}
pub fn with_configuration_name(mut self, configuration_name: impl Into<String>) -> Self {
self.configuration_name = configuration_name.into();
self
}
pub fn with_rti_address(mut self, rti_address: impl Into<String>) -> Self {
self.rti_address = rti_address.into();
self
}
pub fn with_additional_settings(mut self, additional_settings: impl Into<String>) -> Self {
self.additional_settings = additional_settings.into();
self
}
pub fn configuration_name(&self) -> &str {
&self.configuration_name
}
pub fn rti_address(&self) -> &str {
&self.rti_address
}
pub fn additional_settings(&self) -> &str {
&self.additional_settings
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ConfigurationResult {
pub configuration_used: bool,
pub address_used: bool,
pub additional_settings_result_code: AdditionalSettingsResultCode,
pub message: String,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Credentials {
credentials_type: String,
data: Bytes,
}
impl Credentials {
pub const NO_CREDENTIALS: &'static str = "HLAnoCredentials";
pub const PLAIN_TEXT_PASSWORD: &'static str = "HLAplainTextPassword";
pub fn new(credentials_type: impl Into<String>, data: impl Into<Bytes>) -> Self {
Self { credentials_type: credentials_type.into(), data: data.into() }
}
pub fn no_credentials() -> Self {
Self::new(Self::NO_CREDENTIALS, Bytes::new())
}
pub fn plain_text_password(password: &str) -> Self {
Self::new(Self::PLAIN_TEXT_PASSWORD, encode_hla_unicode_string(password))
}
pub fn credentials_type(&self) -> &str {
&self.credentials_type
}
pub fn data(&self) -> &[u8] {
&self.data
}
pub(crate) fn data_bytes(&self) -> Bytes {
self.data.clone()
}
}
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()
}
}
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)
}
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"))
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederationExecutionInformation {
pub federation_execution_name: String,
pub logical_time_implementation_name: String,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederationExecutionMemberInformation {
pub federate_name: String,
pub federate_type: String,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederateHandleSaveStatusPair {
pub federate: FederateHandle,
pub save_status: SaveStatus,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FederateRestoreStatus {
pub pre_restore_handle: FederateHandle,
pub post_restore_handle: Option<FederateHandle>,
pub restore_status: RestoreStatus,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MessageRetractionReturn {
pub handle: Option<MessageRetractionHandle>,
}
impl MessageRetractionReturn {
pub fn retraction_handle_is_valid(&self) -> bool {
self.handle.is_some()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TimeQueryReturn {
pub time: Option<LogicalTime>,
}
impl TimeQueryReturn {
pub fn time_is_valid(&self) -> bool {
self.time.is_some()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SupplementalReflectInfo {
pub producing_federate: FederateHandle,
pub sent_regions: Option<ConveyedRegionSet>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SupplementalReceiveInfo {
pub producing_federate: FederateHandle,
pub sent_regions: Option<ConveyedRegionSet>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct JoinResult {
pub federate_handle: FederateHandle,
pub logical_time_implementation_name: String,
pub time_kind: TimeKind,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum FomModule {
File(PathBuf),
Content {
name: String,
content: Bytes,
},
Compressed(Bytes),
Url(String),
}
impl FomModule {
pub fn file(path: impl Into<PathBuf>) -> Self {
FomModule::File(path.into())
}
pub fn content(name: impl Into<String>, content: impl Into<Bytes>) -> Self {
FomModule::Content { name: name.into(), content: content.into() }
}
pub fn compressed(archive: impl Into<Bytes>) -> Self {
FomModule::Compressed(archive.into())
}
pub fn url(url: impl Into<String>) -> Self {
FomModule::Url(url.into())
}
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) })
}
}