1use std::collections::{BTreeMap, HashMap, HashSet};
30use std::time::Instant;
31
32use crate::error::DecodeError;
33use crate::parameter::{Parameter, ParameterList, SecurityParameters};
34use crate::pl::{PlBuilder, PlValues, decode_pl_payload, encode_pl_payload, pid};
35use crate::qos::{
36 DurabilityKind, DurabilityService, Liveliness, QosPolicyId, Reliability, RxO,
37 incompatible_policies, partitions_match,
38};
39use crate::receiver::receive;
40use crate::reliable::{
41 Change, Outgoing, ReaderConfig, ReliableReader, ReliableWriter, WriterConfig,
42};
43use crate::spdp::ParticipantData;
44use crate::submessage::{PayloadKind, SerializedPayload, Submessage};
45use crate::types::{
46 BuiltinEndpointSet, Duration, EntityId, Guid, GuidPrefix, Locator, SequenceNumber, VendorId,
47};
48use crate::wire::Endianness;
49
50use rustorb_cdr::{ByteOrder, Decoder, Encoding};
51use rustorb_xtypes::assignability::{
52 Consistency, EndpointType, TypeConsistency, TypeConsistencyKind, check_consistency,
53};
54use rustorb_xtypes::registry::TypeRegistry;
55use rustorb_xtypes::type_object::{TypeIdentifier, TypeInformation};
56use rustorb_xtypes::xcdr2::Xcdr2;
57
58pub mod data_representation {
60 pub const XCDR: i16 = 0;
62 pub const XML: i16 = 1;
64 pub const XCDR2: i16 = 2;
66}
67
68#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct EndpointData {
74 pub guid: Guid,
76 pub participant_guid: Guid,
78 pub topic_name: String,
80 pub type_name: String,
82 pub reliability: Reliability,
84 pub durability: DurabilityKind,
86 pub durability_service: Option<DurabilityService>,
88 pub deadline: Duration,
90 pub liveliness: Liveliness,
92 pub partitions: Vec<String>,
94 pub user_data: Vec<u8>,
96 pub unicast_locators: Vec<Locator>,
99 pub multicast_locators: Vec<Locator>,
101 pub expects_inline_qos: bool,
103 pub type_information: Option<TypeInformation>,
105 pub data_representation: Vec<i16>,
108 pub type_consistency: Option<TypeConsistency>,
110 pub content_filter: Option<ContentFilterProperty>,
114 pub related_entity_guid: Option<Guid>,
118 pub service_instance_name: Option<String>,
121 pub topic_aliases: Vec<String>,
126 pub data_tags: Vec<(String, String)>,
129 pub security: SecurityParameters,
132}
133
134#[derive(Clone, Debug, Default, PartialEq, Eq)]
137pub struct ContentFilterProperty {
138 pub content_filtered_topic_name: String,
140 pub related_topic_name: String,
142 pub filter_class_name: String,
144 pub filter_expression: String,
146 pub expression_parameters: Vec<String>,
148}
149
150impl ContentFilterProperty {
151 pub fn signature(&self) -> [u8; 16] {
154 let mut bytes = Vec::new();
155 for s in [
156 &self.content_filtered_topic_name,
157 &self.related_topic_name,
158 &self.filter_class_name,
159 &self.filter_expression,
160 ]
161 .into_iter()
162 .chain(&self.expression_parameters)
163 {
164 bytes.extend_from_slice(s.as_bytes());
165 bytes.push(0);
166 }
167 rustorb_typesupport::md5(&bytes)
168 }
169}
170
171impl EndpointData {
172 pub fn writer(guid: Guid, topic_name: &str, type_name: &str) -> Self {
174 Self::new(guid, topic_name, type_name, Reliability::writer_default())
175 }
176
177 pub fn reader(guid: Guid, topic_name: &str, type_name: &str) -> Self {
179 Self::new(guid, topic_name, type_name, Reliability::reader_default())
180 }
181
182 fn new(guid: Guid, topic_name: &str, type_name: &str, reliability: Reliability) -> Self {
183 EndpointData {
184 guid,
185 participant_guid: Guid::new(guid.prefix, EntityId::PARTICIPANT),
186 topic_name: topic_name.to_owned(),
187 type_name: type_name.to_owned(),
188 reliability,
189 durability: DurabilityKind::Volatile,
190 durability_service: None,
191 deadline: Duration::INFINITE,
192 liveliness: Liveliness::default(),
193 partitions: Vec::new(),
194 user_data: Vec::new(),
195 unicast_locators: Vec::new(),
196 multicast_locators: Vec::new(),
197 expects_inline_qos: false,
198 type_information: None,
199 data_representation: Vec::new(),
200 type_consistency: None,
201 content_filter: None,
202 related_entity_guid: None,
203 service_instance_name: None,
204 topic_aliases: Vec::new(),
205 data_tags: Vec::new(),
206 security: SecurityParameters::default(),
207 }
208 }
209
210 pub fn offered_representation(&self) -> i16 {
213 self.data_representation
214 .first()
215 .copied()
216 .unwrap_or(data_representation::XCDR)
217 }
218
219 pub fn accepts_representation(&self, id: i16) -> bool {
221 if self.data_representation.is_empty() {
222 id == data_representation::XCDR
223 } else {
224 self.data_representation.contains(&id)
225 }
226 }
227
228 pub fn effective_type_consistency(&self) -> TypeConsistency {
235 match (&self.type_consistency, &self.type_information) {
236 (Some(c), _) => *c,
237 (None, Some(_)) => TypeConsistency::default(),
238 (None, None) => TypeConsistency::NOT_ANNOUNCED,
239 }
240 }
241
242 fn endpoint_type(&self) -> EndpointType<'_> {
243 EndpointType {
244 name: &self.type_name,
245 information: self.type_information.as_ref(),
246 }
247 }
248
249 pub fn to_parameter_list(&self, endianness: Endianness) -> ParameterList {
253 let b = PlBuilder::new(endianness);
254 let mut l = ParameterList::new();
255 l.push(b.guid(pid::ENDPOINT_GUID, self.guid));
256 l.push(b.guid(pid::PARTICIPANT_GUID, self.participant_guid));
257 l.push(b.string(pid::TOPIC_NAME, &self.topic_name));
258 l.push(b.string(pid::TYPE_NAME, &self.type_name));
259 l.push(self.reliability.to_parameter(&b));
260 l.push(self.durability.to_parameter(&b));
261 if let Some(ds) = &self.durability_service {
262 l.push(ds.to_parameter(&b));
263 }
264 if self.deadline != Duration::INFINITE {
265 l.push(b.duration(pid::DEADLINE, self.deadline));
266 }
267 if self.liveliness != Liveliness::default() {
268 l.push(self.liveliness.to_parameter(&b));
269 }
270 if !self.partitions.is_empty() {
271 l.push(b.strings(pid::PARTITION, &self.partitions));
272 }
273 if !self.user_data.is_empty() {
274 l.push(b.octets(pid::USER_DATA, &self.user_data));
275 }
276 for loc in &self.unicast_locators {
277 l.push(b.locator(pid::UNICAST_LOCATOR, loc));
278 }
279 for loc in &self.multicast_locators {
280 l.push(b.locator(pid::MULTICAST_LOCATOR, loc));
281 }
282 if self.expects_inline_qos {
283 l.push(b.bool(pid::EXPECTS_INLINE_QOS, true));
284 }
285 let order = byte_order(endianness);
286 if !self.data_representation.is_empty() {
287 let mut v = Vec::new();
288 put_u32(&mut v, self.data_representation.len() as u32, order);
289 for id in &self.data_representation {
290 put_u16(&mut v, *id as u16, order);
291 }
292 v.resize(v.len().next_multiple_of(4), 0);
293 l.push(Parameter::new(pid::DATA_REPRESENTATION, v));
294 }
295 if let Some(c) = &self.type_consistency {
296 let mut v = Vec::new();
297 let kind = match c.kind {
298 TypeConsistencyKind::DisallowTypeCoercion => 0,
299 TypeConsistencyKind::AllowTypeCoercion => 1,
300 };
301 put_u16(&mut v, kind, order);
302 v.extend(
303 [
304 c.ignore_sequence_bounds,
305 c.ignore_string_bounds,
306 c.ignore_member_names,
307 c.prevent_type_widening,
308 c.force_type_validation,
309 ]
310 .map(u8::from),
311 );
312 v.resize(8, 0);
313 l.push(Parameter::new(pid::TYPE_CONSISTENCY_ENFORCEMENT, v));
314 }
315 if let Some(f) = &self.content_filter {
316 l.push(b.content_filter(pid::CONTENT_FILTER_PROPERTY, f));
317 }
318 if let Some(g) = self.related_entity_guid {
319 l.push(b.guid(pid::RELATED_ENTITY_GUID, g));
320 }
321 if let Some(n) = &self.service_instance_name {
322 l.push(b.string(pid::SERVICE_INSTANCE_NAME, n));
323 }
324 if !self.topic_aliases.is_empty() {
325 l.push(b.strings(pid::TOPIC_ALIASES, &self.topic_aliases));
326 }
327 if !self.data_tags.is_empty() {
328 l.push(b.string_pairs(pid::DATA_TAGS, &self.data_tags));
329 }
330 if let Some(info) = &self.type_information {
331 if let Ok(mut v) = info.to_bytes(order) {
333 v.resize(v.len().next_multiple_of(4), 0);
334 l.push(Parameter::new(pid::TYPE_INFORMATION, v));
335 }
336 }
337 for p in self.security.of(endianness) {
338 l.push(p.clone());
339 }
340 l
341 }
342
343 pub fn to_payload(&self, endianness: Endianness) -> Vec<u8> {
345 encode_pl_payload(&self.to_parameter_list(endianness), endianness)
346 }
347
348 pub fn from_parameter_list(
357 list: &ParameterList,
358 endianness: Endianness,
359 writer: bool,
360 ) -> Result<Self, DecodeError> {
361 let v = PlValues::new(endianness);
362 let mut guid = None;
363 let mut participant = None;
364 let mut topic = None;
365 let mut type_name = None;
366 let mut d = EndpointData::new(
367 Guid::UNKNOWN,
368 "",
369 "",
370 if writer {
371 Reliability::writer_default()
372 } else {
373 Reliability::reader_default()
374 },
375 );
376 for p in &list.parameters {
377 match p.id {
378 pid::ENDPOINT_GUID => guid = Some(v.guid(p)?),
379 pid::PARTICIPANT_GUID => participant = Some(v.guid(p)?),
380 pid::TOPIC_NAME => topic = Some(v.string(p)?),
381 pid::TYPE_NAME => type_name = Some(v.string(p)?),
382 pid::RELIABILITY => d.reliability = Reliability::from_parameter(&v, p)?,
383 pid::DURABILITY => d.durability = DurabilityKind::from_parameter(&v, p)?,
384 pid::DURABILITY_SERVICE => {
385 d.durability_service = DurabilityService::from_parameter(&v, p).ok()
386 }
387 pid::DEADLINE => d.deadline = v.duration(p)?,
388 pid::LIVELINESS => d.liveliness = Liveliness::from_parameter(&v, p)?,
389 pid::PARTITION => d.partitions = v.strings(p)?,
390 pid::USER_DATA => d.user_data = v.octets(p)?,
391 pid::UNICAST_LOCATOR => d.unicast_locators.push(v.locator(p)?),
392 pid::MULTICAST_LOCATOR => d.multicast_locators.push(v.locator(p)?),
393 pid::EXPECTS_INLINE_QOS => d.expects_inline_qos = v.bool(p)?,
394 pid::DATA_REPRESENTATION => {
397 d.data_representation =
398 read_representations(&p.value, endianness).unwrap_or_default()
399 }
400 pid::TYPE_CONSISTENCY_ENFORCEMENT => {
401 d.type_consistency = read_type_consistency(&p.value, endianness)
402 }
403 pid::TYPE_INFORMATION => {
404 d.type_information = read_type_information(&p.value, endianness)
405 }
406 pid::CONTENT_FILTER_PROPERTY => d.content_filter = v.content_filter(p).ok(),
409 pid::RELATED_ENTITY_GUID => d.related_entity_guid = v.guid(p).ok(),
411 pid::SERVICE_INSTANCE_NAME => d.service_instance_name = v.string(p).ok(),
412 pid::TOPIC_ALIASES => d.topic_aliases = v.strings(p).unwrap_or_default(),
413 pid::DATA_TAGS => d.data_tags = v.string_pairs(p).unwrap_or_default(),
414 id if SecurityParameters::is_security(id) => d.security.push(p.clone(), endianness),
415 id if !id.is_vendor_specific() && id.must_understand() => {
416 return Err(DecodeError::MustUnderstand(id));
417 }
418 _ => {}
419 }
420 }
421 d.guid = guid.ok_or(DecodeError::MissingParameter(pid::ENDPOINT_GUID))?;
422 d.participant_guid = participant.unwrap_or(Guid::new(d.guid.prefix, EntityId::PARTICIPANT));
423 d.topic_name = topic.ok_or(DecodeError::MissingParameter(pid::TOPIC_NAME))?;
424 d.type_name = type_name.ok_or(DecodeError::MissingParameter(pid::TYPE_NAME))?;
425 Ok(d)
426 }
427
428 pub fn from_payload(bytes: &[u8], writer: bool) -> Result<Self, DecodeError> {
430 let (list, e) = decode_pl_payload(bytes)?;
431 Self::from_parameter_list(&list, e, writer)
432 }
433
434 pub fn rxo(&self) -> RxO {
436 RxO {
437 reliability: self.reliability.kind,
438 durability: self.durability,
439 deadline: self.deadline,
440 liveliness: self.liveliness,
441 }
442 }
443}
444
445pub const DATA_REPRESENTATION_QOS_POLICY_ID: QosPolicyId = QosPolicyId(23);
447
448#[derive(Clone, Debug, PartialEq, Eq)]
450pub enum Match {
451 Matched,
453 Incompatible(Vec<QosPolicyId>),
456 Inconsistent,
459 Unresolved(Vec<TypeIdentifier>),
462 Unrelated,
464}
465
466pub fn match_endpoints(
470 writer: &EndpointData,
471 reader: &EndpointData,
472 registry: &TypeRegistry,
473) -> Match {
474 if !same_topic(writer, reader) {
475 return Match::Unrelated;
476 }
477 match check_consistency(
478 writer.endpoint_type(),
479 reader.endpoint_type(),
480 &reader.effective_type_consistency(),
481 registry,
482 ) {
483 Consistency::Consistent => {}
484 Consistency::Inconsistent => return Match::Inconsistent,
485 Consistency::Unknown(missing) => return Match::Unresolved(missing),
486 }
487 if !partitions_match(&writer.partitions, &reader.partitions) {
488 return Match::Unrelated;
489 }
490 let mut bad = incompatible_policies(&writer.rxo(), &reader.rxo());
491 if !reader.accepts_representation(writer.offered_representation()) {
492 bad.push(DATA_REPRESENTATION_QOS_POLICY_ID);
493 }
494 if bad.is_empty() {
495 Match::Matched
496 } else {
497 Match::Incompatible(bad)
498 }
499}
500
501pub fn same_topic(a: &EndpointData, b: &EndpointData) -> bool {
504 a.topic_name == b.topic_name
505 || a.topic_aliases.contains(&b.topic_name)
506 || b.topic_aliases.contains(&a.topic_name)
507}
508
509pub fn endpoints_match(writer: &EndpointData, reader: &EndpointData) -> bool {
513 match_endpoints(writer, reader, &TypeRegistry::new()) == Match::Matched
514}
515
516fn byte_order(e: Endianness) -> ByteOrder {
517 match e {
518 Endianness::Big => ByteOrder::Big,
519 Endianness::Little => ByteOrder::Little,
520 }
521}
522
523fn put_u16(v: &mut Vec<u8>, x: u16, order: ByteOrder) {
524 v.extend(match order {
525 ByteOrder::Big => x.to_be_bytes(),
526 ByteOrder::Little => x.to_le_bytes(),
527 });
528}
529
530fn put_u32(v: &mut Vec<u8>, x: u32, order: ByteOrder) {
531 v.extend(match order {
532 ByteOrder::Big => x.to_be_bytes(),
533 ByteOrder::Little => x.to_le_bytes(),
534 });
535}
536
537fn read_representations(value: &[u8], e: Endianness) -> Option<Vec<i16>> {
540 let mut dec = Decoder::new(value, byte_order(e), Encoding::Xcdr1);
541 let n = dec.read_u32().ok()? as usize;
542 if n > value.len() / 2 {
543 return None;
544 }
545 (0..n).map(|_| dec.read_i16().ok()).collect()
546}
547
548fn read_type_consistency(value: &[u8], e: Endianness) -> Option<TypeConsistency> {
551 let mut dec = Decoder::new(value, byte_order(e), Encoding::Xcdr1);
552 let kind = match dec.read_u16().ok()? {
553 0 => TypeConsistencyKind::DisallowTypeCoercion,
554 1 => TypeConsistencyKind::AllowTypeCoercion,
555 _ => return None,
556 };
557 let mut c = TypeConsistency {
558 kind,
559 ..TypeConsistency::default()
560 };
561 for field in [
562 &mut c.ignore_sequence_bounds,
563 &mut c.ignore_string_bounds,
564 &mut c.ignore_member_names,
565 &mut c.prevent_type_widening,
566 &mut c.force_type_validation,
567 ] {
568 match dec.read_octet() {
569 Ok(b) => *field = b != 0,
570 Err(_) => break,
571 }
572 }
573 Some(c)
574}
575
576fn read_type_information(value: &[u8], e: Endianness) -> Option<TypeInformation> {
578 let mut dec = Decoder::new(value, byte_order(e), Encoding::Xcdr2);
579 let info = TypeInformation::decode(&mut dec).ok()?;
580 (dec.remaining() < 4).then_some(info)
581}
582
583#[derive(Clone, Debug, Default)]
585pub struct SedpConfig {
586 pub writer: WriterConfig,
588 pub reader: ReaderConfig,
590}
591
592#[derive(Clone, Debug, PartialEq, Eq)]
594pub enum SedpEvent {
595 WriterDiscovered(EndpointData),
597 WriterUpdated(EndpointData),
599 WriterRemoved(Guid),
601 ReaderDiscovered(EndpointData),
603 ReaderUpdated(EndpointData),
605 ReaderRemoved(Guid),
607 Matched {
609 local: Guid,
611 remote: Guid,
613 },
614 Unmatched {
616 local: Guid,
618 remote: Guid,
620 },
621 InconsistentTopic {
624 local: Guid,
626 remote: Guid,
628 },
629 IncompatibleQos {
632 local: Guid,
634 remote: Guid,
636 policies: Vec<QosPolicyId>,
638 },
639}
640
641const STATUS_DISPOSED: u8 = 0x01;
643const STATUS_UNREGISTERED: u8 = 0x02;
644
645#[derive(Debug)]
646struct Local {
647 data: EndpointData,
648 sn: SequenceNumber,
649 secure: bool,
651}
652
653#[derive(Debug)]
655struct Endpoints {
656 secure: bool,
657 pub_writer: ReliableWriter,
658 pub_reader: ReliableReader,
659 sub_writer: ReliableWriter,
660 sub_reader: ReliableReader,
661}
662
663impl Endpoints {
664 fn ids(secure: bool) -> [EntityId; 4] {
667 if secure {
668 [
669 EntityId::SEDP_BUILTIN_PUBLICATIONS_SECURE_WRITER,
670 EntityId::SEDP_BUILTIN_PUBLICATIONS_SECURE_READER,
671 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_WRITER,
672 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_READER,
673 ]
674 } else {
675 [
676 EntityId::SEDP_BUILTIN_PUBLICATIONS_ANNOUNCER,
677 EntityId::SEDP_BUILTIN_PUBLICATIONS_DETECTOR,
678 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_ANNOUNCER,
679 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_DETECTOR,
680 ]
681 }
682 }
683
684 fn bits(secure: bool) -> [u32; 4] {
686 if secure {
687 [
688 BuiltinEndpointSet::PUBLICATIONS_SECURE_WRITER,
689 BuiltinEndpointSet::PUBLICATIONS_SECURE_READER,
690 BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_WRITER,
691 BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_READER,
692 ]
693 } else {
694 [
695 BuiltinEndpointSet::PUBLICATIONS_ANNOUNCER,
696 BuiltinEndpointSet::PUBLICATIONS_DETECTOR,
697 BuiltinEndpointSet::SUBSCRIPTIONS_ANNOUNCER,
698 BuiltinEndpointSet::SUBSCRIPTIONS_DETECTOR,
699 ]
700 }
701 }
702
703 fn new(prefix: GuidPrefix, vendor_id: VendorId, config: &SedpConfig, secure: bool) -> Self {
704 let [pw, pr, sw, sr] = Self::ids(secure);
705 let g = |e| Guid::new(prefix, e);
706 Endpoints {
707 secure,
708 pub_writer: ReliableWriter::new(g(pw), vendor_id, config.writer.clone()),
709 pub_reader: ReliableReader::new(g(pr), vendor_id, config.reader.clone()),
710 sub_writer: ReliableWriter::new(g(sw), vendor_id, config.writer.clone()),
711 sub_reader: ReliableReader::new(g(sr), vendor_id, config.reader.clone()),
712 }
713 }
714
715 fn find<'a>(
718 plain: &'a mut Endpoints,
719 secure: Option<&'a mut Endpoints>,
720 writer_id: EntityId,
721 ) -> Option<(&'a mut Endpoints, Kind)> {
722 let set = if Self::ids(false).contains(&writer_id) {
723 plain
724 } else if Self::ids(true).contains(&writer_id) {
725 secure?
726 } else {
727 return None;
728 };
729 let [pw, _, sw, _] = Self::ids(set.secure);
730 if writer_id == pw {
731 Some((set, Kind::Writer))
732 } else if writer_id == sw {
733 Some((set, Kind::Reader))
734 } else {
735 None
736 }
737 }
738
739 fn writer(&mut self, kind: Kind) -> &mut ReliableWriter {
740 match kind {
741 Kind::Writer => &mut self.pub_writer,
742 Kind::Reader => &mut self.sub_writer,
743 }
744 }
745
746 fn add_participant(&mut self, p: &ParticipantData, now: Instant) {
747 let set = p.available_builtin_endpoints;
748 let uc = p.metatraffic_unicast_locators.clone();
749 let mc = p.metatraffic_multicast_locators.clone();
750 let g = |e| Guid::new(p.guid_prefix, e);
751 let [pw, pr, sw, sr] = Self::ids(self.secure);
752 let [bpw, bpr, bsw, bsr] = Self::bits(self.secure);
753 if set.contains(bpr) {
754 self.pub_writer.add_reader(g(pr), uc.clone(), mc.clone());
755 }
756 if set.contains(bpw) {
757 self.pub_reader
758 .add_writer(g(pw), uc.clone(), mc.clone(), now);
759 }
760 if set.contains(bsr) {
761 self.sub_writer.add_reader(g(sr), uc.clone(), mc.clone());
762 }
763 if set.contains(bsw) {
764 self.sub_reader.add_writer(g(sw), uc, mc, now);
765 }
766 }
767
768 fn remove_participant(&mut self, prefix: &GuidPrefix) {
769 self.pub_writer.remove_readers_of(prefix);
770 self.pub_reader.remove_writers_of(prefix);
771 self.sub_writer.remove_readers_of(prefix);
772 self.sub_reader.remove_writers_of(prefix);
773 }
774
775 fn poll(&mut self, now: Instant) -> Vec<Outgoing> {
776 let mut out = self.pub_writer.poll(now);
777 out.extend(self.sub_writer.poll(now));
778 out.extend(self.pub_reader.poll(now));
779 out.extend(self.sub_reader.poll(now));
780 out
781 }
782
783 fn next_deadline(&self) -> Option<Instant> {
784 [
785 self.pub_writer.next_deadline(),
786 self.sub_writer.next_deadline(),
787 self.pub_reader.next_deadline(),
788 self.sub_reader.next_deadline(),
789 ]
790 .into_iter()
791 .flatten()
792 .min()
793 }
794}
795
796#[derive(Clone, Copy, Debug, PartialEq, Eq)]
797enum Kind {
798 Writer,
799 Reader,
800}
801
802#[derive(Debug)]
805pub struct Sedp {
806 prefix: GuidPrefix,
807 vendor_id: VendorId,
808 config: SedpConfig,
809 plain: Endpoints,
810 secure: Option<Endpoints>,
812 participants: HashMap<GuidPrefix, (Vec<Locator>, Vec<Locator>)>,
814 local_writers: BTreeMap<Guid, Local>,
815 local_readers: BTreeMap<Guid, Local>,
816 remote_writers: HashMap<Guid, EndpointData>,
817 remote_readers: HashMap<Guid, EndpointData>,
818 matches: HashSet<(Guid, Guid)>,
820 incompatible: HashSet<(Guid, Guid)>,
822 inconsistent: HashSet<(Guid, Guid)>,
825 unresolved: HashMap<(Guid, Guid), Vec<TypeIdentifier>>,
827 registry: TypeRegistry,
829}
830
831impl Sedp {
832 pub const BUILTIN_ENDPOINTS: u32 = BuiltinEndpointSet::PUBLICATIONS_ANNOUNCER
835 | BuiltinEndpointSet::PUBLICATIONS_DETECTOR
836 | BuiltinEndpointSet::SUBSCRIPTIONS_ANNOUNCER
837 | BuiltinEndpointSet::SUBSCRIPTIONS_DETECTOR;
838
839 pub const BUILTIN_ENDPOINTS_SECURE: u32 = BuiltinEndpointSet::PUBLICATIONS_SECURE_WRITER
842 | BuiltinEndpointSet::PUBLICATIONS_SECURE_READER
843 | BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_WRITER
844 | BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_READER;
845
846 pub fn new(prefix: GuidPrefix, vendor_id: VendorId, config: SedpConfig) -> Self {
848 Sedp {
849 prefix,
850 vendor_id,
851 plain: Endpoints::new(prefix, vendor_id, &config, false),
852 secure: None,
853 config,
854 participants: HashMap::new(),
855 local_writers: BTreeMap::new(),
856 local_readers: BTreeMap::new(),
857 remote_writers: HashMap::new(),
858 remote_readers: HashMap::new(),
859 matches: HashSet::new(),
860 incompatible: HashSet::new(),
861 inconsistent: HashSet::new(),
862 unresolved: HashMap::new(),
863 registry: TypeRegistry::new(),
864 }
865 }
866
867 pub fn add_participant(&mut self, p: &ParticipantData, now: Instant) {
872 if p.guid_prefix == self.prefix {
873 return;
874 }
875 self.plain.add_participant(p, now);
876 if let Some(s) = self.secure.as_mut() {
877 s.add_participant(p, now);
878 }
879 self.participants.insert(
880 p.guid_prefix,
881 (
882 p.default_unicast_locators.clone(),
883 p.default_multicast_locators.clone(),
884 ),
885 );
886 }
887
888 pub fn remove_participant(&mut self, prefix: &GuidPrefix) -> Vec<SedpEvent> {
891 self.plain.remove_participant(prefix);
892 if let Some(s) = self.secure.as_mut() {
893 s.remove_participant(prefix);
894 }
895 self.participants.remove(prefix);
896 let mut events = Vec::new();
897 let writers: Vec<Guid> = self
898 .remote_writers
899 .keys()
900 .filter(|g| g.prefix == *prefix)
901 .copied()
902 .collect();
903 for g in writers {
904 self.remove_remote(Kind::Writer, g, &mut events);
905 }
906 let readers: Vec<Guid> = self
907 .remote_readers
908 .keys()
909 .filter(|g| g.prefix == *prefix)
910 .copied()
911 .collect();
912 for g in readers {
913 self.remove_remote(Kind::Reader, g, &mut events);
914 }
915 events
916 }
917
918 pub fn add_writer(&mut self, data: EndpointData) -> Vec<SedpEvent> {
921 self.add_local(Kind::Writer, data)
922 }
923
924 pub fn add_reader(&mut self, data: EndpointData) -> Vec<SedpEvent> {
927 self.add_local(Kind::Reader, data)
928 }
929
930 pub fn remove_writer(&mut self, guid: &Guid) -> Vec<SedpEvent> {
932 self.remove_local(Kind::Writer, guid)
933 }
934
935 pub fn remove_reader(&mut self, guid: &Guid) -> Vec<SedpEvent> {
937 self.remove_local(Kind::Reader, guid)
938 }
939
940 pub fn is_announced_to(&self, local: &Guid, prefix: &GuidPrefix) -> bool {
944 let (l, writer) = match (self.local_writers.get(local), self.local_readers.get(local)) {
945 (Some(l), _) => (l, true),
946 (None, Some(l)) => (l, false),
947 (None, None) => return false,
948 };
949 let set = match (l.secure, self.secure.as_ref()) {
950 (true, Some(s)) => s,
951 _ => &self.plain,
952 };
953 let w = if writer {
954 &set.pub_writer
955 } else {
956 &set.sub_writer
957 };
958 w.is_acked_by_participant(prefix, l.sn)
959 }
960
961 pub fn remote_writers(&self) -> impl Iterator<Item = &EndpointData> {
963 self.remote_writers.values()
964 }
965
966 pub fn remote_readers(&self) -> impl Iterator<Item = &EndpointData> {
968 self.remote_readers.values()
969 }
970
971 pub fn remote_writer(&self, guid: &Guid) -> Option<&EndpointData> {
973 self.remote_writers.get(guid)
974 }
975
976 pub fn remote_reader(&self, guid: &Guid) -> Option<&EndpointData> {
978 self.remote_readers.get(guid)
979 }
980
981 pub fn registry(&self) -> &TypeRegistry {
983 &self.registry
984 }
985
986 pub fn registry_mut(&mut self) -> &mut TypeRegistry {
989 &mut self.registry
990 }
991
992 pub fn unresolved_types(&self) -> Vec<(TypeIdentifier, Guid)> {
995 let mut out: Vec<(TypeIdentifier, Guid)> = Vec::new();
996 for ((_, remote), ids) in &self.unresolved {
997 for id in ids {
998 if !out.iter().any(|(i, _)| i == id) {
999 out.push((id.clone(), *remote));
1000 }
1001 }
1002 }
1003 out
1004 }
1005
1006 pub fn rematch_unresolved(&mut self) -> Vec<SedpEvent> {
1008 let mut pairs: Vec<(Guid, Guid)> = self.unresolved.keys().copied().collect();
1009 pairs.sort();
1010 let mut events = Vec::new();
1011 for (local, remote) in pairs {
1012 let kind = if self.local_writers.contains_key(&local) {
1013 Kind::Writer
1014 } else {
1015 Kind::Reader
1016 };
1017 self.update_match(kind, local, remote, &mut events);
1018 }
1019 events
1020 }
1021
1022 pub fn matched(&self, local: &Guid) -> impl Iterator<Item = &Guid> {
1024 self.matches
1025 .iter()
1026 .filter(move |(l, _)| l == local)
1027 .map(|(_, r)| r)
1028 }
1029
1030 pub fn handle_message(&mut self, bytes: &[u8], now: Instant) -> Vec<SedpEvent> {
1032 let Some((_, received)) = receive(bytes, self.prefix) else {
1033 return Vec::new();
1034 };
1035 let mut changes: Vec<(Kind, Change)> = Vec::new();
1036 for r in received {
1037 let src = r.source_prefix;
1038 let writer_id = match &r.submessage {
1039 Submessage::Data(d) => d.writer_id,
1040 Submessage::DataFrag(d) => d.writer_id,
1041 Submessage::Gap(g) => g.writer_id,
1042 Submessage::Heartbeat(h) => h.writer_id,
1043 Submessage::NackFrag(n) => n.writer_id,
1044 Submessage::AckNack(a) => a.writer_id,
1045 _ => continue,
1046 };
1047 let Some((set, kind)) =
1048 Endpoints::find(&mut self.plain, self.secure.as_mut(), writer_id)
1049 else {
1050 continue;
1051 };
1052 let w = Guid::new(src, writer_id);
1053 let (writer, reader) = match kind {
1054 Kind::Writer => (&mut set.pub_writer, &mut set.pub_reader),
1055 Kind::Reader => (&mut set.sub_writer, &mut set.sub_reader),
1056 };
1057 let got = match r.submessage {
1058 Submessage::Data(d) => reader.handle_data(w, &d, r.timestamp),
1059 Submessage::DataFrag(d) => reader.handle_data_frag(w, &d, r.timestamp),
1060 Submessage::Gap(g) => reader.handle_gap(w, &g),
1061 Submessage::Heartbeat(h) => reader.handle_heartbeat(w, &h, now),
1062 Submessage::NackFrag(n) => {
1063 writer.handle_nackfrag(Guid::new(src, n.reader_id), &n, now);
1064 Vec::new()
1065 }
1066 Submessage::AckNack(a) => {
1067 writer.handle_acknack(Guid::new(src, a.reader_id), &a, now);
1068 Vec::new()
1069 }
1070 _ => Vec::new(),
1071 };
1072 changes.extend(got.into_iter().map(|c| (kind, c)));
1073 }
1074 let mut events = Vec::new();
1075 for (kind, c) in changes {
1076 self.apply(kind, &c, &mut events);
1077 }
1078 events
1079 }
1080
1081 pub fn poll(&mut self, now: Instant) -> Vec<Outgoing> {
1083 let mut out = self.plain.poll(now);
1084 if let Some(s) = self.secure.as_mut() {
1085 out.extend(s.poll(now));
1086 }
1087 out
1088 }
1089
1090 pub fn next_deadline(&self) -> Option<Instant> {
1093 [
1094 self.plain.next_deadline(),
1095 self.secure.as_ref().and_then(Endpoints::next_deadline),
1096 ]
1097 .into_iter()
1098 .flatten()
1099 .min()
1100 }
1101
1102 pub fn enable_secure(&mut self) {
1107 if self.secure.is_none() {
1108 self.secure = Some(Endpoints::new(
1109 self.prefix,
1110 self.vendor_id,
1111 &self.config,
1112 true,
1113 ));
1114 }
1115 }
1116
1117 pub fn add_writer_secure(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1120 self.add_local_on(Kind::Writer, data, true)
1121 }
1122
1123 pub fn add_reader_secure(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1126 self.add_local_on(Kind::Reader, data, true)
1127 }
1128
1129 fn set(&mut self, secure: bool) -> &mut Endpoints {
1130 match (secure, self.secure.as_mut()) {
1131 (true, Some(s)) => s,
1132 _ => &mut self.plain,
1133 }
1134 }
1135
1136 fn add_local(&mut self, kind: Kind, data: EndpointData) -> Vec<SedpEvent> {
1137 self.add_local_on(kind, data, false)
1138 }
1139
1140 fn add_local_on(&mut self, kind: Kind, data: EndpointData, secure: bool) -> Vec<SedpEvent> {
1141 let secure = secure && self.secure.is_some();
1142 let mut qos = ParameterList::new();
1143 qos.push(Parameter::new(pid::KEY_HASH, data.guid.to_bytes()));
1144 let payload = SerializedPayload {
1145 kind: PayloadKind::Data,
1146 bytes: data.to_payload(Endianness::NATIVE),
1147 };
1148 let old = match kind {
1149 Kind::Writer => self.local_writers.remove(&data.guid),
1150 Kind::Reader => self.local_readers.remove(&data.guid),
1151 };
1152 if let Some(old) = &old {
1154 self.set(old.secure).writer(kind).remove_change(old.sn);
1155 }
1156 let sn = self
1157 .set(secure)
1158 .writer(kind)
1159 .add_change(Some(qos), Some(payload));
1160 let local = Local {
1161 data: data.clone(),
1162 sn,
1163 secure,
1164 };
1165 match kind {
1166 Kind::Writer => self.local_writers.insert(data.guid, local),
1167 Kind::Reader => self.local_readers.insert(data.guid, local),
1168 };
1169 let mut events = Vec::new();
1170 let remotes: Vec<Guid> = match kind {
1171 Kind::Writer => self.remote_readers.keys().copied().collect(),
1172 Kind::Reader => self.remote_writers.keys().copied().collect(),
1173 };
1174 for r in remotes {
1175 self.update_match(kind, data.guid, r, &mut events);
1176 }
1177 events
1178 }
1179
1180 fn remove_local(&mut self, kind: Kind, guid: &Guid) -> Vec<SedpEvent> {
1181 let old = match kind {
1182 Kind::Writer => self.local_writers.remove(guid),
1183 Kind::Reader => self.local_readers.remove(guid),
1184 };
1185 let Some(old) = old else {
1186 return Vec::new();
1187 };
1188 self.incompatible.retain(|(l, _)| l != guid);
1189 self.inconsistent.retain(|(l, _)| l != guid);
1190 self.unresolved.retain(|(l, _), _| l != guid);
1191 let writer = self.set(old.secure).writer(kind);
1192 writer.remove_change(old.sn);
1193 let e = Endianness::NATIVE;
1195 let b = PlBuilder::new(e);
1196 let mut qos = ParameterList::new();
1197 qos.push(Parameter::new(pid::KEY_HASH, guid.to_bytes()));
1198 qos.push(Parameter::new(
1199 pid::STATUS_INFO,
1200 [0, 0, 0, STATUS_DISPOSED | STATUS_UNREGISTERED],
1201 ));
1202 let mut key = ParameterList::new();
1203 key.push(b.guid(pid::ENDPOINT_GUID, *guid));
1204 writer.add_change(
1205 Some(qos),
1206 Some(SerializedPayload {
1207 kind: PayloadKind::Key,
1208 bytes: encode_pl_payload(&key, e),
1209 }),
1210 );
1211 let mut events = Vec::new();
1212 let pairs: Vec<(Guid, Guid)> = self
1213 .matches
1214 .iter()
1215 .filter(|(l, _)| l == guid)
1216 .copied()
1217 .collect();
1218 for (l, r) in pairs {
1219 self.matches.remove(&(l, r));
1220 events.push(SedpEvent::Unmatched {
1221 local: l,
1222 remote: r,
1223 });
1224 }
1225 events
1226 }
1227
1228 fn apply(&mut self, kind: Kind, c: &Change, events: &mut Vec<SedpEvent>) {
1231 let status = c
1232 .inline_qos
1233 .as_ref()
1234 .and_then(|q| q.get(pid::STATUS_INFO))
1235 .and_then(|p| p.value.get(3).copied())
1236 .unwrap_or(0);
1237 if status & (STATUS_DISPOSED | STATUS_UNREGISTERED) != 0 {
1238 if let Some(g) = disposed_key(c) {
1239 self.remove_remote(kind, g, events);
1240 }
1241 return;
1242 }
1243 let Some(p) = c.payload.as_ref().filter(|p| p.kind == PayloadKind::Data) else {
1244 return;
1245 };
1246 let Ok(mut data) = EndpointData::from_payload(&p.bytes, kind == Kind::Writer) else {
1247 return;
1248 };
1249 if data.guid.prefix == self.prefix {
1250 return;
1251 }
1252 if data.unicast_locators.is_empty()
1253 && data.multicast_locators.is_empty()
1254 && let Some((uc, mc)) = self.participants.get(&data.guid.prefix)
1255 {
1256 data.unicast_locators = uc.clone();
1257 data.multicast_locators = mc.clone();
1258 }
1259 let guid = data.guid;
1260 let remotes = match kind {
1261 Kind::Writer => &mut self.remote_writers,
1262 Kind::Reader => &mut self.remote_readers,
1263 };
1264 match remotes.insert(guid, data.clone()) {
1265 Some(old) if old == data => return,
1266 Some(_) => events.push(match kind {
1267 Kind::Writer => SedpEvent::WriterUpdated(data),
1268 Kind::Reader => SedpEvent::ReaderUpdated(data),
1269 }),
1270 None => events.push(match kind {
1271 Kind::Writer => SedpEvent::WriterDiscovered(data),
1272 Kind::Reader => SedpEvent::ReaderDiscovered(data),
1273 }),
1274 }
1275 let locals: Vec<Guid> = match kind {
1276 Kind::Writer => self.local_readers.keys().copied().collect(),
1277 Kind::Reader => self.local_writers.keys().copied().collect(),
1278 };
1279 let local_kind = match kind {
1280 Kind::Writer => Kind::Reader,
1281 Kind::Reader => Kind::Writer,
1282 };
1283 for l in locals {
1284 self.update_match(local_kind, l, guid, events);
1285 }
1286 }
1287
1288 fn remove_remote(&mut self, kind: Kind, guid: Guid, events: &mut Vec<SedpEvent>) {
1289 let removed = match kind {
1290 Kind::Writer => self.remote_writers.remove(&guid),
1291 Kind::Reader => self.remote_readers.remove(&guid),
1292 };
1293 if removed.is_none() {
1294 return;
1295 }
1296 self.incompatible.retain(|(_, r)| *r != guid);
1297 self.inconsistent.retain(|(_, r)| *r != guid);
1298 self.unresolved.retain(|(_, r), _| *r != guid);
1299 let mut pairs: Vec<(Guid, Guid)> = self
1300 .matches
1301 .iter()
1302 .filter(|(_, r)| *r == guid)
1303 .copied()
1304 .collect();
1305 pairs.sort();
1306 for (l, r) in pairs {
1307 self.matches.remove(&(l, r));
1308 events.push(SedpEvent::Unmatched {
1309 local: l,
1310 remote: r,
1311 });
1312 }
1313 events.push(match kind {
1314 Kind::Writer => SedpEvent::WriterRemoved(guid),
1315 Kind::Reader => SedpEvent::ReaderRemoved(guid),
1316 });
1317 }
1318
1319 fn update_match(&mut self, kind: Kind, local: Guid, remote: Guid, events: &mut Vec<SedpEvent>) {
1322 let m = match kind {
1323 Kind::Writer => match (
1324 self.local_writers.get(&local),
1325 self.remote_readers.get(&remote),
1326 ) {
1327 (Some(w), Some(r)) => match_endpoints(&w.data, r, &self.registry),
1328 _ => Match::Unrelated,
1329 },
1330 Kind::Reader => match (
1331 self.remote_writers.get(&remote),
1332 self.local_readers.get(&local),
1333 ) {
1334 (Some(w), Some(r)) => match_endpoints(w, &r.data, &self.registry),
1335 _ => Match::Unrelated,
1336 },
1337 };
1338 let now = m == Match::Matched;
1339 let pair = (local, remote);
1340 if !matches!(m, Match::Incompatible(_)) {
1341 self.incompatible.remove(&pair);
1342 }
1343 if m != Match::Inconsistent {
1344 self.inconsistent.remove(&pair);
1345 }
1346 if !matches!(m, Match::Unresolved(_)) {
1347 self.unresolved.remove(&pair);
1348 }
1349 match m {
1350 Match::Incompatible(policies) => {
1351 if self.incompatible.insert(pair) {
1352 events.push(SedpEvent::IncompatibleQos {
1353 local,
1354 remote,
1355 policies,
1356 });
1357 }
1358 }
1359 Match::Inconsistent => {
1360 if self.inconsistent.insert(pair) {
1361 events.push(SedpEvent::InconsistentTopic { local, remote });
1362 }
1363 }
1364 Match::Unresolved(missing) => {
1365 self.unresolved.insert(pair, missing);
1366 }
1367 Match::Matched | Match::Unrelated => {}
1368 }
1369 let was = self.matches.contains(&(local, remote));
1370 if now && !was {
1371 self.matches.insert((local, remote));
1372 events.push(SedpEvent::Matched { local, remote });
1373 } else if !now && was {
1374 self.matches.remove(&(local, remote));
1375 events.push(SedpEvent::Unmatched { local, remote });
1376 }
1377 }
1378}
1379
1380fn disposed_key(c: &Change) -> Option<Guid> {
1384 if let Some(p) = &c.payload
1385 && let Ok((list, e)) = decode_pl_payload(&p.bytes)
1386 && let Some(g) = list.get(pid::ENDPOINT_GUID)
1387 {
1388 return PlValues::new(e).guid(g).ok();
1389 }
1390 let hash = c.inline_qos.as_ref()?.get(pid::KEY_HASH)?;
1391 let b: [u8; 16] = hash.value.get(..16)?.try_into().ok()?;
1392 let mut prefix = [0u8; 12];
1393 prefix.copy_from_slice(&b[..12]);
1394 Some(Guid::new(
1395 GuidPrefix(prefix),
1396 EntityId::from_bytes([b[12], b[13], b[14], b[15]]),
1397 ))
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402 use super::*;
1403 use crate::qos::ReliabilityKind;
1404 use crate::types::entity_kind;
1405 use std::time::Duration as StdDuration;
1406
1407 fn prefix(n: u8) -> GuidPrefix {
1408 GuidPrefix([n; 12])
1409 }
1410
1411 fn wguid(n: u8) -> Guid {
1412 Guid::new(
1413 prefix(n),
1414 EntityId::user([0, 0, 1], entity_kind::USER_WRITER_NO_KEY),
1415 )
1416 }
1417
1418 fn rguid(n: u8) -> Guid {
1419 Guid::new(
1420 prefix(n),
1421 EntityId::user([0, 0, 2], entity_kind::USER_READER_NO_KEY),
1422 )
1423 }
1424
1425 fn participant(n: u8) -> ParticipantData {
1426 let mut p = ParticipantData::new(prefix(n), VendorId::UNKNOWN);
1427 p.available_builtin_endpoints.0 |= Sedp::BUILTIN_ENDPOINTS;
1428 p.metatraffic_unicast_locators = vec![Locator::udpv4(
1429 format!("127.0.0.1:{}", 7000 + n as u16).parse().unwrap(),
1430 )];
1431 p.default_unicast_locators = vec![Locator::udpv4(
1432 format!("127.0.0.1:{}", 8000 + n as u16).parse().unwrap(),
1433 )];
1434 p
1435 }
1436
1437 fn sedp(n: u8) -> Sedp {
1438 Sedp::new(prefix(n), VendorId::UNKNOWN, SedpConfig::default())
1439 }
1440
1441 fn pair(t: Instant) -> (Sedp, Sedp) {
1443 let (mut a, mut b) = (sedp(1), sedp(2));
1444 a.add_participant(&participant(2), t);
1445 b.add_participant(&participant(1), t);
1446 (a, b)
1447 }
1448
1449 fn pump(
1452 a: &mut Sedp,
1453 b: &mut Sedp,
1454 t: Instant,
1455 drop: impl Fn(usize) -> bool,
1456 ) -> (Vec<SedpEvent>, Vec<SedpEvent>) {
1457 let (mut ea, mut eb) = (Vec::new(), Vec::new());
1458 let mut i = 0;
1459 for round in 0..50 {
1460 let now = t + StdDuration::from_secs(round);
1461 let out_a = a.poll(now);
1462 let out_b = b.poll(now);
1463 if out_a.is_empty() && out_b.is_empty() && round > 0 {
1464 break;
1465 }
1466 for o in out_a {
1467 if !drop(i) {
1468 eb.extend(b.handle_message(&o.bytes, now));
1469 }
1470 i += 1;
1471 }
1472 for o in out_b {
1473 if !drop(i) {
1474 ea.extend(a.handle_message(&o.bytes, now));
1475 }
1476 i += 1;
1477 }
1478 }
1479 (ea, eb)
1480 }
1481
1482 #[test]
1483 fn content_filter_signature() {
1484 let f = ContentFilterProperty {
1485 content_filtered_topic_name: "a".into(),
1486 related_topic_name: "b".into(),
1487 filter_class_name: "DDSSQL".into(),
1488 filter_expression: "x > %0".into(),
1489 expression_parameters: vec!["1".into()],
1490 };
1491 assert_eq!(
1492 f.signature(),
1493 rustorb_typesupport::md5(b"a\0b\0DDSSQL\0x > %0\0\x31\0")
1494 );
1495 }
1496
1497 #[test]
1498 fn fast_dds_content_filter() {
1499 let value = b"\x15\0\0\0hello_world_filtered\0\0\0\0\x0c\0\0\0hello_world\0\
1503 \x07\0\0\0DDSSQL\0\0\x25\0\0\0index > %0 AND message LIKE 'Hello%'\0\0\0\0\
1504 \x01\0\0\0\x02\0\0\x005\0\0\0";
1505 let p = Parameter::new(pid::CONTENT_FILTER_PROPERTY, value.to_vec());
1506 let f = crate::pl::PlValues::new(Endianness::Little)
1507 .content_filter(&p)
1508 .unwrap();
1509 assert_eq!(
1510 f,
1511 ContentFilterProperty {
1512 content_filtered_topic_name: "hello_world_filtered".into(),
1513 related_topic_name: "hello_world".into(),
1514 filter_class_name: "DDSSQL".into(),
1515 filter_expression: "index > %0 AND message LIKE 'Hello%'".into(),
1516 expression_parameters: vec!["5".into()],
1517 }
1518 );
1519 let b = crate::pl::PlBuilder::new(Endianness::Little);
1520 let mut ours = b.content_filter(pid::CONTENT_FILTER_PROPERTY, &f).value;
1522 ours.resize(ours.len().next_multiple_of(4), 0);
1523 assert_eq!(ours, value);
1524 }
1525
1526 #[test]
1527 fn endpoint_data_round_trip() {
1528 let mut d = EndpointData::reader(rguid(1), "Square", "ShapeType");
1529 d.reliability.kind = ReliabilityKind::Reliable;
1530 d.durability = DurabilityKind::TransientLocal;
1531 d.partitions = vec!["p1".into(), "p2".into()];
1532 d.user_data = vec![1, 2];
1533 d.unicast_locators = participant(1).default_unicast_locators;
1534 d.multicast_locators = vec![Locator::udpv4("239.255.0.1:7401".parse().unwrap())];
1535 d.expects_inline_qos = true;
1536 d.content_filter = Some(ContentFilterProperty {
1537 content_filtered_topic_name: "BigSquares".into(),
1538 related_topic_name: "Square".into(),
1539 filter_class_name: "DDSSQL".into(),
1540 filter_expression: "x > %0 AND color = %1".into(),
1541 expression_parameters: vec!["100".into(), "'BLUE'".into()],
1542 });
1543 d.related_entity_guid = Some(rguid(2));
1544 d.service_instance_name = Some("robot".into());
1545 d.topic_aliases = vec!["Adder_Service_Request".into(), "Sub_Service_Request".into()];
1546 d.data_tags = vec![
1547 ("level".into(), "secret".into()),
1548 ("x".into(), String::new()),
1549 ];
1550 d.durability_service = Some(DurabilityService {
1551 service_cleanup_delay: Duration::from_std(std::time::Duration::from_millis(1500)),
1552 history_kind: 1,
1553 history_depth: 5,
1554 max_samples: 100,
1555 max_instances: -1,
1556 max_samples_per_instance: 20,
1557 });
1558 for e in [Endianness::Big, Endianness::Little] {
1559 assert_eq!(
1560 EndpointData::from_payload(&d.to_payload(e), false).unwrap(),
1561 d
1562 );
1563 }
1564 }
1565
1566 #[test]
1567 fn endpoint_data_defaults_and_rules() {
1568 let e = Endianness::Little;
1569 let b = PlBuilder::new(e);
1570 let mut l = ParameterList::new();
1571 l.push(b.guid(pid::ENDPOINT_GUID, wguid(3)));
1572 assert_eq!(
1573 EndpointData::from_parameter_list(&l, e, true),
1574 Err(DecodeError::MissingParameter(pid::TOPIC_NAME))
1575 );
1576 l.push(b.string(pid::TOPIC_NAME, "T"));
1577 l.push(b.string(pid::TYPE_NAME, "X"));
1578 let w = EndpointData::from_parameter_list(&l, e, true).unwrap();
1581 assert_eq!(w, EndpointData::writer(wguid(3), "T", "X"));
1582 assert_eq!(w.participant_guid.prefix, prefix(3));
1583 let r = EndpointData::from_parameter_list(&l, e, false).unwrap();
1584 assert_eq!(r.reliability.kind, ReliabilityKind::BestEffort);
1585 l.push(Parameter::new(
1586 crate::parameter::ParameterId(0x4fff),
1587 [0; 4],
1588 ));
1589 assert!(matches!(
1590 EndpointData::from_parameter_list(&l, e, true),
1591 Err(DecodeError::MustUnderstand(_))
1592 ));
1593 }
1594
1595 #[test]
1596 fn match_rules() {
1597 let w = EndpointData::writer(wguid(1), "T", "X");
1598 let r = EndpointData::reader(rguid(2), "T", "X");
1599 assert!(endpoints_match(&w, &r));
1600 let mut r2 = r.clone();
1601 r2.topic_name = "U".into();
1602 assert!(!endpoints_match(&w, &r2));
1603 r2.topic_aliases = vec!["V".into(), "T".into()];
1605 assert!(endpoints_match(&w, &r2));
1606 let mut w2 = w.clone();
1607 w2.topic_name = "U".into();
1608 w2.topic_aliases = vec!["T".into()];
1609 assert!(endpoints_match(&w2, &r));
1610 let mut r2 = r.clone();
1611 r2.type_name = "Y".into();
1612 assert!(!endpoints_match(&w, &r2));
1613 let mut r2 = r.clone();
1614 r2.durability = DurabilityKind::TransientLocal;
1615 assert!(!endpoints_match(&w, &r2));
1616 let mut w2 = w.clone();
1617 w2.reliability.kind = ReliabilityKind::BestEffort;
1618 let mut r2 = r.clone();
1619 r2.reliability.kind = ReliabilityKind::Reliable;
1620 assert!(!endpoints_match(&w2, &r2));
1621 assert!(endpoints_match(&w, &r2));
1622 let mut r2 = r.clone();
1623 r2.partitions = vec!["x".into()];
1624 assert!(!endpoints_match(&w, &r2));
1625 }
1626
1627 #[test]
1628 fn discover_match_and_remove() {
1629 let t = Instant::now();
1630 let (mut a, mut b) = pair(t);
1631 assert!(
1632 a.add_writer(EndpointData::writer(wguid(1), "T", "X"))
1633 .is_empty()
1634 );
1635 assert!(
1636 b.add_reader(EndpointData::reader(rguid(2), "T", "X"))
1637 .is_empty()
1638 );
1639 let (ea, eb) = pump(&mut a, &mut b, t, |_| false);
1640
1641 let mut w = EndpointData::writer(wguid(1), "T", "X");
1643 w.unicast_locators = participant(1).default_unicast_locators;
1644 assert_eq!(
1645 eb,
1646 [
1647 SedpEvent::WriterDiscovered(w),
1648 SedpEvent::Matched {
1649 local: rguid(2),
1650 remote: wguid(1)
1651 }
1652 ]
1653 );
1654 assert_eq!(ea.len(), 2);
1655 assert_eq!(
1656 ea[1],
1657 SedpEvent::Matched {
1658 local: wguid(1),
1659 remote: rguid(2)
1660 }
1661 );
1662 assert_eq!(a.matched(&wguid(1)).collect::<Vec<_>>(), [&rguid(2)]);
1663 assert!(a.remote_reader(&rguid(2)).is_some());
1664
1665 assert_eq!(
1667 a.remove_writer(&wguid(1)),
1668 [SedpEvent::Unmatched {
1669 local: wguid(1),
1670 remote: rguid(2)
1671 }]
1672 );
1673 let (_, eb) = pump(&mut a, &mut b, t + StdDuration::from_secs(100), |_| false);
1674 assert_eq!(
1675 eb,
1676 [
1677 SedpEvent::Unmatched {
1678 local: rguid(2),
1679 remote: wguid(1)
1680 },
1681 SedpEvent::WriterRemoved(wguid(1))
1682 ]
1683 );
1684 assert_eq!(b.remote_writers().count(), 0);
1685
1686 assert_eq!(
1688 a.remove_participant(&prefix(2)),
1689 [SedpEvent::ReaderRemoved(rguid(2))]
1690 );
1691 }
1692
1693 #[test]
1694 fn qos_update_changes_the_match() {
1695 let t = Instant::now();
1696 let (mut a, mut b) = pair(t);
1697 let mut w = EndpointData::writer(wguid(1), "T", "X");
1698 w.reliability.kind = ReliabilityKind::BestEffort;
1699 a.add_writer(w.clone());
1700 let mut r = EndpointData::reader(rguid(2), "T", "X");
1701 r.reliability.kind = ReliabilityKind::Reliable;
1702 b.add_reader(r);
1703 let (_, eb) = pump(&mut a, &mut b, t, |_| false);
1704 assert_eq!(eb.len(), 2, "{eb:?}");
1705 assert!(matches!(eb[0], SedpEvent::WriterDiscovered(_)));
1706 assert_eq!(
1708 eb[1],
1709 SedpEvent::IncompatibleQos {
1710 local: rguid(2),
1711 remote: wguid(1),
1712 policies: vec![QosPolicyId::RELIABILITY],
1713 }
1714 );
1715
1716 w.reliability.kind = ReliabilityKind::Reliable;
1717 a.add_writer(w);
1718 let (_, eb) = pump(&mut a, &mut b, t + StdDuration::from_secs(100), |_| false);
1719 assert!(matches!(eb[0], SedpEvent::WriterUpdated(_)));
1720 assert_eq!(
1721 eb[1],
1722 SedpEvent::Matched {
1723 local: rguid(2),
1724 remote: wguid(1)
1725 }
1726 );
1727 }
1728
1729 #[test]
1730 fn survives_loss() {
1731 let t = Instant::now();
1732 let (mut a, mut b) = pair(t);
1733 for i in 0..5u8 {
1734 let g = Guid::new(
1735 prefix(1),
1736 EntityId::user([0, 1, i], entity_kind::USER_WRITER_NO_KEY),
1737 );
1738 a.add_writer(EndpointData::writer(g, "T", "X"));
1739 }
1740 b.add_reader(EndpointData::reader(rguid(2), "T", "X"));
1741 let (_, eb) = pump(&mut a, &mut b, t, |i| i < 12 && i % 2 == 0);
1743 let matched = eb
1744 .iter()
1745 .filter(|e| matches!(e, SedpEvent::Matched { .. }))
1746 .count();
1747 assert_eq!(matched, 5, "{eb:?}");
1748 assert_eq!(b.remote_writers().count(), 5);
1749 }
1750
1751 #[test]
1752 fn own_and_unknown_participants_are_ignored() {
1753 let t = Instant::now();
1754 let mut a = sedp(1);
1755 a.add_participant(&participant(1), t);
1756 assert!(a.poll(t).is_empty());
1757 let mut c = sedp(3);
1759 c.add_participant(&participant(1), t);
1760 c.add_writer(EndpointData::writer(wguid(3), "T", "X"));
1761 for o in c.poll(t) {
1762 assert!(a.handle_message(&o.bytes, t).is_empty());
1763 }
1764 assert!(a.handle_message(b"junk", t).is_empty());
1765 }
1766
1767 fn appendable(name: &str, members: &[&str]) -> rustorb_xtypes::types::TypeObjects {
1768 use rustorb_xtypes::types::*;
1769 let ty: Type = StructType {
1770 name: name.into(),
1771 members: members
1772 .iter()
1773 .enumerate()
1774 .map(|(i, m)| StructMember::new(*m, i as u32, Type::Primitive(Primitive::Int32)))
1775 .collect(),
1776 ..Default::default()
1777 }
1778 .into();
1779 TypeObjects::new(&ty).unwrap()
1780 }
1781
1782 #[test]
1783 fn xtypes_parameters_round_trip() {
1784 let mut d = EndpointData::reader(rguid(1), "T", "X");
1785 d.type_information = Some(appendable("X", &["a", "b"]).information);
1786 d.data_representation = vec![data_representation::XCDR, data_representation::XCDR2];
1787 d.type_consistency = Some(TypeConsistency {
1788 ignore_member_names: true,
1789 ..Default::default()
1790 });
1791 for e in [Endianness::Big, Endianness::Little] {
1792 assert_eq!(
1793 EndpointData::from_payload(&d.to_payload(e), false).unwrap(),
1794 d
1795 );
1796 }
1797 }
1798
1799 #[test]
1802 fn cyclonedds_parameters() {
1803 let hex = |s: &str| -> Vec<u8> {
1804 (0..s.len())
1805 .step_by(2)
1806 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
1807 .collect()
1808 };
1809 let e = Endianness::Little;
1810 let b = PlBuilder::new(e);
1811 let mut l = ParameterList::new();
1812 l.push(b.guid(pid::ENDPOINT_GUID, rguid(3)));
1813 l.push(b.string(pid::TOPIC_NAME, "hello_world"));
1814 l.push(b.string(pid::TYPE_NAME, "HelloWorld::Greeting"));
1815 l.push(Parameter::new(
1816 pid::DATA_REPRESENTATION,
1817 hex("0200000000000200"),
1818 ));
1819 l.push(Parameter::new(
1820 pid::TYPE_INFORMATION,
1821 hex(concat!(
1822 "6000000001100040280000002400000014000000f14c98d3b709b9631e344fd7",
1823 "0a3402003800000000000000040000000000000002100040280000002400000014",
1824 "000000f2d8dede3f3e15043e059145548d1b006600000000000000040000000000",
1825 "0000"
1826 )),
1827 ));
1828 let d = EndpointData::from_parameter_list(&l, e, false).unwrap();
1829 assert_eq!(d.data_representation, vec![0, 2]);
1830 assert!(d.accepts_representation(data_representation::XCDR));
1831 assert!(d.accepts_representation(data_representation::XCDR2));
1832 let info = d.type_information.as_ref().unwrap();
1833 assert_eq!(
1834 info.minimal.typeid_with_size.type_id,
1835 TypeIdentifier::Minimal(hex("4c98d3b709b9631e344fd70a3402").try_into().unwrap())
1836 );
1837 assert_eq!(info.minimal.typeid_with_size.typeobject_serialized_size, 56);
1838 assert_eq!(d.type_consistency, None);
1841 assert_eq!(d.effective_type_consistency(), TypeConsistency::default());
1842 let mut l2 = l.clone();
1844 l2.parameters.retain(|p| p.id != pid::TYPE_INFORMATION);
1845 l2.push(Parameter::new(pid::TYPE_INFORMATION, vec![1, 2, 3, 4]));
1846 let d2 = EndpointData::from_parameter_list(&l2, e, false).unwrap();
1847 assert_eq!(d2.type_information, None);
1848 assert_eq!(
1849 d2.effective_type_consistency(),
1850 TypeConsistency::NOT_ANNOUNCED
1851 );
1852 }
1853
1854 #[test]
1855 fn type_and_representation_rules() {
1856 let registry = TypeRegistry::new();
1857 let v1 = appendable("X", &["a"]);
1858 let mut w = EndpointData::writer(wguid(1), "T", "X");
1859 let mut r = EndpointData::reader(rguid(2), "T", "X");
1860 r.type_name = "Y".into();
1862 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Inconsistent);
1863 w.type_information = Some(v1.information.clone());
1865 r.type_information = Some(v1.information.clone());
1866 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Matched);
1867 w.data_representation = vec![data_representation::XCDR2];
1869 assert_eq!(
1870 match_endpoints(&w, &r, ®istry),
1871 Match::Incompatible(vec![DATA_REPRESENTATION_QOS_POLICY_ID])
1872 );
1873 r.data_representation = vec![data_representation::XCDR, data_representation::XCDR2];
1874 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Matched);
1875 r.partitions = vec!["p".into()];
1877 r.type_consistency = Some(TypeConsistency {
1878 kind: TypeConsistencyKind::DisallowTypeCoercion,
1879 ..Default::default()
1880 });
1881 w.type_information = Some(appendable("X", &["a", "b"]).information);
1882 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Inconsistent);
1883 }
1884
1885 #[test]
1886 fn inconsistent_and_unresolved_types() {
1887 let t = Instant::now();
1888 let (mut a, mut b) = pair(t);
1889 let v1 = appendable("X", &["a"]);
1890 let v2 = appendable("X", &["a", "b"]);
1891 let other = appendable("X", &["z"]);
1892 a.registry_mut().add_type(&v2);
1893 b.registry_mut().add_type(&v1);
1894 let mut w = EndpointData::writer(wguid(1), "T", "X");
1896 w.type_information = Some(v2.information.clone());
1897 a.add_writer(w);
1898 let mut r = EndpointData::reader(rguid(2), "T", "X");
1899 r.type_information = Some(v1.information.clone());
1900 b.add_reader(r);
1901 let (ea, eb) = pump(&mut a, &mut b, t, |_| false);
1902 assert!(
1903 !eb.iter().any(|e| matches!(e, SedpEvent::Matched { .. })),
1904 "{eb:?}"
1905 );
1906 assert!(
1907 !ea.iter().any(|e| matches!(e, SedpEvent::Matched { .. })),
1908 "{ea:?}"
1909 );
1910 assert_eq!(
1911 b.unresolved_types(),
1912 vec![(v2.minimal_id().clone(), wguid(1))]
1913 );
1914 assert_eq!(
1915 a.unresolved_types(),
1916 vec![(v1.minimal_id().clone(), rguid(2))]
1917 );
1918 b.registry_mut().add_pairs(&v2.minimal).unwrap();
1921 assert_eq!(
1922 b.rematch_unresolved(),
1923 vec![SedpEvent::Matched {
1924 local: rguid(2),
1925 remote: wguid(1)
1926 }]
1927 );
1928 a.registry_mut().add_pairs(&v1.minimal).unwrap();
1929 assert_eq!(
1930 a.rematch_unresolved(),
1931 vec![SedpEvent::Matched {
1932 local: wguid(1),
1933 remote: rguid(2)
1934 }]
1935 );
1936 assert!(b.unresolved_types().is_empty());
1937
1938 let w3 = Guid::new(
1941 prefix(1),
1942 EntityId::user([0, 0, 3], entity_kind::USER_WRITER_NO_KEY),
1943 );
1944 let mut w = EndpointData::writer(w3, "T", "X");
1945 w.type_information = Some(other.information.clone());
1946 a.registry_mut().add_type(&other);
1947 b.registry_mut().add_pairs(&other.minimal).unwrap();
1948 let ea = a.add_writer(w);
1949 let (_, eb) = pump(&mut a, &mut b, t + StdDuration::from_secs(100), |_| false);
1950 assert!(ea.contains(&SedpEvent::InconsistentTopic {
1951 local: w3,
1952 remote: rguid(2)
1953 }));
1954 assert!(eb.contains(&SedpEvent::InconsistentTopic {
1955 local: rguid(2),
1956 remote: w3
1957 }));
1958 assert!(!eb.iter().any(|e| matches!(e, SedpEvent::Matched { .. })));
1959 }
1960}