1use std::collections::hash_map::Entry;
11use std::collections::{HashMap, HashSet};
12use std::time::Instant;
13
14use crate::error::DecodeError;
15use crate::message::{Header, Message};
16use crate::parameter::{ParameterList, SecurityParameters};
17use crate::pl::{PlBuilder, PlValues, decode_pl_payload, encode_pl_payload, pid};
18use crate::submessage::{Data, InfoTimestamp, PayloadKind, SerializedPayload, Submessage};
19use crate::types::{
20 BuiltinEndpointSet, Count, Duration, EntityId, Guid, GuidPrefix, Locator, ProtocolVersion,
21 SequenceNumber, Time, VendorId,
22};
23use crate::wire::Endianness;
24
25#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct ParticipantData {
28 pub guid_prefix: GuidPrefix,
30 pub domain_id: Option<u32>,
33 pub domain_tag: String,
35 pub protocol_version: ProtocolVersion,
37 pub vendor_id: VendorId,
39 pub expects_inline_qos: bool,
41 pub metatraffic_unicast_locators: Vec<Locator>,
43 pub metatraffic_multicast_locators: Vec<Locator>,
45 pub default_unicast_locators: Vec<Locator>,
47 pub default_multicast_locators: Vec<Locator>,
49 pub available_builtin_endpoints: BuiltinEndpointSet,
51 pub lease_duration: Duration,
53 pub manual_liveliness_count: Option<Count>,
55 pub builtin_endpoint_qos: Option<u32>,
57 pub user_data: Vec<u8>,
59 pub entity_name: Option<String>,
61 pub security: SecurityParameters,
63}
64
65impl ParticipantData {
66 pub const DEFAULT_LEASE_DURATION: Duration = Duration::from_secs(100);
68
69 pub fn new(guid_prefix: GuidPrefix, vendor_id: VendorId) -> Self {
71 ParticipantData {
72 guid_prefix,
73 domain_id: None,
74 domain_tag: String::new(),
75 protocol_version: ProtocolVersion::CURRENT,
76 vendor_id,
77 expects_inline_qos: false,
78 metatraffic_unicast_locators: Vec::new(),
79 metatraffic_multicast_locators: Vec::new(),
80 default_unicast_locators: Vec::new(),
81 default_multicast_locators: Vec::new(),
82 available_builtin_endpoints: BuiltinEndpointSet(
83 BuiltinEndpointSet::PARTICIPANT_ANNOUNCER
84 | BuiltinEndpointSet::PARTICIPANT_DETECTOR,
85 ),
86 lease_duration: Self::DEFAULT_LEASE_DURATION,
87 manual_liveliness_count: None,
88 builtin_endpoint_qos: None,
89 user_data: Vec::new(),
90 entity_name: None,
91 security: SecurityParameters::default(),
92 }
93 }
94
95 pub fn guid(&self) -> Guid {
97 Guid::new(self.guid_prefix, EntityId::PARTICIPANT)
98 }
99
100 pub fn to_parameter_list(&self, endianness: Endianness) -> ParameterList {
103 let b = PlBuilder::new(endianness);
104 let mut l = ParameterList::new();
105 l.push(b.guid(pid::PARTICIPANT_GUID, self.guid()));
106 if let Some(d) = self.domain_id {
107 l.push(b.u32(pid::DOMAIN_ID, d));
108 }
109 if !self.domain_tag.is_empty() {
110 l.push(b.string(pid::DOMAIN_TAG, &self.domain_tag));
111 }
112 l.push(b.protocol_version(pid::PROTOCOL_VERSION, self.protocol_version));
113 l.push(b.vendor_id(pid::VENDORID, self.vendor_id));
114 if self.expects_inline_qos {
115 l.push(b.bool(pid::EXPECTS_INLINE_QOS, true));
116 }
117 for (id, list) in [
118 (
119 pid::METATRAFFIC_UNICAST_LOCATOR,
120 &self.metatraffic_unicast_locators,
121 ),
122 (
123 pid::METATRAFFIC_MULTICAST_LOCATOR,
124 &self.metatraffic_multicast_locators,
125 ),
126 (pid::DEFAULT_UNICAST_LOCATOR, &self.default_unicast_locators),
127 (
128 pid::DEFAULT_MULTICAST_LOCATOR,
129 &self.default_multicast_locators,
130 ),
131 ] {
132 for loc in list {
133 l.push(b.locator(id, loc));
134 }
135 }
136 l.push(b.u32(
137 pid::BUILTIN_ENDPOINT_SET,
138 self.available_builtin_endpoints.0,
139 ));
140 if self.lease_duration != Self::DEFAULT_LEASE_DURATION {
141 l.push(b.duration(pid::PARTICIPANT_LEASE_DURATION, self.lease_duration));
142 }
143 if let Some(c) = self.manual_liveliness_count {
144 l.push(b.u32(pid::PARTICIPANT_MANUAL_LIVELINESS_COUNT, c.0 as u32));
145 }
146 if let Some(q) = self.builtin_endpoint_qos {
147 l.push(b.u32(pid::BUILTIN_ENDPOINT_QOS, q));
148 }
149 if !self.user_data.is_empty() {
150 l.push(b.octets(pid::USER_DATA, &self.user_data));
151 }
152 if let Some(n) = &self.entity_name {
153 l.push(b.string(pid::ENTITY_NAME, n));
154 }
155 for p in self.security.of(endianness) {
156 l.push(p.clone());
157 }
158 l
159 }
160
161 pub fn to_payload(&self, endianness: Endianness) -> Vec<u8> {
163 encode_pl_payload(&self.to_parameter_list(endianness), endianness)
164 }
165
166 pub fn from_parameter_list(
174 list: &ParameterList,
175 endianness: Endianness,
176 ) -> Result<Self, DecodeError> {
177 let v = PlValues::new(endianness);
178 let mut d = ParticipantData::new(GuidPrefix::UNKNOWN, VendorId::UNKNOWN);
179 let mut guid = None;
180 for p in &list.parameters {
181 match p.id {
182 pid::PARTICIPANT_GUID => guid = Some(v.guid(p)?),
183 pid::DOMAIN_ID => d.domain_id = Some(v.u32(p)?),
184 pid::DOMAIN_TAG => d.domain_tag = v.string(p)?,
185 pid::PROTOCOL_VERSION => d.protocol_version = v.protocol_version(p)?,
186 pid::VENDORID => d.vendor_id = v.vendor_id(p)?,
187 pid::EXPECTS_INLINE_QOS => d.expects_inline_qos = v.bool(p)?,
188 pid::METATRAFFIC_UNICAST_LOCATOR => {
189 d.metatraffic_unicast_locators.push(v.locator(p)?)
190 }
191 pid::METATRAFFIC_MULTICAST_LOCATOR => {
192 d.metatraffic_multicast_locators.push(v.locator(p)?)
193 }
194 pid::DEFAULT_UNICAST_LOCATOR => d.default_unicast_locators.push(v.locator(p)?),
195 pid::DEFAULT_MULTICAST_LOCATOR => d.default_multicast_locators.push(v.locator(p)?),
196 pid::BUILTIN_ENDPOINT_SET => {
197 d.available_builtin_endpoints = BuiltinEndpointSet(v.u32(p)?)
198 }
199 pid::PARTICIPANT_LEASE_DURATION => d.lease_duration = v.duration(p)?,
200 pid::PARTICIPANT_MANUAL_LIVELINESS_COUNT => {
201 d.manual_liveliness_count = Some(Count(v.u32(p)? as i32))
202 }
203 pid::BUILTIN_ENDPOINT_QOS => d.builtin_endpoint_qos = Some(v.u32(p)?),
204 pid::USER_DATA => d.user_data = v.octets(p)?,
205 pid::ENTITY_NAME => d.entity_name = Some(v.string(p)?),
206 id if SecurityParameters::is_security(id) => d.security.push(p.clone(), endianness),
207 id if !id.is_vendor_specific() && id.must_understand() => {
208 return Err(DecodeError::MustUnderstand(id));
209 }
210 _ => {}
211 }
212 }
213 let guid = guid.ok_or(DecodeError::MissingParameter(pid::PARTICIPANT_GUID))?;
214 d.guid_prefix = guid.prefix;
215 Ok(d)
216 }
217
218 pub fn from_payload(bytes: &[u8]) -> Result<Self, DecodeError> {
220 let (list, e) = decode_pl_payload(bytes)?;
221 Self::from_parameter_list(&list, e)
222 }
223}
224
225#[derive(Clone, Debug)]
227pub struct SpdpConfig {
228 pub domain_id: u32,
230 pub announce_period: std::time::Duration,
233 pub announce_locators: Vec<Locator>,
236}
237
238impl SpdpConfig {
239 pub fn new(domain_id: u32, announce_locators: Vec<Locator>) -> Self {
241 SpdpConfig {
242 domain_id,
243 announce_period: std::time::Duration::from_secs(30),
244 announce_locators,
245 }
246 }
247}
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251pub enum RemovalReason {
252 LeaseExpired,
254 Disposed,
256}
257
258#[derive(Clone, Debug, PartialEq, Eq)]
260pub enum ParticipantEvent {
261 Discovered(ParticipantData),
263 Updated(ParticipantData),
265 Removed(GuidPrefix, RemovalReason),
267}
268
269#[derive(Debug)]
270struct Remote {
271 data: ParticipantData,
272 expires: Option<Instant>,
273}
274
275#[derive(Debug)]
281pub struct Spdp {
282 local: ParticipantData,
283 config: SpdpConfig,
284 sequence_number: SequenceNumber,
285 next_announce: Option<Instant>,
286 remote: HashMap<GuidPrefix, Remote>,
287 secured: HashSet<GuidPrefix>,
290}
291
292const STATUS_DISPOSED: u8 = 0x01;
294const STATUS_UNREGISTERED: u8 = 0x02;
295
296impl Spdp {
297 pub fn new(local: ParticipantData, config: SpdpConfig) -> Self {
300 Spdp {
301 local,
302 config,
303 sequence_number: SequenceNumber(1),
304 next_announce: None,
305 remote: HashMap::new(),
306 secured: HashSet::new(),
307 }
308 }
309
310 pub fn local(&self) -> &ParticipantData {
312 &self.local
313 }
314
315 pub fn set_local(&mut self, data: ParticipantData) {
318 self.local = data;
319 self.sequence_number.0 += 1;
320 self.next_announce = None;
321 }
322
323 pub fn announcement(&self, endianness: Endianness) -> Message {
327 let mut msg = Message::new(Header::new(self.local.vendor_id, self.local.guid_prefix));
328 msg.submessages
329 .push(Submessage::InfoTimestamp(InfoTimestamp {
330 timestamp: Some(Time::now()),
331 }));
332 msg.submessages.push(Submessage::Data(Data {
333 reader_id: EntityId::UNKNOWN,
334 writer_id: EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER,
335 writer_sn: self.sequence_number,
336 inline_qos: None,
337 serialized_payload: Some(SerializedPayload {
338 kind: PayloadKind::Data,
339 bytes: self.local.to_payload(endianness),
340 }),
341 non_standard_payload: false,
342 }));
343 msg
344 }
345
346 pub fn dispose(&mut self) -> (Vec<u8>, &[Locator]) {
352 self.sequence_number.0 += 1;
353 let e = Endianness::NATIVE;
354 let guid = self.local.guid();
355 let mut qos = ParameterList::new();
356 qos.push(crate::parameter::Parameter::new(
357 pid::KEY_HASH,
358 guid.to_bytes(),
359 ));
360 qos.push(crate::parameter::Parameter::new(
361 pid::STATUS_INFO,
362 [0, 0, 0, STATUS_DISPOSED | STATUS_UNREGISTERED],
363 ));
364 let mut key = ParameterList::new();
365 key.push(PlBuilder::new(e).guid(pid::PARTICIPANT_GUID, guid));
366 let mut msg = Message::new(Header::new(self.local.vendor_id, self.local.guid_prefix));
367 msg.submessages
368 .push(Submessage::InfoTimestamp(InfoTimestamp {
369 timestamp: Some(Time::now()),
370 }));
371 msg.submessages.push(Submessage::Data(Data {
372 reader_id: EntityId::UNKNOWN,
373 writer_id: EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER,
374 writer_sn: self.sequence_number,
375 inline_qos: Some(qos),
376 serialized_payload: Some(SerializedPayload {
377 kind: PayloadKind::Key,
378 bytes: encode_pl_payload(&key, e),
379 }),
380 non_standard_payload: false,
381 }));
382 let bytes = msg.encode(e).expect("a dispose is always encodable");
383 (bytes, &self.config.announce_locators)
384 }
385
386 pub fn poll_announce(&mut self, now: Instant) -> Option<(Vec<u8>, &[Locator])> {
389 if self.next_announce.is_some_and(|t| now < t) {
390 return None;
391 }
392 self.next_announce = Some(now + self.config.announce_period);
393 let bytes = self
394 .announcement(Endianness::NATIVE)
395 .encode(Endianness::NATIVE)
396 .expect("an announcement is always encodable");
397 Some((bytes, &self.config.announce_locators))
398 }
399
400 pub fn next_deadline(&self) -> Option<Instant> {
403 let expiry = self.remote.values().filter_map(|r| r.expires).min();
404 match (self.next_announce, expiry) {
405 (Some(a), Some(b)) => Some(a.min(b)),
406 (a, b) => a.or(b),
407 }
408 }
409
410 pub fn participants(&self) -> impl Iterator<Item = &ParticipantData> {
412 self.remote.values().map(|r| &r.data)
413 }
414
415 pub fn participant(&self, prefix: &GuidPrefix) -> Option<&ParticipantData> {
417 self.remote.get(prefix).map(|r| &r.data)
418 }
419
420 pub fn remove_expired(&mut self, now: Instant) -> Vec<ParticipantEvent> {
422 let gone: Vec<GuidPrefix> = self
423 .remote
424 .iter()
425 .filter(|(_, r)| r.expires.is_some_and(|t| t <= now))
426 .map(|(k, _)| *k)
427 .collect();
428 gone.into_iter()
429 .map(|k| {
430 self.remote.remove(&k);
431 self.secured.remove(&k);
432 ParticipantEvent::Removed(k, RemovalReason::LeaseExpired)
433 })
434 .collect()
435 }
436
437 pub fn handle_message(&mut self, bytes: &[u8], now: Instant) -> Vec<ParticipantEvent> {
445 let Ok((_, submessages)) = Message::parse(bytes) else {
446 return Vec::new();
447 };
448 let mut events = Vec::new();
449 let mut for_us = true;
450 for sub in submessages {
451 let Ok(sub) = sub else { break };
452 match sub {
453 Submessage::InfoDestination(d) => {
454 for_us = d.guid_prefix == GuidPrefix::UNKNOWN
455 || d.guid_prefix == self.local.guid_prefix;
456 }
457 Submessage::Data(d)
458 if for_us && d.writer_id == EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER =>
459 {
460 if let Some(e) = self.handle_data(&d, now) {
461 events.push(e);
462 }
463 }
464 _ => {}
465 }
466 }
467 events
468 }
469
470 fn handle_data(&mut self, d: &Data, now: Instant) -> Option<ParticipantEvent> {
471 let status = d
472 .inline_qos
473 .as_ref()
474 .and_then(|q| q.get(pid::STATUS_INFO))
475 .and_then(|p| p.value.get(3).copied())
476 .unwrap_or(0);
477 if status & (STATUS_DISPOSED | STATUS_UNREGISTERED) != 0 {
478 let prefix = self.disposed_key(d)?;
479 if self.secured.contains(&prefix) {
480 return None;
481 }
482 self.remote.remove(&prefix)?;
483 return Some(ParticipantEvent::Removed(prefix, RemovalReason::Disposed));
484 }
485 let payload = d.serialized_payload.as_ref()?;
486 if payload.kind != PayloadKind::Data {
487 return None;
488 }
489 let data = ParticipantData::from_payload(&payload.bytes).ok()?;
490 if data.guid_prefix == self.local.guid_prefix
491 || data.domain_id.is_some_and(|id| id != self.config.domain_id)
492 || data.domain_tag != self.local.domain_tag
493 {
494 return None;
495 }
496 if self.secured.contains(&data.guid_prefix) {
497 if let Some(r) = self.remote.get_mut(&data.guid_prefix) {
499 r.expires = r.data.lease_duration.to_std().map(|d| now + d);
500 }
501 return None;
502 }
503 self.update(data, now)
504 }
505
506 pub fn handle_secure(
511 &mut self,
512 event: crate::spdp_secure::SecureParticipantEvent,
513 now: Instant,
514 ) -> Option<ParticipantEvent> {
515 use crate::spdp_secure::SecureParticipantEvent as S;
516 match event {
517 S::Data(data) => {
518 let data = *data;
519 if data.guid_prefix == self.local.guid_prefix
520 || data.domain_id.is_some_and(|id| id != self.config.domain_id)
521 || data.domain_tag != self.local.domain_tag
522 {
523 return None;
524 }
525 self.secured.insert(data.guid_prefix);
526 self.update(data, now)
527 }
528 S::Disposed(prefix) => {
529 self.secured.remove(&prefix);
530 self.remote.remove(&prefix)?;
531 Some(ParticipantEvent::Removed(prefix, RemovalReason::Disposed))
532 }
533 }
534 }
535
536 fn update(&mut self, data: ParticipantData, now: Instant) -> Option<ParticipantEvent> {
538 let expires = data.lease_duration.to_std().map(|d| now + d);
539 match self.remote.entry(data.guid_prefix) {
540 Entry::Occupied(mut o) => {
541 let r = o.get_mut();
542 r.expires = expires;
543 if r.data == data {
544 None
545 } else {
546 r.data = data.clone();
547 Some(ParticipantEvent::Updated(data))
548 }
549 }
550 Entry::Vacant(v) => {
551 v.insert(Remote {
552 data: data.clone(),
553 expires,
554 });
555 self.next_announce = None;
558 Some(ParticipantEvent::Discovered(data))
559 }
560 }
561 }
562
563 fn disposed_key(&self, d: &Data) -> Option<GuidPrefix> {
568 if let Some(p) = &d.serialized_payload
569 && let Ok((list, e)) = decode_pl_payload(&p.bytes)
570 && let Some(g) = list.get(pid::PARTICIPANT_GUID)
571 {
572 return PlValues::new(e).guid(g).ok().map(|g| g.prefix);
573 }
574 let hash = d.inline_qos.as_ref()?.get(pid::KEY_HASH)?;
575 let mut prefix = [0u8; 12];
576 prefix.copy_from_slice(hash.value.get(..12)?);
577 Some(GuidPrefix(prefix))
578 }
579}
580
581#[cfg(test)]
582mod tests {
583 use super::*;
584 use crate::parameter::Parameter;
585 use std::time::Duration as StdDuration;
586
587 fn data(n: u8) -> ParticipantData {
588 let mut d = ParticipantData::new(GuidPrefix([n; 12]), VendorId([0x01, 0x99]));
589 d.domain_id = Some(7);
590 d.metatraffic_unicast_locators = vec![Locator::udpv4("10.0.0.1:9160".parse().unwrap())];
591 d.metatraffic_multicast_locators =
592 vec![Locator::udpv4("239.255.0.1:9150".parse().unwrap())];
593 d.default_unicast_locators = vec![Locator::udpv4("10.0.0.1:9161".parse().unwrap())];
594 d.lease_duration = Duration::from_secs(10);
595 d
596 }
597
598 fn spdp(n: u8) -> Spdp {
599 Spdp::new(data(n), SpdpConfig::new(7, vec![]))
600 }
601
602 #[test]
603 fn participant_data_round_trip() {
604 let mut d = data(1);
605 d.domain_tag = "tag".into();
606 d.expects_inline_qos = true;
607 d.manual_liveliness_count = Some(Count(3));
608 d.builtin_endpoint_qos = Some(1);
609 d.user_data = vec![1, 2, 3];
610 d.entity_name = Some("p".into());
611 d.default_multicast_locators = vec![Locator::udpv4("239.255.0.1:9151".parse().unwrap())];
612 for e in [Endianness::Big, Endianness::Little] {
613 assert_eq!(ParticipantData::from_payload(&d.to_payload(e)).unwrap(), d);
614 }
615 }
616
617 #[test]
618 fn participant_data_rules() {
619 let e = Endianness::Little;
620 let b = PlBuilder::new(e);
621 let l = ParameterList::new();
623 assert_eq!(
624 ParticipantData::from_parameter_list(&l, e),
625 Err(DecodeError::MissingParameter(pid::PARTICIPANT_GUID))
626 );
627 let mut l = ParameterList::new();
628 l.push(b.guid(pid::PARTICIPANT_GUID, data(2).guid()));
629 l.push(Parameter::new(ParameterId(0x0fff), [0; 4]));
632 l.push(Parameter::new(ParameterId(0xc001), [0; 4]));
633 let d = ParticipantData::from_parameter_list(&l, e).unwrap();
634 assert_eq!(d.guid_prefix, GuidPrefix([2; 12]));
635 assert_eq!(d.domain_id, None);
636 assert_eq!(d.lease_duration, ParticipantData::DEFAULT_LEASE_DURATION);
637 l.push(Parameter::new(ParameterId(0x4fff), [0; 4]));
639 assert_eq!(
640 ParticipantData::from_parameter_list(&l, e),
641 Err(DecodeError::MustUnderstand(ParameterId(0x4fff)))
642 );
643 }
644
645 use crate::parameter::ParameterId;
646
647 #[test]
648 fn announce_schedule() {
649 let mut s = spdp(1);
650 s.config.announce_locators = vec![Locator::udpv4("239.255.0.1:9150".parse().unwrap())];
651 let t0 = Instant::now();
652 let (bytes, to) = s.poll_announce(t0).unwrap();
653 assert_eq!(to.len(), 1);
654 let msg = Message::decode(&bytes).unwrap();
655 assert_eq!(msg.header.guid_prefix, GuidPrefix([1; 12]));
656 let Submessage::Data(d) = &msg.submessages[1] else {
657 panic!()
658 };
659 assert_eq!(d.reader_id, EntityId::UNKNOWN);
660 assert_eq!(d.writer_id, EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER);
661 assert_eq!(
662 ParticipantData::from_payload(&d.serialized_payload.as_ref().unwrap().bytes).unwrap(),
663 data(1)
664 );
665 assert!(s.poll_announce(t0 + StdDuration::from_secs(29)).is_none());
666 assert!(s.poll_announce(t0 + StdDuration::from_secs(30)).is_some());
667 assert_eq!(s.next_deadline(), Some(t0 + StdDuration::from_secs(60)));
668 }
669
670 #[test]
671 fn discover_update_and_expire() {
672 let mut a = spdp(1);
673 let mut b = spdp(2);
674 let t0 = Instant::now();
675 let (msg_b, _) = b.poll_announce(t0).unwrap();
676 let (_, _) = a.poll_announce(t0).unwrap();
677
678 let ev = a.handle_message(&msg_b, t0);
679 assert_eq!(ev, [ParticipantEvent::Discovered(data(2))]);
680 assert!(a.poll_announce(t0).is_some());
682 let t1 = t0 + StdDuration::from_secs(8);
684 assert!(a.handle_message(&msg_b, t1).is_empty());
685 assert!(a.remove_expired(t0 + StdDuration::from_secs(12)).is_empty());
686
687 let mut changed = data(2);
688 changed.user_data = vec![9];
689 b.set_local(changed.clone());
690 let (msg_b2, _) = b.poll_announce(t1).unwrap();
691 assert_eq!(
692 a.handle_message(&msg_b2, t1),
693 [ParticipantEvent::Updated(changed)]
694 );
695 assert_eq!(a.participants().count(), 1);
696
697 assert_eq!(
698 a.remove_expired(t1 + StdDuration::from_secs(10)),
699 [ParticipantEvent::Removed(
700 GuidPrefix([2; 12]),
701 RemovalReason::LeaseExpired
702 )]
703 );
704 assert_eq!(a.participants().count(), 0);
705 }
706
707 #[test]
708 fn ignored_announcements() {
709 let mut a = spdp(1);
710 let t0 = Instant::now();
711 let (own, _) = a.poll_announce(t0).unwrap();
713 assert!(a.handle_message(&own, t0).is_empty());
714 let mut other = data(3);
716 other.domain_id = Some(8);
717 let mut s = Spdp::new(other, SpdpConfig::new(8, vec![]));
718 let (m, _) = s.poll_announce(t0).unwrap();
719 assert!(a.handle_message(&m, t0).is_empty());
720 let mut other = data(4);
722 other.domain_tag = "x".into();
723 let mut s = Spdp::new(other, SpdpConfig::new(7, vec![]));
724 let (m, _) = s.poll_announce(t0).unwrap();
725 assert!(a.handle_message(&m, t0).is_empty());
726 let mut other = data(5);
728 other.domain_id = None;
729 let mut s = Spdp::new(other, SpdpConfig::new(7, vec![]));
730 let (m, _) = s.poll_announce(t0).unwrap();
731 assert_eq!(a.handle_message(&m, t0).len(), 1);
732 let mut msg = Spdp::new(data(6), SpdpConfig::new(7, vec![])).announcement(Endianness::Big);
734 msg.submessages.insert(
735 0,
736 Submessage::InfoDestination(crate::submessage::InfoDestination {
737 guid_prefix: GuidPrefix([9; 12]),
738 }),
739 );
740 assert!(
741 a.handle_message(&msg.encode(Endianness::Big).unwrap(), t0)
742 .is_empty()
743 );
744 assert!(a.handle_message(b"RTPS", t0).is_empty());
746 }
747
748 #[test]
749 fn dispose_removes() {
750 let mut a = spdp(1);
751 let t0 = Instant::now();
752 let (m, _) = spdp(2).poll_announce(t0).unwrap();
753 assert_eq!(a.handle_message(&m, t0).len(), 1);
754
755 let mut msg = Message::new(Header::new(VendorId([1, 1]), GuidPrefix([2; 12])));
757 let mut qos = ParameterList::new();
758 qos.push(Parameter::new(pid::KEY_HASH, data(2).guid().to_bytes()));
759 qos.push(Parameter::new(pid::STATUS_INFO, [0, 0, 0, 3]));
760 msg.submessages.push(Submessage::Data(Data {
761 reader_id: EntityId::UNKNOWN,
762 writer_id: EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER,
763 writer_sn: SequenceNumber(2),
764 inline_qos: Some(qos),
765 serialized_payload: None,
766 non_standard_payload: false,
767 }));
768 let bytes = msg.encode(Endianness::Little).unwrap();
769 assert_eq!(
770 a.handle_message(&bytes, t0),
771 [ParticipantEvent::Removed(
772 GuidPrefix([2; 12]),
773 RemovalReason::Disposed
774 )]
775 );
776 assert_eq!(a.participants().count(), 0);
777 }
778
779 #[test]
780 fn our_dispose_removes() {
781 let mut a = spdp(1);
782 let mut b = spdp(2);
783 let t0 = Instant::now();
784 let (m, _) = b.poll_announce(t0).unwrap();
785 assert_eq!(a.handle_message(&m, t0).len(), 1);
786 let (bytes, _) = b.dispose();
787 assert_eq!(
788 a.handle_message(&bytes, t0),
789 [ParticipantEvent::Removed(
790 GuidPrefix([2; 12]),
791 RemovalReason::Disposed
792 )]
793 );
794 }
795
796 #[test]
797 fn secured_participants_change_only_through_the_secure_topic() {
798 use crate::spdp_secure::SecureParticipantEvent as S;
799 let mut a = spdp(1);
800 let mut b = spdp(2);
801 let t0 = Instant::now();
802 let (m, _) = b.poll_announce(t0).unwrap();
803 assert_eq!(a.handle_message(&m, t0).len(), 1);
804 assert_eq!(a.handle_secure(S::Data(Box::new(data(2))), t0), None);
806 let mut changed = data(2);
808 changed.user_data = vec![9];
809 b.set_local(changed.clone());
810 let t1 = t0 + StdDuration::from_secs(8);
811 let (m, _) = b.poll_announce(t1).unwrap();
812 assert!(a.handle_message(&m, t1).is_empty());
813 assert!(a.remove_expired(t0 + StdDuration::from_secs(11)).is_empty());
814 assert_eq!(a.participant(&GuidPrefix([2; 12])), Some(&data(2)));
815 let (bytes, _) = b.dispose();
817 assert!(a.handle_message(&bytes, t1).is_empty());
818 assert_eq!(
820 a.handle_secure(S::Data(Box::new(changed.clone())), t1),
821 Some(ParticipantEvent::Updated(changed))
822 );
823 assert_eq!(
824 a.handle_secure(S::Disposed(GuidPrefix([2; 12])), t1),
825 Some(ParticipantEvent::Removed(
826 GuidPrefix([2; 12]),
827 RemovalReason::Disposed
828 ))
829 );
830 assert_eq!(a.handle_secure(S::Data(Box::new(data(1))), t1), None);
832 let mut other = data(3);
833 other.domain_id = Some(8);
834 assert_eq!(a.handle_secure(S::Data(Box::new(other)), t1), None);
835 }
836
837 #[test]
838 fn infinite_lease_never_expires() {
839 let mut a = spdp(1);
840 let mut d = data(2);
841 d.lease_duration = Duration::INFINITE;
842 let t0 = Instant::now();
843 let (m, _) = Spdp::new(d, SpdpConfig::new(7, vec![]))
844 .poll_announce(t0)
845 .unwrap();
846 assert_eq!(a.handle_message(&m, t0).len(), 1);
847 assert!(
848 a.remove_expired(t0 + StdDuration::from_secs(1_000_000))
849 .is_empty()
850 );
851 }
852}