Skip to main content

rustorb_rtps/
spdp.rs

1//! The Simple Participant Discovery Protocol (DDSI-RTPS 2.5, 8.5.3, 9.6.2
2//! and 9.6.3).
3//!
4//! [`ParticipantData`] is `SPDPdiscoveredParticipantData` and its PL_CDR
5//! form. [`Spdp`] holds the built-in SPDP writer and reader of one
6//! participant without doing any I/O: the caller feeds it received
7//! messages and the time, sends what it asks to send, and gets back
8//! [`ParticipantEvent`]s.
9
10use 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/// `SPDPdiscoveredParticipantData` (Table 8.78).
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct ParticipantData {
28    /// The participant's GUID prefix (sent as `PID_PARTICIPANT_GUID`).
29    pub guid_prefix: GuidPrefix,
30    /// `domainId`. `None` when not sent, which means "the receiver's
31    /// domain" (Table 9.19).
32    pub domain_id: Option<u32>,
33    /// `domainTag`; empty by default.
34    pub domain_tag: String,
35    /// `protocolVersion`.
36    pub protocol_version: ProtocolVersion,
37    /// `vendorId`.
38    pub vendor_id: VendorId,
39    /// `expectsInlineQos`.
40    pub expects_inline_qos: bool,
41    /// `metatrafficUnicastLocatorList`.
42    pub metatraffic_unicast_locators: Vec<Locator>,
43    /// `metatrafficMulticastLocatorList`.
44    pub metatraffic_multicast_locators: Vec<Locator>,
45    /// `defaultUnicastLocatorList`.
46    pub default_unicast_locators: Vec<Locator>,
47    /// `defaultMulticastLocatorList`.
48    pub default_multicast_locators: Vec<Locator>,
49    /// `availableBuiltinEndpoints`.
50    pub available_builtin_endpoints: BuiltinEndpointSet,
51    /// `leaseDuration`; `{100, 0}` by default.
52    pub lease_duration: Duration,
53    /// `manualLivelinessCount`.
54    pub manual_liveliness_count: Option<Count>,
55    /// `builtinEndpointQos`.
56    pub builtin_endpoint_qos: Option<u32>,
57    /// `user_data` of the DDS participant QoS.
58    pub user_data: Vec<u8>,
59    /// `PID_ENTITY_NAME`, if any.
60    pub entity_name: Option<String>,
61    /// The parameters of DDS Security: tokens and security info.
62    pub security: SecurityParameters,
63}
64
65impl ParticipantData {
66    /// The default lease duration (Table 9.19).
67    pub const DEFAULT_LEASE_DURATION: Duration = Duration::from_secs(100);
68
69    /// Data with the given prefix and vendor, and defaults for the rest.
70    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    /// The participant's GUID.
96    pub fn guid(&self) -> Guid {
97        Guid::new(self.guid_prefix, EntityId::PARTICIPANT)
98    }
99
100    /// The parameter list. Values equal to their defaults are left out,
101    /// as is the separate guidPrefix (Table 9.17).
102    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    /// The serialized payload: `PL_CDR_*` header and parameter list.
162    pub fn to_payload(&self, endianness: Endianness) -> Vec<u8> {
163        encode_pl_payload(&self.to_parameter_list(endianness), endianness)
164    }
165
166    /// Reads the data from a parameter list.
167    ///
168    /// `PID_PARTICIPANT_GUID` is required. Unknown parameters are skipped,
169    /// except protocol-defined ones with the must-understand bit
170    /// (Table 9.6), which make the whole data invalid. Vendor-specific
171    /// parameters are always skipped, since this implementation has no
172    /// vendor-specific parameters of its own.
173    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    /// Reads the data from a serialized payload.
219    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/// Settings of [`Spdp`].
226#[derive(Clone, Debug)]
227pub struct SpdpConfig {
228    /// The domain id of the local participant.
229    pub domain_id: u32,
230    /// How often to announce (`resendPeriod`); 30 s by default
231    /// (9.6.2.4.2). It should be shorter than the lease duration.
232    pub announce_period: std::time::Duration,
233    /// Where to announce (`readerLocators`): by default the discovery
234    /// multicast locator (9.6.2.4.1).
235    pub announce_locators: Vec<Locator>,
236}
237
238impl SpdpConfig {
239    /// The defaults, announcing to `announce_locators`.
240    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/// Why a remote participant was removed.
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251pub enum RemovalReason {
252    /// Its lease duration passed without an announcement.
253    LeaseExpired,
254    /// It said it is going away (disposed or unregistered).
255    Disposed,
256}
257
258/// A change in the set of remote participants.
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub enum ParticipantEvent {
261    /// A participant was seen for the first time.
262    Discovered(ParticipantData),
263    /// A known participant announced different data.
264    Updated(ParticipantData),
265    /// A participant is gone.
266    Removed(GuidPrefix, RemovalReason),
267}
268
269#[derive(Debug)]
270struct Remote {
271    data: ParticipantData,
272    expires: Option<Instant>,
273}
274
275/// The SPDP built-in writer and reader of one participant.
276///
277/// The writer is a best-effort stateless writer with one change; it is
278/// resent every `announce_period` (8.5.3.1). The reader keeps the remote
279/// participants and drops those whose lease has passed (8.5.3.3.2).
280#[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    /// The authenticated participants whose data comes on
288    /// DCPSParticipantsSecure (DDS Security 1.2, 7.5.1.6).
289    secured: HashSet<GuidPrefix>,
290}
291
292/// `StatusInfo_t` flags (9.6.4.9).
293const STATUS_DISPOSED: u8 = 0x01;
294const STATUS_UNREGISTERED: u8 = 0x02;
295
296impl Spdp {
297    /// The SPDP endpoints of `local`. The first announcement is due at
298    /// once.
299    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    /// The local participant's data.
311    pub fn local(&self) -> &ParticipantData {
312        &self.local
313    }
314
315    /// Replaces the local data. It is announced at the next
316    /// [`Spdp::poll_announce`] with a new sequence number.
317    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    /// The announcement message: the header, INFO_TS and a DATA with the
324    /// local participant data, from the SPDP writer to any reader
325    /// (8.4.8.1.4: `DATA.readerId := ENTITYID_UNKNOWN`).
326    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    /// The message that tells the others that the local participant is
347    /// going away, and the locators to send it to: a DATA with
348    /// `PID_STATUS_INFO` disposed and unregistered, the key hash in-line
349    /// and the key, `PID_PARTICIPANT_GUID`, as the payload (9.6.3.2). It
350    /// takes the next sequence number.
351    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    /// If an announcement is due at `now`, returns the encoded message and
387    /// the locators to send it to, and schedules the next one.
388    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    /// The next time [`Spdp::poll_announce`] or [`Spdp::remove_expired`]
401    /// has something to do.
402    ///
403    /// An announcement that is due (the first one, or one to answer a new
404    /// participant) makes it now: the caller does not sleep first.
405    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    /// The remote participants currently known.
412    pub fn participants(&self) -> impl Iterator<Item = &ParticipantData> {
413        self.remote.values().map(|r| &r.data)
414    }
415
416    /// Looks up a remote participant.
417    pub fn participant(&self, prefix: &GuidPrefix) -> Option<&ParticipantData> {
418        self.remote.get(prefix).map(|r| &r.data)
419    }
420
421    /// Removes participants whose lease has passed.
422    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    /// Processes one received RTPS message and returns what changed.
439    ///
440    /// Only DATA from SPDP writers is looked at. Messages and submessages
441    /// that are invalid, data for another domain or domain tag, and the
442    /// local participant's own announcements are ignored. The receiver
443    /// state follows 8.3.4 as far as SPDP needs: INFO_DST to another
444    /// participant makes the DATA after it not for us.
445    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            // Only its liveliness is taken from SPDP.
499            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    /// Takes in what an authenticated participant sent on
508    /// DCPSParticipantsSecure (DDS Security 1.2, 7.5.1.6). From then on
509    /// its data and its deletion are only taken from there: what SPDP
510    /// says of it only keeps it alive.
511    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    /// Records the data of a remote participant.
538    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                // Answering a new participant at once shortens start-up
557                // (8.5.3.1, optional).
558                self.next_announce = None;
559                Some(ParticipantEvent::Discovered(data))
560            }
561        }
562    }
563
564    /// The participant a dispose or unregister refers to: from the
565    /// payload's `PID_PARTICIPANT_GUID` (9.6.3.2), or else from the
566    /// in-line `PID_KEY_HASH`, which for a GUID key is the GUID itself
567    /// (9.6.4.8 step 5.1).
568    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        // Missing GUID.
623        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        // Unknown and vendor-specific parameters are skipped, even with
631        // the must-understand bit when vendor-specific.
632        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        // An unknown protocol parameter that must be understood.
639        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        // The first announcement is due at once.
654        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        // A new participant makes the next announcement due at once.
684        assert!(a.poll_announce(t0).is_some());
685        // The same data again: no event, but the lease is renewed.
686        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        // Own announcement.
715        let (own, _) = a.poll_announce(t0).unwrap();
716        assert!(a.handle_message(&own, t0).is_empty());
717        // Another domain.
718        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        // Another domain tag.
724        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        // No domain id means "the receiver's domain".
730        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        // Addressed to another participant with INFO_DST.
736        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        // Garbage.
748        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        // A dispose carrying only the key hash in-line.
759        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        // The same data on the secure topic changes nothing.
808        assert_eq!(a.handle_secure(S::Data(Box::new(data(2))), t0), None);
809        // A change on SPDP is ignored; it only keeps the lease.
810        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        // So is a dispose.
819        let (bytes, _) = b.dispose();
820        assert!(a.handle_message(&bytes, t1).is_empty());
821        // Both are taken from the secure topic.
822        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        // Data of the local participant or another domain is ignored.
834        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}