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)]
585pub struct SedpConfig {
586 pub writer: WriterConfig,
588 pub reader: ReaderConfig,
590}
591
592impl Default for SedpConfig {
593 fn default() -> Self {
599 SedpConfig {
600 writer: WriterConfig {
601 heartbeat_period: std::time::Duration::from_millis(100),
602 ..WriterConfig::default()
603 },
604 reader: ReaderConfig::default(),
605 }
606 }
607}
608
609#[derive(Clone, Debug, PartialEq, Eq)]
611pub enum SedpEvent {
612 WriterDiscovered(EndpointData),
614 WriterUpdated(EndpointData),
616 WriterRemoved(Guid),
618 ReaderDiscovered(EndpointData),
620 ReaderUpdated(EndpointData),
622 ReaderRemoved(Guid),
624 Matched {
626 local: Guid,
628 remote: Guid,
630 },
631 Unmatched {
633 local: Guid,
635 remote: Guid,
637 },
638 InconsistentTopic {
641 local: Guid,
643 remote: Guid,
645 },
646 IncompatibleQos {
649 local: Guid,
651 remote: Guid,
653 policies: Vec<QosPolicyId>,
655 },
656}
657
658const STATUS_DISPOSED: u8 = 0x01;
660const STATUS_UNREGISTERED: u8 = 0x02;
661
662#[derive(Debug)]
663struct Local {
664 data: EndpointData,
665 sn: SequenceNumber,
666 secure: bool,
668}
669
670#[derive(Debug)]
672struct Endpoints {
673 secure: bool,
674 pub_writer: ReliableWriter,
675 pub_reader: ReliableReader,
676 sub_writer: ReliableWriter,
677 sub_reader: ReliableReader,
678}
679
680impl Endpoints {
681 fn ids(secure: bool) -> [EntityId; 4] {
684 if secure {
685 [
686 EntityId::SEDP_BUILTIN_PUBLICATIONS_SECURE_WRITER,
687 EntityId::SEDP_BUILTIN_PUBLICATIONS_SECURE_READER,
688 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_WRITER,
689 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_READER,
690 ]
691 } else {
692 [
693 EntityId::SEDP_BUILTIN_PUBLICATIONS_ANNOUNCER,
694 EntityId::SEDP_BUILTIN_PUBLICATIONS_DETECTOR,
695 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_ANNOUNCER,
696 EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_DETECTOR,
697 ]
698 }
699 }
700
701 fn bits(secure: bool) -> [u32; 4] {
703 if secure {
704 [
705 BuiltinEndpointSet::PUBLICATIONS_SECURE_WRITER,
706 BuiltinEndpointSet::PUBLICATIONS_SECURE_READER,
707 BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_WRITER,
708 BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_READER,
709 ]
710 } else {
711 [
712 BuiltinEndpointSet::PUBLICATIONS_ANNOUNCER,
713 BuiltinEndpointSet::PUBLICATIONS_DETECTOR,
714 BuiltinEndpointSet::SUBSCRIPTIONS_ANNOUNCER,
715 BuiltinEndpointSet::SUBSCRIPTIONS_DETECTOR,
716 ]
717 }
718 }
719
720 fn new(prefix: GuidPrefix, vendor_id: VendorId, config: &SedpConfig, secure: bool) -> Self {
721 let [pw, pr, sw, sr] = Self::ids(secure);
722 let g = |e| Guid::new(prefix, e);
723 Endpoints {
724 secure,
725 pub_writer: ReliableWriter::new(g(pw), vendor_id, config.writer.clone()),
726 pub_reader: ReliableReader::new(g(pr), vendor_id, config.reader.clone()),
727 sub_writer: ReliableWriter::new(g(sw), vendor_id, config.writer.clone()),
728 sub_reader: ReliableReader::new(g(sr), vendor_id, config.reader.clone()),
729 }
730 }
731
732 fn find<'a>(
735 plain: &'a mut Endpoints,
736 secure: Option<&'a mut Endpoints>,
737 writer_id: EntityId,
738 ) -> Option<(&'a mut Endpoints, Kind)> {
739 let set = if Self::ids(false).contains(&writer_id) {
740 plain
741 } else if Self::ids(true).contains(&writer_id) {
742 secure?
743 } else {
744 return None;
745 };
746 let [pw, _, sw, _] = Self::ids(set.secure);
747 if writer_id == pw {
748 Some((set, Kind::Writer))
749 } else if writer_id == sw {
750 Some((set, Kind::Reader))
751 } else {
752 None
753 }
754 }
755
756 fn writer(&mut self, kind: Kind) -> &mut ReliableWriter {
757 match kind {
758 Kind::Writer => &mut self.pub_writer,
759 Kind::Reader => &mut self.sub_writer,
760 }
761 }
762
763 fn add_participant(&mut self, p: &ParticipantData, now: Instant) {
764 let set = p.available_builtin_endpoints;
765 let uc = p.metatraffic_unicast_locators.clone();
766 let mc = p.metatraffic_multicast_locators.clone();
767 let g = |e| Guid::new(p.guid_prefix, e);
768 let [pw, pr, sw, sr] = Self::ids(self.secure);
769 let [bpw, bpr, bsw, bsr] = Self::bits(self.secure);
770 if set.contains(bpr) {
771 self.pub_writer.add_reader(g(pr), uc.clone(), mc.clone());
772 }
773 if set.contains(bpw) {
774 self.pub_reader
775 .add_writer(g(pw), uc.clone(), mc.clone(), now);
776 }
777 if set.contains(bsr) {
778 self.sub_writer.add_reader(g(sr), uc.clone(), mc.clone());
779 }
780 if set.contains(bsw) {
781 self.sub_reader.add_writer(g(sw), uc, mc, now);
782 }
783 }
784
785 fn remove_participant(&mut self, prefix: &GuidPrefix) {
786 self.pub_writer.remove_readers_of(prefix);
787 self.pub_reader.remove_writers_of(prefix);
788 self.sub_writer.remove_readers_of(prefix);
789 self.sub_reader.remove_writers_of(prefix);
790 }
791
792 fn poll(&mut self, now: Instant) -> Vec<Outgoing> {
793 let mut out = self.pub_writer.poll(now);
794 out.extend(self.sub_writer.poll(now));
795 out.extend(self.pub_reader.poll(now));
796 out.extend(self.sub_reader.poll(now));
797 out
798 }
799
800 fn next_deadline(&self) -> Option<Instant> {
801 [
802 self.pub_writer.next_deadline(),
803 self.sub_writer.next_deadline(),
804 self.pub_reader.next_deadline(),
805 self.sub_reader.next_deadline(),
806 ]
807 .into_iter()
808 .flatten()
809 .min()
810 }
811}
812
813#[derive(Clone, Copy, Debug, PartialEq, Eq)]
814enum Kind {
815 Writer,
816 Reader,
817}
818
819#[derive(Debug)]
822pub struct Sedp {
823 prefix: GuidPrefix,
824 vendor_id: VendorId,
825 config: SedpConfig,
826 plain: Endpoints,
827 secure: Option<Endpoints>,
829 participants: HashMap<GuidPrefix, (Vec<Locator>, Vec<Locator>)>,
831 local_writers: BTreeMap<Guid, Local>,
832 local_readers: BTreeMap<Guid, Local>,
833 remote_writers: HashMap<Guid, EndpointData>,
834 remote_readers: HashMap<Guid, EndpointData>,
835 matches: HashSet<(Guid, Guid)>,
837 incompatible: HashSet<(Guid, Guid)>,
839 inconsistent: HashSet<(Guid, Guid)>,
842 unresolved: HashMap<(Guid, Guid), Vec<TypeIdentifier>>,
844 registry: TypeRegistry,
846}
847
848impl Sedp {
849 pub const BUILTIN_ENDPOINTS: u32 = BuiltinEndpointSet::PUBLICATIONS_ANNOUNCER
852 | BuiltinEndpointSet::PUBLICATIONS_DETECTOR
853 | BuiltinEndpointSet::SUBSCRIPTIONS_ANNOUNCER
854 | BuiltinEndpointSet::SUBSCRIPTIONS_DETECTOR;
855
856 pub const BUILTIN_ENDPOINTS_SECURE: u32 = BuiltinEndpointSet::PUBLICATIONS_SECURE_WRITER
859 | BuiltinEndpointSet::PUBLICATIONS_SECURE_READER
860 | BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_WRITER
861 | BuiltinEndpointSet::SUBSCRIPTIONS_SECURE_READER;
862
863 pub fn new(prefix: GuidPrefix, vendor_id: VendorId, config: SedpConfig) -> Self {
865 Sedp {
866 prefix,
867 vendor_id,
868 plain: Endpoints::new(prefix, vendor_id, &config, false),
869 secure: None,
870 config,
871 participants: HashMap::new(),
872 local_writers: BTreeMap::new(),
873 local_readers: BTreeMap::new(),
874 remote_writers: HashMap::new(),
875 remote_readers: HashMap::new(),
876 matches: HashSet::new(),
877 incompatible: HashSet::new(),
878 inconsistent: HashSet::new(),
879 unresolved: HashMap::new(),
880 registry: TypeRegistry::new(),
881 }
882 }
883
884 pub fn add_participant(&mut self, p: &ParticipantData, now: Instant) {
889 if p.guid_prefix == self.prefix {
890 return;
891 }
892 self.plain.add_participant(p, now);
893 if let Some(s) = self.secure.as_mut() {
894 s.add_participant(p, now);
895 }
896 self.participants.insert(
897 p.guid_prefix,
898 (
899 p.default_unicast_locators.clone(),
900 p.default_multicast_locators.clone(),
901 ),
902 );
903 }
904
905 pub fn remove_participant(&mut self, prefix: &GuidPrefix) -> Vec<SedpEvent> {
908 self.plain.remove_participant(prefix);
909 if let Some(s) = self.secure.as_mut() {
910 s.remove_participant(prefix);
911 }
912 self.participants.remove(prefix);
913 let mut events = Vec::new();
914 let writers: Vec<Guid> = self
915 .remote_writers
916 .keys()
917 .filter(|g| g.prefix == *prefix)
918 .copied()
919 .collect();
920 for g in writers {
921 self.remove_remote(Kind::Writer, g, &mut events);
922 }
923 let readers: Vec<Guid> = self
924 .remote_readers
925 .keys()
926 .filter(|g| g.prefix == *prefix)
927 .copied()
928 .collect();
929 for g in readers {
930 self.remove_remote(Kind::Reader, g, &mut events);
931 }
932 events
933 }
934
935 pub fn add_writer(&mut self, data: EndpointData) -> Vec<SedpEvent> {
938 self.add_local(Kind::Writer, data)
939 }
940
941 pub fn add_reader(&mut self, data: EndpointData) -> Vec<SedpEvent> {
944 self.add_local(Kind::Reader, data)
945 }
946
947 pub fn remove_writer(&mut self, guid: &Guid) -> Vec<SedpEvent> {
949 self.remove_local(Kind::Writer, guid)
950 }
951
952 pub fn remove_reader(&mut self, guid: &Guid) -> Vec<SedpEvent> {
954 self.remove_local(Kind::Reader, guid)
955 }
956
957 pub fn is_announced_to(&self, local: &Guid, prefix: &GuidPrefix) -> bool {
961 let (l, writer) = match (self.local_writers.get(local), self.local_readers.get(local)) {
962 (Some(l), _) => (l, true),
963 (None, Some(l)) => (l, false),
964 (None, None) => return false,
965 };
966 let set = match (l.secure, self.secure.as_ref()) {
967 (true, Some(s)) => s,
968 _ => &self.plain,
969 };
970 let w = if writer {
971 &set.pub_writer
972 } else {
973 &set.sub_writer
974 };
975 w.is_acked_by_participant(prefix, l.sn)
976 }
977
978 pub fn remote_writers(&self) -> impl Iterator<Item = &EndpointData> {
980 self.remote_writers.values()
981 }
982
983 pub fn remote_readers(&self) -> impl Iterator<Item = &EndpointData> {
985 self.remote_readers.values()
986 }
987
988 pub fn remote_writer(&self, guid: &Guid) -> Option<&EndpointData> {
990 self.remote_writers.get(guid)
991 }
992
993 pub fn remote_reader(&self, guid: &Guid) -> Option<&EndpointData> {
995 self.remote_readers.get(guid)
996 }
997
998 pub fn registry(&self) -> &TypeRegistry {
1000 &self.registry
1001 }
1002
1003 pub fn registry_mut(&mut self) -> &mut TypeRegistry {
1006 &mut self.registry
1007 }
1008
1009 pub fn unresolved_types(&self) -> Vec<(TypeIdentifier, Guid)> {
1012 let mut out: Vec<(TypeIdentifier, Guid)> = Vec::new();
1013 for ((_, remote), ids) in &self.unresolved {
1014 for id in ids {
1015 if !out.iter().any(|(i, _)| i == id) {
1016 out.push((id.clone(), *remote));
1017 }
1018 }
1019 }
1020 out
1021 }
1022
1023 pub fn rematch_unresolved(&mut self) -> Vec<SedpEvent> {
1025 let mut pairs: Vec<(Guid, Guid)> = self.unresolved.keys().copied().collect();
1026 pairs.sort();
1027 let mut events = Vec::new();
1028 for (local, remote) in pairs {
1029 let kind = if self.local_writers.contains_key(&local) {
1030 Kind::Writer
1031 } else {
1032 Kind::Reader
1033 };
1034 self.update_match(kind, local, remote, &mut events);
1035 }
1036 events
1037 }
1038
1039 pub fn matched(&self, local: &Guid) -> impl Iterator<Item = &Guid> {
1041 self.matches
1042 .iter()
1043 .filter(move |(l, _)| l == local)
1044 .map(|(_, r)| r)
1045 }
1046
1047 pub fn handle_message(&mut self, bytes: &[u8], now: Instant) -> Vec<SedpEvent> {
1049 let Some((_, received)) = receive(bytes, self.prefix) else {
1050 return Vec::new();
1051 };
1052 let mut changes: Vec<(Kind, Change)> = Vec::new();
1053 for r in received {
1054 let src = r.source_prefix;
1055 let writer_id = match &r.submessage {
1056 Submessage::Data(d) => d.writer_id,
1057 Submessage::DataFrag(d) => d.writer_id,
1058 Submessage::Gap(g) => g.writer_id,
1059 Submessage::Heartbeat(h) => h.writer_id,
1060 Submessage::NackFrag(n) => n.writer_id,
1061 Submessage::AckNack(a) => a.writer_id,
1062 _ => continue,
1063 };
1064 let Some((set, kind)) =
1065 Endpoints::find(&mut self.plain, self.secure.as_mut(), writer_id)
1066 else {
1067 continue;
1068 };
1069 let w = Guid::new(src, writer_id);
1070 let (writer, reader) = match kind {
1071 Kind::Writer => (&mut set.pub_writer, &mut set.pub_reader),
1072 Kind::Reader => (&mut set.sub_writer, &mut set.sub_reader),
1073 };
1074 let got = match r.submessage {
1075 Submessage::Data(d) => reader.handle_data(w, &d, r.timestamp),
1076 Submessage::DataFrag(d) => reader.handle_data_frag(w, &d, r.timestamp),
1077 Submessage::Gap(g) => reader.handle_gap(w, &g),
1078 Submessage::Heartbeat(h) => reader.handle_heartbeat(w, &h, now),
1079 Submessage::NackFrag(n) => {
1080 writer.handle_nackfrag(Guid::new(src, n.reader_id), &n, now);
1081 Vec::new()
1082 }
1083 Submessage::AckNack(a) => {
1084 writer.handle_acknack(Guid::new(src, a.reader_id), &a, now);
1085 Vec::new()
1086 }
1087 _ => Vec::new(),
1088 };
1089 changes.extend(got.into_iter().map(|c| (kind, c)));
1090 }
1091 let mut events = Vec::new();
1092 for (kind, c) in changes {
1093 self.apply(kind, &c, &mut events);
1094 }
1095 events
1096 }
1097
1098 pub fn poll(&mut self, now: Instant) -> Vec<Outgoing> {
1100 let mut out = self.plain.poll(now);
1101 if let Some(s) = self.secure.as_mut() {
1102 out.extend(s.poll(now));
1103 }
1104 out
1105 }
1106
1107 pub fn next_deadline(&self) -> Option<Instant> {
1110 [
1111 self.plain.next_deadline(),
1112 self.secure.as_ref().and_then(Endpoints::next_deadline),
1113 ]
1114 .into_iter()
1115 .flatten()
1116 .min()
1117 }
1118
1119 pub fn enable_secure(&mut self) {
1124 if self.secure.is_none() {
1125 self.secure = Some(Endpoints::new(
1126 self.prefix,
1127 self.vendor_id,
1128 &self.config,
1129 true,
1130 ));
1131 }
1132 }
1133
1134 pub fn add_writer_secure(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1137 self.add_local_on(Kind::Writer, data, true)
1138 }
1139
1140 pub fn add_reader_secure(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1143 self.add_local_on(Kind::Reader, data, true)
1144 }
1145
1146 fn set(&mut self, secure: bool) -> &mut Endpoints {
1147 match (secure, self.secure.as_mut()) {
1148 (true, Some(s)) => s,
1149 _ => &mut self.plain,
1150 }
1151 }
1152
1153 fn add_local(&mut self, kind: Kind, data: EndpointData) -> Vec<SedpEvent> {
1154 self.add_local_on(kind, data, false)
1155 }
1156
1157 fn add_local_on(&mut self, kind: Kind, data: EndpointData, secure: bool) -> Vec<SedpEvent> {
1158 let secure = secure && self.secure.is_some();
1159 let mut qos = ParameterList::new();
1160 qos.push(Parameter::new(pid::KEY_HASH, data.guid.to_bytes()));
1161 let payload = SerializedPayload {
1162 kind: PayloadKind::Data,
1163 bytes: data.to_payload(Endianness::NATIVE).into(),
1164 };
1165 let old = match kind {
1166 Kind::Writer => self.local_writers.remove(&data.guid),
1167 Kind::Reader => self.local_readers.remove(&data.guid),
1168 };
1169 if let Some(old) = &old {
1171 self.set(old.secure).writer(kind).remove_change(old.sn);
1172 }
1173 let sn = self
1174 .set(secure)
1175 .writer(kind)
1176 .add_change(Some(qos), Some(payload));
1177 let local = Local {
1178 data: data.clone(),
1179 sn,
1180 secure,
1181 };
1182 match kind {
1183 Kind::Writer => self.local_writers.insert(data.guid, local),
1184 Kind::Reader => self.local_readers.insert(data.guid, local),
1185 };
1186 let mut events = Vec::new();
1187 let remotes: Vec<Guid> = match kind {
1188 Kind::Writer => self.remote_readers.keys().copied().collect(),
1189 Kind::Reader => self.remote_writers.keys().copied().collect(),
1190 };
1191 for r in remotes {
1192 self.update_match(kind, data.guid, r, &mut events);
1193 }
1194 events
1195 }
1196
1197 fn remove_local(&mut self, kind: Kind, guid: &Guid) -> Vec<SedpEvent> {
1198 let old = match kind {
1199 Kind::Writer => self.local_writers.remove(guid),
1200 Kind::Reader => self.local_readers.remove(guid),
1201 };
1202 let Some(old) = old else {
1203 return Vec::new();
1204 };
1205 self.incompatible.retain(|(l, _)| l != guid);
1206 self.inconsistent.retain(|(l, _)| l != guid);
1207 self.unresolved.retain(|(l, _), _| l != guid);
1208 let writer = self.set(old.secure).writer(kind);
1209 writer.remove_change(old.sn);
1210 let e = Endianness::NATIVE;
1212 let b = PlBuilder::new(e);
1213 let mut qos = ParameterList::new();
1214 qos.push(Parameter::new(pid::KEY_HASH, guid.to_bytes()));
1215 qos.push(Parameter::new(
1216 pid::STATUS_INFO,
1217 [0, 0, 0, STATUS_DISPOSED | STATUS_UNREGISTERED],
1218 ));
1219 let mut key = ParameterList::new();
1220 key.push(b.guid(pid::ENDPOINT_GUID, *guid));
1221 writer.add_change(
1222 Some(qos),
1223 Some(SerializedPayload {
1224 kind: PayloadKind::Key,
1225 bytes: encode_pl_payload(&key, e).into(),
1226 }),
1227 );
1228 let mut events = Vec::new();
1229 let pairs: Vec<(Guid, Guid)> = self
1230 .matches
1231 .iter()
1232 .filter(|(l, _)| l == guid)
1233 .copied()
1234 .collect();
1235 for (l, r) in pairs {
1236 self.matches.remove(&(l, r));
1237 events.push(SedpEvent::Unmatched {
1238 local: l,
1239 remote: r,
1240 });
1241 }
1242 events
1243 }
1244
1245 fn apply(&mut self, kind: Kind, c: &Change, events: &mut Vec<SedpEvent>) {
1248 let status = c
1249 .inline_qos
1250 .as_ref()
1251 .and_then(|q| q.get(pid::STATUS_INFO))
1252 .and_then(|p| p.value.get(3).copied())
1253 .unwrap_or(0);
1254 if status & (STATUS_DISPOSED | STATUS_UNREGISTERED) != 0 {
1255 if let Some(g) = disposed_key(c) {
1256 self.remove_remote(kind, g, events);
1257 }
1258 return;
1259 }
1260 let Some(p) = c.payload.as_ref().filter(|p| p.kind == PayloadKind::Data) else {
1261 return;
1262 };
1263 let Ok(mut data) = EndpointData::from_payload(&p.bytes, kind == Kind::Writer) else {
1264 return;
1265 };
1266 if data.guid.prefix == self.prefix {
1267 return;
1268 }
1269 if data.unicast_locators.is_empty()
1270 && data.multicast_locators.is_empty()
1271 && let Some((uc, mc)) = self.participants.get(&data.guid.prefix)
1272 {
1273 data.unicast_locators = uc.clone();
1274 data.multicast_locators = mc.clone();
1275 }
1276 let guid = data.guid;
1277 let remotes = match kind {
1278 Kind::Writer => &mut self.remote_writers,
1279 Kind::Reader => &mut self.remote_readers,
1280 };
1281 match remotes.insert(guid, data.clone()) {
1282 Some(old) if old == data => return,
1283 Some(_) => events.push(match kind {
1284 Kind::Writer => SedpEvent::WriterUpdated(data),
1285 Kind::Reader => SedpEvent::ReaderUpdated(data),
1286 }),
1287 None => events.push(match kind {
1288 Kind::Writer => SedpEvent::WriterDiscovered(data),
1289 Kind::Reader => SedpEvent::ReaderDiscovered(data),
1290 }),
1291 }
1292 let locals: Vec<Guid> = match kind {
1293 Kind::Writer => self.local_readers.keys().copied().collect(),
1294 Kind::Reader => self.local_writers.keys().copied().collect(),
1295 };
1296 let local_kind = match kind {
1297 Kind::Writer => Kind::Reader,
1298 Kind::Reader => Kind::Writer,
1299 };
1300 for l in locals {
1301 self.update_match(local_kind, l, guid, events);
1302 }
1303 }
1304
1305 fn remove_remote(&mut self, kind: Kind, guid: Guid, events: &mut Vec<SedpEvent>) {
1306 let removed = match kind {
1307 Kind::Writer => self.remote_writers.remove(&guid),
1308 Kind::Reader => self.remote_readers.remove(&guid),
1309 };
1310 if removed.is_none() {
1311 return;
1312 }
1313 self.incompatible.retain(|(_, r)| *r != guid);
1314 self.inconsistent.retain(|(_, r)| *r != guid);
1315 self.unresolved.retain(|(_, r), _| *r != guid);
1316 let mut pairs: Vec<(Guid, Guid)> = self
1317 .matches
1318 .iter()
1319 .filter(|(_, r)| *r == guid)
1320 .copied()
1321 .collect();
1322 pairs.sort();
1323 for (l, r) in pairs {
1324 self.matches.remove(&(l, r));
1325 events.push(SedpEvent::Unmatched {
1326 local: l,
1327 remote: r,
1328 });
1329 }
1330 events.push(match kind {
1331 Kind::Writer => SedpEvent::WriterRemoved(guid),
1332 Kind::Reader => SedpEvent::ReaderRemoved(guid),
1333 });
1334 }
1335
1336 fn update_match(&mut self, kind: Kind, local: Guid, remote: Guid, events: &mut Vec<SedpEvent>) {
1339 let m = match kind {
1340 Kind::Writer => match (
1341 self.local_writers.get(&local),
1342 self.remote_readers.get(&remote),
1343 ) {
1344 (Some(w), Some(r)) => match_endpoints(&w.data, r, &self.registry),
1345 _ => Match::Unrelated,
1346 },
1347 Kind::Reader => match (
1348 self.remote_writers.get(&remote),
1349 self.local_readers.get(&local),
1350 ) {
1351 (Some(w), Some(r)) => match_endpoints(w, &r.data, &self.registry),
1352 _ => Match::Unrelated,
1353 },
1354 };
1355 let now = m == Match::Matched;
1356 let pair = (local, remote);
1357 if !matches!(m, Match::Incompatible(_)) {
1358 self.incompatible.remove(&pair);
1359 }
1360 if m != Match::Inconsistent {
1361 self.inconsistent.remove(&pair);
1362 }
1363 if !matches!(m, Match::Unresolved(_)) {
1364 self.unresolved.remove(&pair);
1365 }
1366 match m {
1367 Match::Incompatible(policies) => {
1368 if self.incompatible.insert(pair) {
1369 events.push(SedpEvent::IncompatibleQos {
1370 local,
1371 remote,
1372 policies,
1373 });
1374 }
1375 }
1376 Match::Inconsistent => {
1377 if self.inconsistent.insert(pair) {
1378 events.push(SedpEvent::InconsistentTopic { local, remote });
1379 }
1380 }
1381 Match::Unresolved(missing) => {
1382 self.unresolved.insert(pair, missing);
1383 }
1384 Match::Matched | Match::Unrelated => {}
1385 }
1386 let was = self.matches.contains(&(local, remote));
1387 if now && !was {
1388 self.matches.insert((local, remote));
1389 events.push(SedpEvent::Matched { local, remote });
1390 } else if !now && was {
1391 self.matches.remove(&(local, remote));
1392 events.push(SedpEvent::Unmatched { local, remote });
1393 }
1394 }
1395}
1396
1397fn disposed_key(c: &Change) -> Option<Guid> {
1401 if let Some(p) = &c.payload
1402 && let Ok((list, e)) = decode_pl_payload(&p.bytes)
1403 && let Some(g) = list.get(pid::ENDPOINT_GUID)
1404 {
1405 return PlValues::new(e).guid(g).ok();
1406 }
1407 let hash = c.inline_qos.as_ref()?.get(pid::KEY_HASH)?;
1408 let b: [u8; 16] = hash.value.get(..16)?.try_into().ok()?;
1409 let mut prefix = [0u8; 12];
1410 prefix.copy_from_slice(&b[..12]);
1411 Some(Guid::new(
1412 GuidPrefix(prefix),
1413 EntityId::from_bytes([b[12], b[13], b[14], b[15]]),
1414 ))
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419 use super::*;
1420 use crate::qos::ReliabilityKind;
1421 use crate::types::entity_kind;
1422 use std::time::Duration as StdDuration;
1423
1424 fn prefix(n: u8) -> GuidPrefix {
1425 GuidPrefix([n; 12])
1426 }
1427
1428 fn wguid(n: u8) -> Guid {
1429 Guid::new(
1430 prefix(n),
1431 EntityId::user([0, 0, 1], entity_kind::USER_WRITER_NO_KEY),
1432 )
1433 }
1434
1435 fn rguid(n: u8) -> Guid {
1436 Guid::new(
1437 prefix(n),
1438 EntityId::user([0, 0, 2], entity_kind::USER_READER_NO_KEY),
1439 )
1440 }
1441
1442 fn participant(n: u8) -> ParticipantData {
1443 let mut p = ParticipantData::new(prefix(n), VendorId::UNKNOWN);
1444 p.available_builtin_endpoints.0 |= Sedp::BUILTIN_ENDPOINTS;
1445 p.metatraffic_unicast_locators = vec![Locator::udpv4(
1446 format!("127.0.0.1:{}", 7000 + n as u16).parse().unwrap(),
1447 )];
1448 p.default_unicast_locators = vec![Locator::udpv4(
1449 format!("127.0.0.1:{}", 8000 + n as u16).parse().unwrap(),
1450 )];
1451 p
1452 }
1453
1454 fn sedp(n: u8) -> Sedp {
1455 Sedp::new(prefix(n), VendorId::UNKNOWN, SedpConfig::default())
1456 }
1457
1458 fn pair(t: Instant) -> (Sedp, Sedp) {
1460 let (mut a, mut b) = (sedp(1), sedp(2));
1461 a.add_participant(&participant(2), t);
1462 b.add_participant(&participant(1), t);
1463 (a, b)
1464 }
1465
1466 fn pump(
1469 a: &mut Sedp,
1470 b: &mut Sedp,
1471 t: Instant,
1472 drop: impl Fn(usize) -> bool,
1473 ) -> (Vec<SedpEvent>, Vec<SedpEvent>) {
1474 let (mut ea, mut eb) = (Vec::new(), Vec::new());
1475 let mut i = 0;
1476 for round in 0..50 {
1477 let now = t + StdDuration::from_secs(round);
1478 let out_a = a.poll(now);
1479 let out_b = b.poll(now);
1480 if out_a.is_empty() && out_b.is_empty() && round > 0 {
1481 break;
1482 }
1483 for o in out_a {
1484 if !drop(i) {
1485 eb.extend(b.handle_message(&o.bytes, now));
1486 }
1487 i += 1;
1488 }
1489 for o in out_b {
1490 if !drop(i) {
1491 ea.extend(a.handle_message(&o.bytes, now));
1492 }
1493 i += 1;
1494 }
1495 }
1496 (ea, eb)
1497 }
1498
1499 #[test]
1500 fn content_filter_signature() {
1501 let f = ContentFilterProperty {
1502 content_filtered_topic_name: "a".into(),
1503 related_topic_name: "b".into(),
1504 filter_class_name: "DDSSQL".into(),
1505 filter_expression: "x > %0".into(),
1506 expression_parameters: vec!["1".into()],
1507 };
1508 assert_eq!(
1509 f.signature(),
1510 rustorb_typesupport::md5(b"a\0b\0DDSSQL\0x > %0\0\x31\0")
1511 );
1512 }
1513
1514 #[test]
1515 fn fast_dds_content_filter() {
1516 let value = b"\x15\0\0\0hello_world_filtered\0\0\0\0\x0c\0\0\0hello_world\0\
1520 \x07\0\0\0DDSSQL\0\0\x25\0\0\0index > %0 AND message LIKE 'Hello%'\0\0\0\0\
1521 \x01\0\0\0\x02\0\0\x005\0\0\0";
1522 let p = Parameter::new(pid::CONTENT_FILTER_PROPERTY, value.to_vec());
1523 let f = crate::pl::PlValues::new(Endianness::Little)
1524 .content_filter(&p)
1525 .unwrap();
1526 assert_eq!(
1527 f,
1528 ContentFilterProperty {
1529 content_filtered_topic_name: "hello_world_filtered".into(),
1530 related_topic_name: "hello_world".into(),
1531 filter_class_name: "DDSSQL".into(),
1532 filter_expression: "index > %0 AND message LIKE 'Hello%'".into(),
1533 expression_parameters: vec!["5".into()],
1534 }
1535 );
1536 let b = crate::pl::PlBuilder::new(Endianness::Little);
1537 let mut ours = b.content_filter(pid::CONTENT_FILTER_PROPERTY, &f).value;
1539 ours.resize(ours.len().next_multiple_of(4), 0);
1540 assert_eq!(ours, value);
1541 }
1542
1543 #[test]
1544 fn endpoint_data_round_trip() {
1545 let mut d = EndpointData::reader(rguid(1), "Square", "ShapeType");
1546 d.reliability.kind = ReliabilityKind::Reliable;
1547 d.durability = DurabilityKind::TransientLocal;
1548 d.partitions = vec!["p1".into(), "p2".into()];
1549 d.user_data = vec![1, 2];
1550 d.unicast_locators = participant(1).default_unicast_locators;
1551 d.multicast_locators = vec![Locator::udpv4("239.255.0.1:7401".parse().unwrap())];
1552 d.expects_inline_qos = true;
1553 d.content_filter = Some(ContentFilterProperty {
1554 content_filtered_topic_name: "BigSquares".into(),
1555 related_topic_name: "Square".into(),
1556 filter_class_name: "DDSSQL".into(),
1557 filter_expression: "x > %0 AND color = %1".into(),
1558 expression_parameters: vec!["100".into(), "'BLUE'".into()],
1559 });
1560 d.related_entity_guid = Some(rguid(2));
1561 d.service_instance_name = Some("robot".into());
1562 d.topic_aliases = vec!["Adder_Service_Request".into(), "Sub_Service_Request".into()];
1563 d.data_tags = vec![
1564 ("level".into(), "secret".into()),
1565 ("x".into(), String::new()),
1566 ];
1567 d.durability_service = Some(DurabilityService {
1568 service_cleanup_delay: Duration::from_std(std::time::Duration::from_millis(1500)),
1569 history_kind: 1,
1570 history_depth: 5,
1571 max_samples: 100,
1572 max_instances: -1,
1573 max_samples_per_instance: 20,
1574 });
1575 for e in [Endianness::Big, Endianness::Little] {
1576 assert_eq!(
1577 EndpointData::from_payload(&d.to_payload(e), false).unwrap(),
1578 d
1579 );
1580 }
1581 }
1582
1583 #[test]
1584 fn endpoint_data_defaults_and_rules() {
1585 let e = Endianness::Little;
1586 let b = PlBuilder::new(e);
1587 let mut l = ParameterList::new();
1588 l.push(b.guid(pid::ENDPOINT_GUID, wguid(3)));
1589 assert_eq!(
1590 EndpointData::from_parameter_list(&l, e, true),
1591 Err(DecodeError::MissingParameter(pid::TOPIC_NAME))
1592 );
1593 l.push(b.string(pid::TOPIC_NAME, "T"));
1594 l.push(b.string(pid::TYPE_NAME, "X"));
1595 let w = EndpointData::from_parameter_list(&l, e, true).unwrap();
1598 assert_eq!(w, EndpointData::writer(wguid(3), "T", "X"));
1599 assert_eq!(w.participant_guid.prefix, prefix(3));
1600 let r = EndpointData::from_parameter_list(&l, e, false).unwrap();
1601 assert_eq!(r.reliability.kind, ReliabilityKind::BestEffort);
1602 l.push(Parameter::new(
1603 crate::parameter::ParameterId(0x4fff),
1604 [0; 4],
1605 ));
1606 assert!(matches!(
1607 EndpointData::from_parameter_list(&l, e, true),
1608 Err(DecodeError::MustUnderstand(_))
1609 ));
1610 }
1611
1612 #[test]
1613 fn match_rules() {
1614 let w = EndpointData::writer(wguid(1), "T", "X");
1615 let r = EndpointData::reader(rguid(2), "T", "X");
1616 assert!(endpoints_match(&w, &r));
1617 let mut r2 = r.clone();
1618 r2.topic_name = "U".into();
1619 assert!(!endpoints_match(&w, &r2));
1620 r2.topic_aliases = vec!["V".into(), "T".into()];
1622 assert!(endpoints_match(&w, &r2));
1623 let mut w2 = w.clone();
1624 w2.topic_name = "U".into();
1625 w2.topic_aliases = vec!["T".into()];
1626 assert!(endpoints_match(&w2, &r));
1627 let mut r2 = r.clone();
1628 r2.type_name = "Y".into();
1629 assert!(!endpoints_match(&w, &r2));
1630 let mut r2 = r.clone();
1631 r2.durability = DurabilityKind::TransientLocal;
1632 assert!(!endpoints_match(&w, &r2));
1633 let mut w2 = w.clone();
1634 w2.reliability.kind = ReliabilityKind::BestEffort;
1635 let mut r2 = r.clone();
1636 r2.reliability.kind = ReliabilityKind::Reliable;
1637 assert!(!endpoints_match(&w2, &r2));
1638 assert!(endpoints_match(&w, &r2));
1639 let mut r2 = r.clone();
1640 r2.partitions = vec!["x".into()];
1641 assert!(!endpoints_match(&w, &r2));
1642 }
1643
1644 #[test]
1645 fn discover_match_and_remove() {
1646 let t = Instant::now();
1647 let (mut a, mut b) = pair(t);
1648 assert!(
1649 a.add_writer(EndpointData::writer(wguid(1), "T", "X"))
1650 .is_empty()
1651 );
1652 assert!(
1653 b.add_reader(EndpointData::reader(rguid(2), "T", "X"))
1654 .is_empty()
1655 );
1656 let (ea, eb) = pump(&mut a, &mut b, t, |_| false);
1657
1658 let mut w = EndpointData::writer(wguid(1), "T", "X");
1660 w.unicast_locators = participant(1).default_unicast_locators;
1661 assert_eq!(
1662 eb,
1663 [
1664 SedpEvent::WriterDiscovered(w),
1665 SedpEvent::Matched {
1666 local: rguid(2),
1667 remote: wguid(1)
1668 }
1669 ]
1670 );
1671 assert_eq!(ea.len(), 2);
1672 assert_eq!(
1673 ea[1],
1674 SedpEvent::Matched {
1675 local: wguid(1),
1676 remote: rguid(2)
1677 }
1678 );
1679 assert_eq!(a.matched(&wguid(1)).collect::<Vec<_>>(), [&rguid(2)]);
1680 assert!(a.remote_reader(&rguid(2)).is_some());
1681
1682 assert_eq!(
1684 a.remove_writer(&wguid(1)),
1685 [SedpEvent::Unmatched {
1686 local: wguid(1),
1687 remote: rguid(2)
1688 }]
1689 );
1690 let (_, eb) = pump(&mut a, &mut b, t + StdDuration::from_secs(100), |_| false);
1691 assert_eq!(
1692 eb,
1693 [
1694 SedpEvent::Unmatched {
1695 local: rguid(2),
1696 remote: wguid(1)
1697 },
1698 SedpEvent::WriterRemoved(wguid(1))
1699 ]
1700 );
1701 assert_eq!(b.remote_writers().count(), 0);
1702
1703 assert_eq!(
1705 a.remove_participant(&prefix(2)),
1706 [SedpEvent::ReaderRemoved(rguid(2))]
1707 );
1708 }
1709
1710 #[test]
1711 fn qos_update_changes_the_match() {
1712 let t = Instant::now();
1713 let (mut a, mut b) = pair(t);
1714 let mut w = EndpointData::writer(wguid(1), "T", "X");
1715 w.reliability.kind = ReliabilityKind::BestEffort;
1716 a.add_writer(w.clone());
1717 let mut r = EndpointData::reader(rguid(2), "T", "X");
1718 r.reliability.kind = ReliabilityKind::Reliable;
1719 b.add_reader(r);
1720 let (_, eb) = pump(&mut a, &mut b, t, |_| false);
1721 assert_eq!(eb.len(), 2, "{eb:?}");
1722 assert!(matches!(eb[0], SedpEvent::WriterDiscovered(_)));
1723 assert_eq!(
1725 eb[1],
1726 SedpEvent::IncompatibleQos {
1727 local: rguid(2),
1728 remote: wguid(1),
1729 policies: vec![QosPolicyId::RELIABILITY],
1730 }
1731 );
1732
1733 w.reliability.kind = ReliabilityKind::Reliable;
1734 a.add_writer(w);
1735 let (_, eb) = pump(&mut a, &mut b, t + StdDuration::from_secs(100), |_| false);
1736 assert!(matches!(eb[0], SedpEvent::WriterUpdated(_)));
1737 assert_eq!(
1738 eb[1],
1739 SedpEvent::Matched {
1740 local: rguid(2),
1741 remote: wguid(1)
1742 }
1743 );
1744 }
1745
1746 #[test]
1747 fn survives_loss() {
1748 let t = Instant::now();
1749 let (mut a, mut b) = pair(t);
1750 for i in 0..5u8 {
1751 let g = Guid::new(
1752 prefix(1),
1753 EntityId::user([0, 1, i], entity_kind::USER_WRITER_NO_KEY),
1754 );
1755 a.add_writer(EndpointData::writer(g, "T", "X"));
1756 }
1757 b.add_reader(EndpointData::reader(rguid(2), "T", "X"));
1758 let (_, eb) = pump(&mut a, &mut b, t, |i| i < 12 && i % 2 == 0);
1760 let matched = eb
1761 .iter()
1762 .filter(|e| matches!(e, SedpEvent::Matched { .. }))
1763 .count();
1764 assert_eq!(matched, 5, "{eb:?}");
1765 assert_eq!(b.remote_writers().count(), 5);
1766 }
1767
1768 #[test]
1769 fn own_and_unknown_participants_are_ignored() {
1770 let t = Instant::now();
1771 let mut a = sedp(1);
1772 a.add_participant(&participant(1), t);
1773 assert!(a.poll(t).is_empty());
1774 let mut c = sedp(3);
1776 c.add_participant(&participant(1), t);
1777 c.add_writer(EndpointData::writer(wguid(3), "T", "X"));
1778 for o in c.poll(t) {
1779 assert!(a.handle_message(&o.bytes, t).is_empty());
1780 }
1781 assert!(a.handle_message(b"junk", t).is_empty());
1782 }
1783
1784 fn appendable(name: &str, members: &[&str]) -> rustorb_xtypes::types::TypeObjects {
1785 use rustorb_xtypes::types::*;
1786 let ty: Type = StructType {
1787 name: name.into(),
1788 members: members
1789 .iter()
1790 .enumerate()
1791 .map(|(i, m)| StructMember::new(*m, i as u32, Type::Primitive(Primitive::Int32)))
1792 .collect(),
1793 ..Default::default()
1794 }
1795 .into();
1796 TypeObjects::new(&ty).unwrap()
1797 }
1798
1799 #[test]
1800 fn xtypes_parameters_round_trip() {
1801 let mut d = EndpointData::reader(rguid(1), "T", "X");
1802 d.type_information = Some(appendable("X", &["a", "b"]).information);
1803 d.data_representation = vec![data_representation::XCDR, data_representation::XCDR2];
1804 d.type_consistency = Some(TypeConsistency {
1805 ignore_member_names: true,
1806 ..Default::default()
1807 });
1808 for e in [Endianness::Big, Endianness::Little] {
1809 assert_eq!(
1810 EndpointData::from_payload(&d.to_payload(e), false).unwrap(),
1811 d
1812 );
1813 }
1814 }
1815
1816 #[test]
1819 fn cyclonedds_parameters() {
1820 let hex = |s: &str| -> Vec<u8> {
1821 (0..s.len())
1822 .step_by(2)
1823 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
1824 .collect()
1825 };
1826 let e = Endianness::Little;
1827 let b = PlBuilder::new(e);
1828 let mut l = ParameterList::new();
1829 l.push(b.guid(pid::ENDPOINT_GUID, rguid(3)));
1830 l.push(b.string(pid::TOPIC_NAME, "hello_world"));
1831 l.push(b.string(pid::TYPE_NAME, "HelloWorld::Greeting"));
1832 l.push(Parameter::new(
1833 pid::DATA_REPRESENTATION,
1834 hex("0200000000000200"),
1835 ));
1836 l.push(Parameter::new(
1837 pid::TYPE_INFORMATION,
1838 hex(concat!(
1839 "6000000001100040280000002400000014000000f14c98d3b709b9631e344fd7",
1840 "0a3402003800000000000000040000000000000002100040280000002400000014",
1841 "000000f2d8dede3f3e15043e059145548d1b006600000000000000040000000000",
1842 "0000"
1843 )),
1844 ));
1845 let d = EndpointData::from_parameter_list(&l, e, false).unwrap();
1846 assert_eq!(d.data_representation, vec![0, 2]);
1847 assert!(d.accepts_representation(data_representation::XCDR));
1848 assert!(d.accepts_representation(data_representation::XCDR2));
1849 let info = d.type_information.as_ref().unwrap();
1850 assert_eq!(
1851 info.minimal.typeid_with_size.type_id,
1852 TypeIdentifier::Minimal(hex("4c98d3b709b9631e344fd70a3402").try_into().unwrap())
1853 );
1854 assert_eq!(info.minimal.typeid_with_size.typeobject_serialized_size, 56);
1855 assert_eq!(d.type_consistency, None);
1858 assert_eq!(d.effective_type_consistency(), TypeConsistency::default());
1859 let mut l2 = l.clone();
1861 l2.parameters.retain(|p| p.id != pid::TYPE_INFORMATION);
1862 l2.push(Parameter::new(pid::TYPE_INFORMATION, vec![1, 2, 3, 4]));
1863 let d2 = EndpointData::from_parameter_list(&l2, e, false).unwrap();
1864 assert_eq!(d2.type_information, None);
1865 assert_eq!(
1866 d2.effective_type_consistency(),
1867 TypeConsistency::NOT_ANNOUNCED
1868 );
1869 }
1870
1871 #[test]
1872 fn type_and_representation_rules() {
1873 let registry = TypeRegistry::new();
1874 let v1 = appendable("X", &["a"]);
1875 let mut w = EndpointData::writer(wguid(1), "T", "X");
1876 let mut r = EndpointData::reader(rguid(2), "T", "X");
1877 r.type_name = "Y".into();
1879 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Inconsistent);
1880 w.type_information = Some(v1.information.clone());
1882 r.type_information = Some(v1.information.clone());
1883 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Matched);
1884 w.data_representation = vec![data_representation::XCDR2];
1886 assert_eq!(
1887 match_endpoints(&w, &r, ®istry),
1888 Match::Incompatible(vec![DATA_REPRESENTATION_QOS_POLICY_ID])
1889 );
1890 r.data_representation = vec![data_representation::XCDR, data_representation::XCDR2];
1891 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Matched);
1892 r.partitions = vec!["p".into()];
1894 r.type_consistency = Some(TypeConsistency {
1895 kind: TypeConsistencyKind::DisallowTypeCoercion,
1896 ..Default::default()
1897 });
1898 w.type_information = Some(appendable("X", &["a", "b"]).information);
1899 assert_eq!(match_endpoints(&w, &r, ®istry), Match::Inconsistent);
1900 }
1901
1902 #[test]
1903 fn inconsistent_and_unresolved_types() {
1904 let t = Instant::now();
1905 let (mut a, mut b) = pair(t);
1906 let v1 = appendable("X", &["a"]);
1907 let v2 = appendable("X", &["a", "b"]);
1908 let other = appendable("X", &["z"]);
1909 a.registry_mut().add_type(&v2);
1910 b.registry_mut().add_type(&v1);
1911 let mut w = EndpointData::writer(wguid(1), "T", "X");
1913 w.type_information = Some(v2.information.clone());
1914 a.add_writer(w);
1915 let mut r = EndpointData::reader(rguid(2), "T", "X");
1916 r.type_information = Some(v1.information.clone());
1917 b.add_reader(r);
1918 let (ea, eb) = pump(&mut a, &mut b, t, |_| false);
1919 assert!(
1920 !eb.iter().any(|e| matches!(e, SedpEvent::Matched { .. })),
1921 "{eb:?}"
1922 );
1923 assert!(
1924 !ea.iter().any(|e| matches!(e, SedpEvent::Matched { .. })),
1925 "{ea:?}"
1926 );
1927 assert_eq!(
1928 b.unresolved_types(),
1929 vec![(v2.minimal_id().clone(), wguid(1))]
1930 );
1931 assert_eq!(
1932 a.unresolved_types(),
1933 vec![(v1.minimal_id().clone(), rguid(2))]
1934 );
1935 b.registry_mut().add_pairs(&v2.minimal).unwrap();
1938 assert_eq!(
1939 b.rematch_unresolved(),
1940 vec![SedpEvent::Matched {
1941 local: rguid(2),
1942 remote: wguid(1)
1943 }]
1944 );
1945 a.registry_mut().add_pairs(&v1.minimal).unwrap();
1946 assert_eq!(
1947 a.rematch_unresolved(),
1948 vec![SedpEvent::Matched {
1949 local: wguid(1),
1950 remote: rguid(2)
1951 }]
1952 );
1953 assert!(b.unresolved_types().is_empty());
1954
1955 let w3 = Guid::new(
1958 prefix(1),
1959 EntityId::user([0, 0, 3], entity_kind::USER_WRITER_NO_KEY),
1960 );
1961 let mut w = EndpointData::writer(w3, "T", "X");
1962 w.type_information = Some(other.information.clone());
1963 a.registry_mut().add_type(&other);
1964 b.registry_mut().add_pairs(&other.minimal).unwrap();
1965 let ea = a.add_writer(w);
1966 let (_, eb) = pump(&mut a, &mut b, t + StdDuration::from_secs(100), |_| false);
1967 assert!(ea.contains(&SedpEvent::InconsistentTopic {
1968 local: w3,
1969 remote: rguid(2)
1970 }));
1971 assert!(eb.contains(&SedpEvent::InconsistentTopic {
1972 local: rguid(2),
1973 remote: w3
1974 }));
1975 assert!(!eb.iter().any(|e| matches!(e, SedpEvent::Matched { .. })));
1976 }
1977}