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).into(),
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).into(),
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> {
406 let announce = self.next_announce.unwrap_or_else(Instant::now);
407 let expiry = self.remote.values().filter_map(|r| r.expires).min();
408 Some(expiry.map_or(announce, |e| e.min(announce)))
409 }
410
411 pub fn participants(&self) -> impl Iterator<Item = &ParticipantData> {
413 self.remote.values().map(|r| &r.data)
414 }
415
416 pub fn participant(&self, prefix: &GuidPrefix) -> Option<&ParticipantData> {
418 self.remote.get(prefix).map(|r| &r.data)
419 }
420
421 pub fn remove_expired(&mut self, now: Instant) -> Vec<ParticipantEvent> {
423 let gone: Vec<GuidPrefix> = self
424 .remote
425 .iter()
426 .filter(|(_, r)| r.expires.is_some_and(|t| t <= now))
427 .map(|(k, _)| *k)
428 .collect();
429 gone.into_iter()
430 .map(|k| {
431 self.remote.remove(&k);
432 self.secured.remove(&k);
433 ParticipantEvent::Removed(k, RemovalReason::LeaseExpired)
434 })
435 .collect()
436 }
437
438 pub fn handle_message(&mut self, bytes: &[u8], now: Instant) -> Vec<ParticipantEvent> {
446 let Ok((_, submessages)) = Message::parse(bytes) else {
447 return Vec::new();
448 };
449 let mut events = Vec::new();
450 let mut for_us = true;
451 for sub in submessages {
452 let Ok(sub) = sub else { break };
453 match sub {
454 Submessage::InfoDestination(d) => {
455 for_us = d.guid_prefix == GuidPrefix::UNKNOWN
456 || d.guid_prefix == self.local.guid_prefix;
457 }
458 Submessage::Data(d)
459 if for_us && d.writer_id == EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER =>
460 {
461 if let Some(e) = self.handle_data(&d, now) {
462 events.push(e);
463 }
464 }
465 _ => {}
466 }
467 }
468 events
469 }
470
471 fn handle_data(&mut self, d: &Data, now: Instant) -> Option<ParticipantEvent> {
472 let status = d
473 .inline_qos
474 .as_ref()
475 .and_then(|q| q.get(pid::STATUS_INFO))
476 .and_then(|p| p.value.get(3).copied())
477 .unwrap_or(0);
478 if status & (STATUS_DISPOSED | STATUS_UNREGISTERED) != 0 {
479 let prefix = self.disposed_key(d)?;
480 if self.secured.contains(&prefix) {
481 return None;
482 }
483 self.remote.remove(&prefix)?;
484 return Some(ParticipantEvent::Removed(prefix, RemovalReason::Disposed));
485 }
486 let payload = d.serialized_payload.as_ref()?;
487 if payload.kind != PayloadKind::Data {
488 return None;
489 }
490 let data = ParticipantData::from_payload(&payload.bytes).ok()?;
491 if data.guid_prefix == self.local.guid_prefix
492 || data.domain_id.is_some_and(|id| id != self.config.domain_id)
493 || data.domain_tag != self.local.domain_tag
494 {
495 return None;
496 }
497 if self.secured.contains(&data.guid_prefix) {
498 if let Some(r) = self.remote.get_mut(&data.guid_prefix) {
500 r.expires = r.data.lease_duration.to_std().map(|d| now + d);
501 }
502 return None;
503 }
504 self.update(data, now)
505 }
506
507 pub fn handle_secure(
512 &mut self,
513 event: crate::spdp_secure::SecureParticipantEvent,
514 now: Instant,
515 ) -> Option<ParticipantEvent> {
516 use crate::spdp_secure::SecureParticipantEvent as S;
517 match event {
518 S::Data(data) => {
519 let data = *data;
520 if data.guid_prefix == self.local.guid_prefix
521 || data.domain_id.is_some_and(|id| id != self.config.domain_id)
522 || data.domain_tag != self.local.domain_tag
523 {
524 return None;
525 }
526 self.secured.insert(data.guid_prefix);
527 self.update(data, now)
528 }
529 S::Disposed(prefix) => {
530 self.secured.remove(&prefix);
531 self.remote.remove(&prefix)?;
532 Some(ParticipantEvent::Removed(prefix, RemovalReason::Disposed))
533 }
534 }
535 }
536
537 fn update(&mut self, data: ParticipantData, now: Instant) -> Option<ParticipantEvent> {
539 let expires = data.lease_duration.to_std().map(|d| now + d);
540 match self.remote.entry(data.guid_prefix) {
541 Entry::Occupied(mut o) => {
542 let r = o.get_mut();
543 r.expires = expires;
544 if r.data == data {
545 None
546 } else {
547 r.data = data.clone();
548 Some(ParticipantEvent::Updated(data))
549 }
550 }
551 Entry::Vacant(v) => {
552 v.insert(Remote {
553 data: data.clone(),
554 expires,
555 });
556 self.next_announce = None;
559 Some(ParticipantEvent::Discovered(data))
560 }
561 }
562 }
563
564 fn disposed_key(&self, d: &Data) -> Option<GuidPrefix> {
569 if let Some(p) = &d.serialized_payload
570 && let Ok((list, e)) = decode_pl_payload(&p.bytes)
571 && let Some(g) = list.get(pid::PARTICIPANT_GUID)
572 {
573 return PlValues::new(e).guid(g).ok().map(|g| g.prefix);
574 }
575 let hash = d.inline_qos.as_ref()?.get(pid::KEY_HASH)?;
576 let mut prefix = [0u8; 12];
577 prefix.copy_from_slice(hash.value.get(..12)?);
578 Some(GuidPrefix(prefix))
579 }
580}
581
582#[cfg(test)]
583mod tests {
584 use super::*;
585 use crate::parameter::Parameter;
586 use std::time::Duration as StdDuration;
587
588 fn data(n: u8) -> ParticipantData {
589 let mut d = ParticipantData::new(GuidPrefix([n; 12]), VendorId([0x01, 0x99]));
590 d.domain_id = Some(7);
591 d.metatraffic_unicast_locators = vec![Locator::udpv4("10.0.0.1:9160".parse().unwrap())];
592 d.metatraffic_multicast_locators =
593 vec![Locator::udpv4("239.255.0.1:9150".parse().unwrap())];
594 d.default_unicast_locators = vec![Locator::udpv4("10.0.0.1:9161".parse().unwrap())];
595 d.lease_duration = Duration::from_secs(10);
596 d
597 }
598
599 fn spdp(n: u8) -> Spdp {
600 Spdp::new(data(n), SpdpConfig::new(7, vec![]))
601 }
602
603 #[test]
604 fn participant_data_round_trip() {
605 let mut d = data(1);
606 d.domain_tag = "tag".into();
607 d.expects_inline_qos = true;
608 d.manual_liveliness_count = Some(Count(3));
609 d.builtin_endpoint_qos = Some(1);
610 d.user_data = vec![1, 2, 3];
611 d.entity_name = Some("p".into());
612 d.default_multicast_locators = vec![Locator::udpv4("239.255.0.1:9151".parse().unwrap())];
613 for e in [Endianness::Big, Endianness::Little] {
614 assert_eq!(ParticipantData::from_payload(&d.to_payload(e)).unwrap(), d);
615 }
616 }
617
618 #[test]
619 fn participant_data_rules() {
620 let e = Endianness::Little;
621 let b = PlBuilder::new(e);
622 let l = ParameterList::new();
624 assert_eq!(
625 ParticipantData::from_parameter_list(&l, e),
626 Err(DecodeError::MissingParameter(pid::PARTICIPANT_GUID))
627 );
628 let mut l = ParameterList::new();
629 l.push(b.guid(pid::PARTICIPANT_GUID, data(2).guid()));
630 l.push(Parameter::new(ParameterId(0x0fff), [0; 4]));
633 l.push(Parameter::new(ParameterId(0xc001), [0; 4]));
634 let d = ParticipantData::from_parameter_list(&l, e).unwrap();
635 assert_eq!(d.guid_prefix, GuidPrefix([2; 12]));
636 assert_eq!(d.domain_id, None);
637 assert_eq!(d.lease_duration, ParticipantData::DEFAULT_LEASE_DURATION);
638 l.push(Parameter::new(ParameterId(0x4fff), [0; 4]));
640 assert_eq!(
641 ParticipantData::from_parameter_list(&l, e),
642 Err(DecodeError::MustUnderstand(ParameterId(0x4fff)))
643 );
644 }
645
646 use crate::parameter::ParameterId;
647
648 #[test]
649 fn announce_schedule() {
650 let mut s = spdp(1);
651 s.config.announce_locators = vec![Locator::udpv4("239.255.0.1:9150".parse().unwrap())];
652 let t0 = Instant::now();
653 assert!(s.next_deadline().unwrap() <= Instant::now());
655 let (bytes, to) = s.poll_announce(t0).unwrap();
656 assert_eq!(to.len(), 1);
657 let msg = Message::decode(&bytes).unwrap();
658 assert_eq!(msg.header.guid_prefix, GuidPrefix([1; 12]));
659 let Submessage::Data(d) = &msg.submessages[1] else {
660 panic!()
661 };
662 assert_eq!(d.reader_id, EntityId::UNKNOWN);
663 assert_eq!(d.writer_id, EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER);
664 assert_eq!(
665 ParticipantData::from_payload(&d.serialized_payload.as_ref().unwrap().bytes).unwrap(),
666 data(1)
667 );
668 assert!(s.poll_announce(t0 + StdDuration::from_secs(29)).is_none());
669 assert!(s.poll_announce(t0 + StdDuration::from_secs(30)).is_some());
670 assert_eq!(s.next_deadline(), Some(t0 + StdDuration::from_secs(60)));
671 }
672
673 #[test]
674 fn discover_update_and_expire() {
675 let mut a = spdp(1);
676 let mut b = spdp(2);
677 let t0 = Instant::now();
678 let (msg_b, _) = b.poll_announce(t0).unwrap();
679 let (_, _) = a.poll_announce(t0).unwrap();
680
681 let ev = a.handle_message(&msg_b, t0);
682 assert_eq!(ev, [ParticipantEvent::Discovered(data(2))]);
683 assert!(a.poll_announce(t0).is_some());
685 let t1 = t0 + StdDuration::from_secs(8);
687 assert!(a.handle_message(&msg_b, t1).is_empty());
688 assert!(a.remove_expired(t0 + StdDuration::from_secs(12)).is_empty());
689
690 let mut changed = data(2);
691 changed.user_data = vec![9];
692 b.set_local(changed.clone());
693 let (msg_b2, _) = b.poll_announce(t1).unwrap();
694 assert_eq!(
695 a.handle_message(&msg_b2, t1),
696 [ParticipantEvent::Updated(changed)]
697 );
698 assert_eq!(a.participants().count(), 1);
699
700 assert_eq!(
701 a.remove_expired(t1 + StdDuration::from_secs(10)),
702 [ParticipantEvent::Removed(
703 GuidPrefix([2; 12]),
704 RemovalReason::LeaseExpired
705 )]
706 );
707 assert_eq!(a.participants().count(), 0);
708 }
709
710 #[test]
711 fn ignored_announcements() {
712 let mut a = spdp(1);
713 let t0 = Instant::now();
714 let (own, _) = a.poll_announce(t0).unwrap();
716 assert!(a.handle_message(&own, t0).is_empty());
717 let mut other = data(3);
719 other.domain_id = Some(8);
720 let mut s = Spdp::new(other, SpdpConfig::new(8, vec![]));
721 let (m, _) = s.poll_announce(t0).unwrap();
722 assert!(a.handle_message(&m, t0).is_empty());
723 let mut other = data(4);
725 other.domain_tag = "x".into();
726 let mut s = Spdp::new(other, SpdpConfig::new(7, vec![]));
727 let (m, _) = s.poll_announce(t0).unwrap();
728 assert!(a.handle_message(&m, t0).is_empty());
729 let mut other = data(5);
731 other.domain_id = None;
732 let mut s = Spdp::new(other, SpdpConfig::new(7, vec![]));
733 let (m, _) = s.poll_announce(t0).unwrap();
734 assert_eq!(a.handle_message(&m, t0).len(), 1);
735 let mut msg = Spdp::new(data(6), SpdpConfig::new(7, vec![])).announcement(Endianness::Big);
737 msg.submessages.insert(
738 0,
739 Submessage::InfoDestination(crate::submessage::InfoDestination {
740 guid_prefix: GuidPrefix([9; 12]),
741 }),
742 );
743 assert!(
744 a.handle_message(&msg.encode(Endianness::Big).unwrap(), t0)
745 .is_empty()
746 );
747 assert!(a.handle_message(b"RTPS", t0).is_empty());
749 }
750
751 #[test]
752 fn dispose_removes() {
753 let mut a = spdp(1);
754 let t0 = Instant::now();
755 let (m, _) = spdp(2).poll_announce(t0).unwrap();
756 assert_eq!(a.handle_message(&m, t0).len(), 1);
757
758 let mut msg = Message::new(Header::new(VendorId([1, 1]), GuidPrefix([2; 12])));
760 let mut qos = ParameterList::new();
761 qos.push(Parameter::new(pid::KEY_HASH, data(2).guid().to_bytes()));
762 qos.push(Parameter::new(pid::STATUS_INFO, [0, 0, 0, 3]));
763 msg.submessages.push(Submessage::Data(Data {
764 reader_id: EntityId::UNKNOWN,
765 writer_id: EntityId::SPDP_BUILTIN_PARTICIPANT_ANNOUNCER,
766 writer_sn: SequenceNumber(2),
767 inline_qos: Some(qos),
768 serialized_payload: None,
769 non_standard_payload: false,
770 }));
771 let bytes = msg.encode(Endianness::Little).unwrap();
772 assert_eq!(
773 a.handle_message(&bytes, t0),
774 [ParticipantEvent::Removed(
775 GuidPrefix([2; 12]),
776 RemovalReason::Disposed
777 )]
778 );
779 assert_eq!(a.participants().count(), 0);
780 }
781
782 #[test]
783 fn our_dispose_removes() {
784 let mut a = spdp(1);
785 let mut b = spdp(2);
786 let t0 = Instant::now();
787 let (m, _) = b.poll_announce(t0).unwrap();
788 assert_eq!(a.handle_message(&m, t0).len(), 1);
789 let (bytes, _) = b.dispose();
790 assert_eq!(
791 a.handle_message(&bytes, t0),
792 [ParticipantEvent::Removed(
793 GuidPrefix([2; 12]),
794 RemovalReason::Disposed
795 )]
796 );
797 }
798
799 #[test]
800 fn secured_participants_change_only_through_the_secure_topic() {
801 use crate::spdp_secure::SecureParticipantEvent as S;
802 let mut a = spdp(1);
803 let mut b = spdp(2);
804 let t0 = Instant::now();
805 let (m, _) = b.poll_announce(t0).unwrap();
806 assert_eq!(a.handle_message(&m, t0).len(), 1);
807 assert_eq!(a.handle_secure(S::Data(Box::new(data(2))), t0), None);
809 let mut changed = data(2);
811 changed.user_data = vec![9];
812 b.set_local(changed.clone());
813 let t1 = t0 + StdDuration::from_secs(8);
814 let (m, _) = b.poll_announce(t1).unwrap();
815 assert!(a.handle_message(&m, t1).is_empty());
816 assert!(a.remove_expired(t0 + StdDuration::from_secs(11)).is_empty());
817 assert_eq!(a.participant(&GuidPrefix([2; 12])), Some(&data(2)));
818 let (bytes, _) = b.dispose();
820 assert!(a.handle_message(&bytes, t1).is_empty());
821 assert_eq!(
823 a.handle_secure(S::Data(Box::new(changed.clone())), t1),
824 Some(ParticipantEvent::Updated(changed))
825 );
826 assert_eq!(
827 a.handle_secure(S::Disposed(GuidPrefix([2; 12])), t1),
828 Some(ParticipantEvent::Removed(
829 GuidPrefix([2; 12]),
830 RemovalReason::Disposed
831 ))
832 );
833 assert_eq!(a.handle_secure(S::Data(Box::new(data(1))), t1), None);
835 let mut other = data(3);
836 other.domain_id = Some(8);
837 assert_eq!(a.handle_secure(S::Data(Box::new(other)), t1), None);
838 }
839
840 #[test]
841 fn infinite_lease_never_expires() {
842 let mut a = spdp(1);
843 let mut d = data(2);
844 d.lease_duration = Duration::INFINITE;
845 let t0 = Instant::now();
846 let (m, _) = Spdp::new(d, SpdpConfig::new(7, vec![]))
847 .poll_announce(t0)
848 .unwrap();
849 assert_eq!(a.handle_message(&m, t0).len(), 1);
850 assert!(
851 a.remove_expired(t0 + StdDuration::from_secs(1_000_000))
852 .is_empty()
853 );
854 }
855}