Skip to main content

rustorb_dds/
participant.rs

1//! `DomainParticipant` and the thread that runs discovery and receives
2//! data for it.
3
4use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
5use std::io;
6use std::net::Ipv4Addr;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak};
9use std::thread::JoinHandle;
10use std::time::{Duration, Instant};
11
12use rustorb_rtps::frag::{Keep, Reassembler, ReassemblyLimits};
13use rustorb_rtps::pl::pid;
14use rustorb_rtps::qos::{DurabilityKind, LivelinessKind, ReliabilityKind};
15use rustorb_rtps::receiver::receive;
16use rustorb_rtps::reliable::{
17    Change, MatchedReader, ReaderConfig, ReliableReader, ReliableWriter, WriterConfig,
18};
19use rustorb_rtps::sedp::{EndpointData, Match, Sedp, SedpConfig, SedpEvent, match_endpoints};
20use rustorb_rtps::spdp::{ParticipantData, ParticipantEvent, Spdp, SpdpConfig};
21use rustorb_rtps::spdp_secure::SpdpSecure;
22use rustorb_rtps::typelookup::{TypeLookup, TypeLookupReplied};
23use rustorb_rtps::udp::{Channel, Datagram, Incoming as UdpIncoming, UdpConfig, UdpTransport};
24use rustorb_rtps::wlp::{self, Wlp};
25use rustorb_rtps::{
26    Endianness, EntityId, Guid, GuidPrefix, Locator, Parameter, ParameterList, PayloadKind,
27    SampleIdentity, SequenceNumber, SerializedPayload, Submessage, Time, VendorId,
28};
29use rustorb_typesupport::TopicType;
30use rustorb_xtypes::dynamic::{ContentFilter, DynamicData, DynamicType, DynamicTypeBuilderFactory};
31use rustorb_xtypes::type_object::{TypeIdentifier, TypeInformation};
32use rustorb_xtypes::typelookup::{
33    GetTypeDependenciesIn, GetTypesIn, TypeLookupCall, TypeLookupReturn,
34};
35use rustorb_xtypes::types::{DescribeType, TypeObjects};
36
37use crate::condition::Waker;
38use crate::error::{Error, Result};
39use crate::instance::{self, Incoming, InstanceHandle, ReaderHistory};
40use crate::listener::{
41    AnyDataReader, AnyDataWriter, DomainParticipantListener, PublisherEntity, PublisherListener,
42    SubscriberEntity, SubscriberListener, TopicListener,
43};
44use crate::persistent::{Record, Store};
45use crate::publisher::Publisher;
46use crate::qos::{DataReaderQos, DataWriterQos, History, PublisherQos, SubscriberQos};
47#[cfg(feature = "security")]
48use crate::security::{PeerEvent, Security, SecurityConfig};
49use crate::status::{
50    DeadlineMissedStatus, Deadlines, IncompatibleQosStatus, InconsistentTopicStatus,
51    LivelinessChangedStatus, LivelinessLostStatus, MatchedStatus, SampleLostStatus,
52    SampleRejectedStatus, StatusMask,
53};
54use crate::subscriber::Subscriber;
55use crate::topic::{ContentFilteredTopic, Topic};
56use crate::typed::{Dynamic, KeyOps, Typed};
57
58/// The vendor id sent in RTPS headers. rustorb has no vendor id from the
59/// OMG yet, so this is `VENDORID_UNKNOWN` (DDSI-RTPS 2.5, 8.3.3.1.3).
60pub const VENDOR_ID: VendorId = VendorId::UNKNOWN;
61
62/// Settings of a [`DomainParticipant`].
63#[derive(Clone, Debug)]
64pub struct ParticipantConfig {
65    /// The UDP settings: interfaces, port numbers, participant id.
66    pub udp: UdpConfig,
67    /// How often the participant announces itself (SPDP).
68    pub announce_period: Duration,
69    /// How long other participants keep this one without hearing from it
70    /// (SPDP lease duration).
71    pub lease_duration: Duration,
72    /// The timing of the user writers (HEARTBEAT period, NACK response
73    /// delay, message size; DDSI-RTPS 2.5, 8.4.7.1).
74    pub writer: WriterConfig,
75    /// The timing of the reliable user readers (HEARTBEAT response delay,
76    /// 8.4.10.1).
77    pub reader: ReaderConfig,
78    /// For testing: drop user-traffic datagrams received (DATA,
79    /// HEARTBEAT, GAP, ACKNACK) at random, one in `n` on average, as if
80    /// they were lost on the way. `None`, the default, drops nothing.
81    pub drop_one_in: Option<u32>,
82    /// USER_DATA of the participant (DDS 1.4, 2.2.3.1): octets announced
83    /// to the other participants with SPDP. Empty by default. ROS 2
84    /// announces `enclave=/;` here.
85    pub user_data: Vec<u8>,
86    /// Whether to exchange messages with the participants of rustorb-dds
87    /// on this host through shared memory rather than UDP (feature `shm`;
88    /// true by default). Others are reached by UDP either way.
89    pub shared_memory: bool,
90    /// The directory of the files in which PERSISTENT writers keep their
91    /// samples. `None`, the default, is the `RUSTORB_DDS_PERSISTENCE_DIR`
92    /// environment variable when it is set, and otherwise
93    /// `rustorb-dds-persistent` in the current directory. The property
94    /// [`Self::PERSISTENCE_DIRECTORY`] sets it too.
95    pub persistence_directory: Option<std::path::PathBuf>,
96    /// DDS Security (feature `security`): the participant's identity,
97    /// governance and permissions. `None`, the default, joins without
98    /// security.
99    #[cfg(feature = "security")]
100    pub security: Option<SecurityConfig>,
101}
102
103impl ParticipantConfig {
104    /// The defaults for a domain: the system's interfaces, the default
105    /// ports, an announcement every 3 s and a lease of 20 s.
106    ///
107    /// The announcement period is shorter than SPDP's suggested 30 s so
108    /// that participants find each other quickly in a small domain.
109    /// Writers send a HEARTBEAT every 200 ms while some reliable reader
110    /// has not acknowledged everything.
111    pub fn new(domain_id: u32) -> Self {
112        ParticipantConfig {
113            udp: UdpConfig::new(domain_id),
114            announce_period: Duration::from_secs(3),
115            lease_duration: Duration::from_secs(20),
116            writer: WriterConfig {
117                heartbeat_period: Duration::from_millis(200),
118                ..WriterConfig::default()
119            },
120            reader: ReaderConfig::default(),
121            drop_one_in: None,
122            user_data: Vec::new(),
123            shared_memory: true,
124            persistence_directory: None,
125            #[cfg(feature = "security")]
126            security: None,
127        }
128    }
129
130    /// The property that sets [`Self::persistence_directory`].
131    pub const PERSISTENCE_DIRECTORY: &'static str = "rustorb.dds.persistence.directory";
132
133    /// The directory of the files of PERSISTENT writers, as
134    /// [`Self::persistence_directory`] says.
135    pub fn effective_persistence_directory(&self) -> std::path::PathBuf {
136        self.persistence_directory
137            .clone()
138            .or_else(|| std::env::var_os("RUSTORB_DDS_PERSISTENCE_DIR").map(Into::into))
139            .unwrap_or_else(|| "rustorb-dds-persistent".into())
140    }
141
142    /// Only this host: every socket on the loopback interface.
143    pub fn localhost(domain_id: u32) -> Self {
144        let mut c = Self::new(domain_id);
145        c.udp.interfaces = vec![Ipv4Addr::LOCALHOST];
146        c
147    }
148
149    /// Takes the PROPERTY of a DomainParticipantQos (DDS Security 1.2,
150    /// 7.2.5), as the bindings for other languages give it: the
151    /// `dds.sec.*` properties turn on DDS Security with the builtin
152    /// plugins (`SecurityConfig::from_properties`);
153    /// [`Self::PERSISTENCE_DIRECTORY`] sets
154    /// [`Self::persistence_directory`]; the others are ignored.
155    ///
156    /// Fails with [`Error::Security`] when some but not all of the
157    /// `dds.sec.auth.*` and `dds.sec.access.*` properties are given, and
158    /// with [`Error::Unsupported`] when there are `dds.sec.*` properties
159    /// and the feature `security` is off.
160    #[cfg_attr(not(feature = "security"), allow(unused_mut))]
161    pub fn set_properties<'a>(
162        &mut self,
163        properties: impl IntoIterator<Item = (&'a str, &'a str)>,
164    ) -> Result<()> {
165        let mut sec: Vec<(&str, &str)> = Vec::new();
166        for (n, v) in properties {
167            if n.starts_with("dds.sec.") || n.starts_with("rustorb.dds.sec.") {
168                sec.push((n, v));
169            } else if n == Self::PERSISTENCE_DIRECTORY {
170                self.persistence_directory = Some(v.into());
171            }
172        }
173        if sec.is_empty() {
174            return Ok(());
175        }
176        #[cfg(feature = "security")]
177        {
178            self.security =
179                Some(SecurityConfig::try_from_properties(sec).map_err(Error::Security)?);
180            Ok(())
181        }
182        #[cfg(not(feature = "security"))]
183        Err(Error::Unsupported(
184            "DDS Security: rustorb-dds was built without the feature `security`",
185        ))
186    }
187}
188
189/// A status change of a reader, with the status, for its listener.
190pub(crate) enum ReaderEvent {
191    DataAvailable,
192    SubscriptionMatched(MatchedStatus),
193    LivelinessChanged(LivelinessChangedStatus),
194    RequestedDeadlineMissed(DeadlineMissedStatus),
195    RequestedIncompatibleQos(IncompatibleQosStatus),
196    SampleRejected(SampleRejectedStatus),
197    SampleLost(SampleLostStatus),
198}
199
200/// A status change of a writer, with the status, for its listener.
201pub(crate) enum WriterEvent {
202    PublicationMatched(MatchedStatus),
203    LivelinessLost(LivelinessLostStatus),
204    OfferedDeadlineMissed(DeadlineMissedStatus),
205    OfferedIncompatibleQos(IncompatibleQosStatus),
206}
207
208/// A reader's listener, with its type erased: it is given the reader's
209/// participant and GUID to make a handle of the right type.
210pub(crate) type ReaderListener = Arc<dyn Fn(&Arc<Shared>, Guid, ReaderEvent) + Send + Sync>;
211/// A writer's listener, with its type erased.
212pub(crate) type WriterListener = Arc<dyn Fn(&Arc<Shared>, Guid, WriterEvent) + Send + Sync>;
213
214/// A listener call that [`Shared::flush`] makes after unlocking.
215type ListenerCall = Box<dyn FnOnce(&Arc<Shared>)>;
216
217/// Hands a writer's status change to the listener of its publisher or
218/// participant.
219fn writer_event<L: PublisherListener + ?Sized>(
220    l: &L,
221    shared: &Arc<Shared>,
222    guid: Guid,
223    ev: WriterEvent,
224) {
225    let w = AnyDataWriter {
226        shared: shared.clone(),
227        guid,
228    };
229    match ev {
230        WriterEvent::PublicationMatched(s) => l.on_publication_matched(&w, s),
231        WriterEvent::LivelinessLost(s) => l.on_liveliness_lost(&w, s),
232        WriterEvent::OfferedDeadlineMissed(s) => l.on_offered_deadline_missed(&w, s),
233        WriterEvent::OfferedIncompatibleQos(s) => l.on_offered_incompatible_qos(&w, s),
234    }
235}
236
237/// Calls `on_data_on_readers` of the listener of a subscriber or
238/// participant.
239fn data_on_readers<L: SubscriberListener + ?Sized>(
240    l: &L,
241    shared: &Arc<Shared>,
242    sub: Arc<SubscriberEntity>,
243) {
244    l.on_data_on_readers(&Subscriber::from_entity(shared.clone(), sub));
245}
246
247/// Hands a reader's status change to the listener of its subscriber or
248/// participant.
249fn reader_event<L: SubscriberListener + ?Sized>(
250    l: &L,
251    shared: &Arc<Shared>,
252    guid: Guid,
253    ev: ReaderEvent,
254) {
255    let r = AnyDataReader {
256        shared: shared.clone(),
257        guid,
258    };
259    match ev {
260        ReaderEvent::DataAvailable => l.on_data_available(&r),
261        ReaderEvent::SubscriptionMatched(s) => l.on_subscription_matched(&r, s),
262        ReaderEvent::LivelinessChanged(s) => l.on_liveliness_changed(&r, s),
263        ReaderEvent::RequestedDeadlineMissed(s) => l.on_requested_deadline_missed(&r, s),
264        ReaderEvent::RequestedIncompatibleQos(s) => l.on_requested_incompatible_qos(&r, s),
265        ReaderEvent::SampleRejected(s) => l.on_sample_rejected(&r, s),
266        ReaderEvent::SampleLost(s) => l.on_sample_lost(&r, s),
267    }
268}
269
270/// `StatusInfo_t` flags (DDSI-RTPS 2.5, 9.6.4.9).
271const STATUS_DISPOSED: u8 = 0x01;
272const STATUS_UNREGISTERED: u8 = 0x02;
273
274pub(crate) struct ReaderState {
275    pub(crate) data: EndpointData,
276    /// The reliable protocol state, for a RELIABLE reader: it orders the
277    /// changes of each remote writer and asks for what is missing.
278    pub(crate) rtps: Option<ReliableReader>,
279    /// Matched writers, local and remote.
280    pub(crate) matched: BTreeSet<Guid>,
281    /// For a BEST_EFFORT reader, the changes of each remote writer that
282    /// came as DATA_FRAG and are not all in yet (a RELIABLE reader keeps
283    /// them in `rtps`).
284    pub(crate) fragments: HashMap<Guid, Reassembler>,
285    pub(crate) reassembly: ReassemblyLimits,
286    /// REQUESTED_INCOMPATIBLE_QOS.
287    pub(crate) incompatible: IncompatibleQosStatus,
288    /// The liveliness of the matched writers.
289    pub(crate) liveliness: HashMap<Guid, WriterLiveliness>,
290    /// LIVELINESS_CHANGED.
291    pub(crate) liveliness_changed: LivelinessChangedStatus,
292    /// DEADLINE: when each alive instance must next get a sample, and
293    /// REQUESTED_DEADLINE_MISSED.
294    pub(crate) deadlines: Deadlines,
295    /// The samples and the instances.
296    pub(crate) samples: ReaderHistory,
297    pub(crate) keys: Arc<dyn KeyOps>,
298    /// SUBSCRIPTION_MATCHED.
299    pub(crate) matched_status: MatchedStatus,
300    /// The statuses changed since they were last read or given to the
301    /// listener (the StatusChangedFlags, DDS 1.4, 2.2.4.2).
302    pub(crate) changes: StatusMask,
303    /// The statuses its StatusCondition is sensitive to.
304    pub(crate) enabled: StatusMask,
305    /// The listener and the statuses it is called for.
306    pub(crate) listener: Option<(ReaderListener, StatusMask)>,
307    /// The subscriber it was created by.
308    pub(crate) subscriber: Option<Arc<SubscriberEntity>>,
309    /// The filter of a reader of a content filtered topic: the samples
310    /// that do not pass it are dropped as they come.
311    pub(crate) filter: Option<ContentFilter>,
312    /// The security of the participant, when the reader's topic has its
313    /// payloads protected: to decode them.
314    #[cfg(feature = "security")]
315    pub(crate) payload_security: Option<Arc<Security>>,
316    /// The pools of the samples that writers of this host send by
317    /// reference, when shared memory is on.
318    #[cfg(feature = "shm")]
319    pub(crate) pools: Option<Arc<rustorb_rtps::shm::Pools>>,
320}
321
322/// What a reader knows of the liveliness of a matched writer.
323#[derive(Clone, Copy, Debug)]
324pub(crate) struct WriterLiveliness {
325    kind: LivelinessKind,
326    /// `None`: it cannot lose its liveliness (an infinite lease, or an
327    /// AUTOMATIC writer of the same participant).
328    lease: Option<Duration>,
329    last: Instant,
330    alive: bool,
331}
332
333impl ReaderState {
334    fn new(
335        data: EndpointData,
336        qos: &DataReaderQos,
337        keys: Arc<dyn KeyOps>,
338        config: &ReaderConfig,
339    ) -> Self {
340        let rtps = (qos.reliability.kind == ReliabilityKind::Reliable)
341            .then(|| ReliableReader::new(data.guid, VENDOR_ID, config.clone()));
342        ReaderState {
343            data,
344            rtps,
345            matched: BTreeSet::new(),
346            fragments: HashMap::new(),
347            reassembly: config.reassembly,
348            incompatible: IncompatibleQosStatus::default(),
349            liveliness: HashMap::new(),
350            liveliness_changed: LivelinessChangedStatus::default(),
351            deadlines: Deadlines::new(qos.deadline),
352            samples: ReaderHistory::with_limits(qos.history, qos.resource_limits),
353            keys,
354            matched_status: MatchedStatus::default(),
355            changes: StatusMask::NONE,
356            enabled: StatusMask::ALL,
357            listener: None,
358            subscriber: None,
359            filter: None,
360            #[cfg(feature = "security")]
361            payload_security: None,
362            #[cfg(feature = "shm")]
363            pools: None,
364        }
365    }
366
367    /// Takes a change in; returns the statuses it changed:
368    /// DATA_AVAILABLE when a sample was added, SAMPLE_REJECTED and
369    /// SAMPLE_LOST.
370    fn accept(&mut self, c: Incoming) -> StatusMask {
371        if !self.matched.contains(&c.writer) {
372            return StatusMask::NONE;
373        }
374        if let (Some(f), instance::Change::Write(bytes)) = (&self.filter, &c.change) {
375            // A sample that cannot be read cannot pass the filter.
376            let passes =
377                DynamicData::from_payload(f.get_type(), bytes).is_ok_and(|d| f.evaluate(&d));
378            if !passes {
379                return StatusMask::NONE;
380            }
381        }
382        let h = c.instance;
383        let value = matches!(c.change, instance::Change::Write(_));
384        let rejected = self.samples.rejected_count();
385        let lost = self.samples.lost.total_count;
386        let mut changes = StatusMask::NONE;
387        if self.samples.accept(c) {
388            changes |= StatusMask::DATA_AVAILABLE;
389            if value {
390                self.deadlines.renew(h, Instant::now());
391            }
392        }
393        if self.samples.rejected_count() != rejected {
394            changes |= StatusMask::SAMPLE_REJECTED;
395        }
396        if self.samples.lost.total_count != lost {
397            changes |= StatusMask::SAMPLE_LOST;
398        }
399        changes
400    }
401
402    /// Matches a writer; returns whether it was not matched before.
403    fn add_match(&mut self, writer: Guid) -> bool {
404        let new = self.matched.insert(writer);
405        if new {
406            self.matched_status.matched(writer);
407        }
408        new
409    }
410
411    /// Unmatches a writer; returns whether it was matched.
412    fn remove_match(&mut self, writer: &Guid) -> bool {
413        let was = self.matched.remove(writer);
414        if was {
415            self.matched_status.unmatched(*writer);
416        }
417        was
418    }
419
420    /// A matched writer is gone (deleted, or unmatched): it is
421    /// unmatched, and its instances lose it. Returns the statuses
422    /// changed.
423    fn writer_removed(&mut self, writer: &Guid) -> StatusMask {
424        let mut k = StatusMask::NONE;
425        if self.writer_unmatched(writer) {
426            k |= StatusMask::LIVELINESS_CHANGED;
427        }
428        if self.remove_match(writer) {
429            k |= StatusMask::SUBSCRIPTION_MATCHED;
430            if self.samples.writer_gone(writer) {
431                k |= StatusMask::DATA_AVAILABLE;
432            }
433        }
434        k
435    }
436
437    /// The status of kind `k`, for the listener: reading it resets its
438    /// changes. `None` for a kind a reader does not have.
439    fn take_event(&mut self, k: StatusMask) -> Option<ReaderEvent> {
440        Some(match k {
441            StatusMask::DATA_AVAILABLE => ReaderEvent::DataAvailable,
442            StatusMask::SUBSCRIPTION_MATCHED => {
443                ReaderEvent::SubscriptionMatched(self.matched_status.take())
444            }
445            StatusMask::LIVELINESS_CHANGED => {
446                ReaderEvent::LivelinessChanged(self.liveliness_changed.take())
447            }
448            StatusMask::REQUESTED_DEADLINE_MISSED => {
449                ReaderEvent::RequestedDeadlineMissed(self.deadlines.missed.take())
450            }
451            StatusMask::REQUESTED_INCOMPATIBLE_QOS => {
452                ReaderEvent::RequestedIncompatibleQos(self.incompatible.take())
453            }
454            StatusMask::SAMPLE_REJECTED => {
455                ReaderEvent::SampleRejected(self.samples.take_rejected_status())
456            }
457            StatusMask::SAMPLE_LOST => ReaderEvent::SampleLost(self.samples.lost.take()),
458            _ => return None,
459        })
460    }
461
462    /// Starts tracking the liveliness of a newly matched writer: it is
463    /// alive.
464    fn writer_matched(
465        &mut self,
466        writer: Guid,
467        kind: LivelinessKind,
468        lease: Option<Duration>,
469        now: Instant,
470    ) -> bool {
471        let l = WriterLiveliness {
472            kind,
473            lease,
474            last: now,
475            alive: true,
476        };
477        if self.liveliness.insert(writer, l).is_none() {
478            self.liveliness_changed.update(writer, None, Some(true));
479            return true;
480        }
481        false
482    }
483
484    /// Stops tracking a writer that is no longer matched; returns whether
485    /// LIVELINESS_CHANGED changed.
486    fn writer_unmatched(&mut self, writer: &Guid) -> bool {
487        match self.liveliness.remove(writer) {
488            Some(l) => {
489                self.liveliness_changed.update(*writer, Some(l.alive), None);
490                true
491            }
492            None => false,
493        }
494    }
495
496    /// A matched writer asserted its liveliness; returns whether it was
497    /// not alive.
498    fn writer_asserted(&mut self, writer: &Guid, now: Instant) -> bool {
499        if let Some(l) = self.liveliness.get_mut(writer) {
500            l.last = now;
501            if !l.alive {
502                l.alive = true;
503                self.liveliness_changed
504                    .update(*writer, Some(false), Some(true));
505                return true;
506            }
507        }
508        false
509    }
510
511    /// Writers whose lease passed become not alive, and the instances
512    /// they alone wrote lose their writers; deadlines missed are counted.
513    /// Returns the statuses changed.
514    fn check(&mut self, now: Instant) -> StatusMask {
515        let mut changes = StatusMask::NONE;
516        let lost: Vec<Guid> = self
517            .liveliness
518            .iter()
519            .filter(|(_, l)| l.alive && l.lease.is_some_and(|d| now > l.last + d))
520            .map(|(g, _)| *g)
521            .collect();
522        for g in lost {
523            self.liveliness.get_mut(&g).expect("listed above").alive = false;
524            self.liveliness_changed.update(g, Some(true), Some(false));
525            changes |= StatusMask::LIVELINESS_CHANGED;
526            if self.samples.writer_lost(&g) {
527                changes |= StatusMask::DATA_AVAILABLE;
528            }
529        }
530        let samples = &self.samples;
531        if self.deadlines.check(now, |h| samples.is_alive(h)) {
532            changes |= StatusMask::REQUESTED_DEADLINE_MISSED;
533        }
534        changes
535    }
536
537    /// Reads a change received from a remote writer: its instance from
538    /// the in-line key hash, or else from the value or the key payload,
539    /// and what it does to the instance. `None` when it cannot be placed.
540    fn incoming(&self, c: Change) -> Option<Incoming> {
541        let mut key_hash = None;
542        let mut status = 0u8;
543        let mut related_sample_identity = None;
544        if let Some(q) = &c.inline_qos {
545            for p in &q.parameters {
546                if p.id == pid::RELATED_SAMPLE_IDENTITY {
547                    related_sample_identity = SampleIdentity::from_bytes(
548                        &p.value,
549                        q.endianness().unwrap_or(Endianness::NATIVE),
550                    )
551                    .ok();
552                } else if p.id == pid::KEY_HASH && p.value.len() >= 16 {
553                    key_hash = Some(InstanceHandle(p.value[..16].try_into().expect("16 octets")));
554                } else if p.id == pid::STATUS_INFO && p.value.len() >= 4 {
555                    // An octet array: the flags are in the last octet.
556                    status = p.value[3];
557                }
558            }
559        }
560        let lifecycle = status & (STATUS_DISPOSED | STATUS_UNREGISTERED) != 0;
561        #[allow(unused_mut)]
562        let mut payload = c.payload;
563        #[cfg(feature = "security")]
564        if let (Some(sec), Some(p)) = (&self.payload_security, payload.as_mut()) {
565            p.bytes = sec.decode_payload(&c.writer, &p.bytes)?;
566        }
567        if let Some(p) = payload.as_mut() {
568            drop_missing_padding(&mut p.bytes);
569        }
570        let change = if lifecycle {
571            instance::Change::Lifecycle {
572                disposed: status & STATUS_DISPOSED != 0,
573                unregistered: status & STATUS_UNREGISTERED != 0,
574            }
575        } else {
576            match &payload {
577                #[cfg(feature = "shm")]
578                Some(p)
579                    if p.kind == PayloadKind::Data && rustorb_rtps::shm::is_reference(&p.bytes) =>
580                {
581                    // A sample in a writer's pool: unreadable once the
582                    // pool is gone.
583                    instance::Change::Write(instance::Payload::Loaned(
584                        self.pools.as_ref()?.resolve(&p.bytes)?,
585                    ))
586                }
587                Some(p) if p.kind == PayloadKind::Data => {
588                    instance::Change::Write(instance::Payload::Owned(p.bytes.clone()))
589                }
590                _ => return None,
591            }
592        };
593        let instance = if !self.keys.keyed() {
594            InstanceHandle::KEYLESS
595        } else if let Some(h) = key_hash {
596            h
597        } else {
598            match (&change, &payload) {
599                (instance::Change::Write(v), _) => self.keys.instance_of_value(v)?,
600                (_, Some(p)) => self
601                    .samples
602                    .last_values()
603                    .find(|(_, v)| self.keys.key_matches(&p.bytes, v))
604                    .map(|(h, _)| h)?,
605                _ => return None,
606            }
607        };
608        Some(Incoming {
609            writer: c.writer,
610            sequence_number: c.sequence_number,
611            source_timestamp: c.timestamp,
612            related_sample_identity,
613            instance,
614            change,
615        })
616    }
617}
618
619/// Clears the padding count of an encapsulation (DDS-XTypes 1.3,
620/// 7.6.3.1.2: the last two bits of the options) when the payload does not
621/// have the octets it counts. OpenDDS 3.31 counts the octets that pad its
622/// data to a multiple of 4, but leaves them out of a DATA that ends the
623/// message; read as counted, the data would lose its last octets.
624fn drop_missing_padding(bytes: &mut [u8]) {
625    if bytes.len() > 4 && bytes[3] & 3 != 0 && !(bytes.len() - 4).is_multiple_of(4) {
626        bytes[3] &= !3;
627    }
628}
629
630/// How many of the newest samples a writer sent by reference it holds on
631/// to after they leave its history, for the readers that have yet to
632/// take them up (a best-effort writer's history keeps none).
633#[cfg(feature = "shm")]
634const LOANS_KEPT: usize = 8;
635
636/// The most slots of a writer's pool.
637#[cfg(feature = "shm")]
638const MAX_POOL_SLOTS: usize = 256;
639
640/// The vendor id that OpenDDS sends.
641const OPENDDS: VendorId = VendorId([0x01, 0x03]);
642
643/// An instance a writer has registered.
644#[derive(Debug)]
645pub(crate) struct WriterInstance {
646    /// Its changes still in the history, oldest first.
647    changes: VecDeque<SequenceNumber>,
648    /// Its key payload (the key holder in XCDR1, `CDR_LE`), from the
649    /// first value written, for the readers that need one with a
650    /// dispose or an unregister.
651    key: Option<Vec<u8>>,
652}
653
654/// What a writer does to an instance.
655#[derive(Debug)]
656pub(crate) enum WriteOp {
657    /// `write`: a value payload, and the sample it answers (sent in-line
658    /// as `PID_RELATED_SAMPLE_IDENTITY`).
659    /// The third is the only reader to send it to, if any.
660    Value(instance::Payload, Option<SampleIdentity>, Option<Guid>),
661    /// `dispose` and/or `unregister_instance`.
662    Lifecycle { dispose: bool, unregister: bool },
663}
664
665pub(crate) struct WriterState {
666    pub(crate) data: EndpointData,
667    pub(crate) qos: DataWriterQos,
668    keyed: bool,
669    /// The topic type's key operations.
670    keys: Arc<dyn KeyOps>,
671    /// The history and the remote readers. Local readers get each sample
672    /// directly when it is written.
673    pub(crate) rtps: ReliableWriter,
674    /// Matched readers, local and remote.
675    pub(crate) matched: BTreeSet<Guid>,
676    /// The registered instances.
677    pub(crate) instances: BTreeMap<InstanceHandle, WriterInstance>,
678    /// The instance of each change in the history.
679    change_instance: HashMap<SequenceNumber, InstanceHandle>,
680    /// OFFERED_INCOMPATIBLE_QOS.
681    pub(crate) incompatible: IncompatibleQosStatus,
682    /// When it last asserted its liveliness.
683    last_asserted: Instant,
684    /// Whether its liveliness is not lost.
685    alive: bool,
686    /// LIVELINESS_LOST.
687    pub(crate) liveliness_lost: LivelinessLostStatus,
688    /// DEADLINE: when each registered instance must next be written, and
689    /// OFFERED_DEADLINE_MISSED.
690    pub(crate) deadlines: Deadlines,
691    /// PUBLICATION_MATCHED.
692    pub(crate) matched_status: MatchedStatus,
693    /// The statuses changed since they were last read or given to the
694    /// listener.
695    pub(crate) changes: StatusMask,
696    /// The statuses its StatusCondition is sensitive to.
697    pub(crate) enabled: StatusMask,
698    /// The listener and the statuses it is called for.
699    pub(crate) listener: Option<(WriterListener, StatusMask)>,
700    /// The publisher it was created by.
701    pub(crate) publisher: Option<Arc<PublisherEntity>>,
702    /// Encodes the payloads, when the topic has them protected.
703    #[cfg(feature = "security")]
704    pub(crate) payload_encoder: Option<Arc<rustorb_dds_security::crypto::Encoder>>,
705    /// The instances whose last change is a dispose.
706    disposed: BTreeSet<InstanceHandle>,
707    /// Whether the writer was deleted, and the participant keeps it for
708    /// its TRANSIENT or PERSISTENT samples.
709    orphan: bool,
710    /// When an orphan writer drops the instances it disposed
711    /// (`service_cleanup_delay`).
712    cleanup_at: Option<Instant>,
713    /// The file of a PERSISTENT writer.
714    store: Option<Store>,
715    /// The pool of the samples it loans, once one is loaned.
716    #[cfg(feature = "shm")]
717    pool: Option<Arc<rustorb_rtps::shm::Pool>>,
718    /// The loaned samples sent by reference, oldest first: each is held
719    /// while its change is in the history, or is among the newest
720    /// [`LOANS_KEPT`] (for the readers that have yet to take it up).
721    #[cfg(feature = "shm")]
722    loans: VecDeque<(SequenceNumber, rustorb_rtps::shm::PoolLoan)>,
723    /// The changes in the history as the file keeps them, for a
724    /// PERSISTENT writer.
725    persisted: BTreeMap<SequenceNumber, Record>,
726    /// Whether the changes added are taken up from the file, not new.
727    restoring: bool,
728}
729
730impl WriterState {
731    /// Matches a reader; returns whether it was not matched before.
732    fn add_match(&mut self, reader: Guid) -> bool {
733        let new = self.matched.insert(reader);
734        if new {
735            self.matched_status.matched(reader);
736        }
737        new
738    }
739
740    /// Unmatches a reader; returns whether it was matched.
741    fn remove_match(&mut self, reader: &Guid) -> bool {
742        let was = self.matched.remove(reader);
743        if was {
744            self.matched_status.unmatched(*reader);
745        }
746        was
747    }
748
749    /// The status of kind `k`, for the listener: reading it resets its
750    /// changes.
751    fn take_event(&mut self, k: StatusMask) -> Option<WriterEvent> {
752        Some(match k {
753            StatusMask::PUBLICATION_MATCHED => {
754                WriterEvent::PublicationMatched(self.matched_status.take())
755            }
756            StatusMask::LIVELINESS_LOST => WriterEvent::LivelinessLost(self.liveliness_lost.take()),
757            StatusMask::OFFERED_DEADLINE_MISSED => {
758                WriterEvent::OfferedDeadlineMissed(self.deadlines.missed.take())
759            }
760            StatusMask::OFFERED_INCOMPATIBLE_QOS => {
761                WriterEvent::OfferedIncompatibleQos(self.incompatible.take())
762            }
763            _ => return None,
764        })
765    }
766
767    /// The lease within which a reader takes the writer as alive, as a
768    /// local reader sees it: an AUTOMATIC writer of the same participant
769    /// is always alive.
770    fn local_lease(&self) -> Option<Duration> {
771        match self.qos.liveliness.kind {
772            LivelinessKind::Automatic => None,
773            _ => self.qos.liveliness.lease_duration,
774        }
775    }
776
777    /// The liveliness of the writer is lost when its lease passes without
778    /// an assertion; deadlines missed are counted. Returns the statuses
779    /// changed.
780    fn check(&mut self, now: Instant) -> StatusMask {
781        let mut changes = StatusMask::NONE;
782        if let Some(lease) = self.local_lease()
783            && self.alive
784            && now > self.last_asserted + lease
785        {
786            self.alive = false;
787            self.liveliness_lost.add();
788            changes |= StatusMask::LIVELINESS_LOST;
789        }
790        let instances = &self.instances;
791        if self.deadlines.check(now, |h| instances.contains_key(h)) {
792            changes |= StatusMask::OFFERED_DEADLINE_MISSED;
793        }
794        if self.cleanup_at.is_some_and(|t| now >= t) {
795            self.cleanup_at = None;
796            self.clean_up();
797        }
798        changes
799    }
800
801    /// Drops the changes of the instances disposed, past the
802    /// `service_cleanup_delay` of an orphan writer (DDS 1.4, 2.2.3.4).
803    fn clean_up(&mut self) {
804        let disposed = std::mem::take(&mut self.disposed);
805        let sns: Vec<SequenceNumber> = self
806            .change_instance
807            .iter()
808            .filter(|(_, h)| disposed.contains(h))
809            .map(|(sn, _)| *sn)
810            .collect();
811        for sn in sns {
812            self.rtps.remove_change(sn);
813        }
814        for h in &disposed {
815            self.instances.remove(h);
816        }
817        self.trim();
818    }
819
820    /// Leaves the writer, deleted, to the participant: it keeps the
821    /// samples that its DURABILITY_SERVICE allows, and goes on sending
822    /// them to the readers that match it.
823    fn orphan(&mut self, now: Instant) {
824        self.orphan = true;
825        self.listener = None;
826        self.publisher = None;
827        let ds = self.qos.durability_service;
828        self.qos.history = ds.history;
829        self.qos.resource_limits = ds.resource_limits;
830        self.deadlines = Deadlines::new(None);
831        // A delay too long for an `Instant` is never.
832        self.cleanup_at = now.checked_add(ds.service_cleanup_delay);
833        self.trim();
834    }
835
836    /// Takes up the changes kept in the file of a PERSISTENT writer.
837    fn restore(&mut self, records: Vec<Record>) {
838        self.restoring = true;
839        for r in records {
840            let op = match r.value {
841                Some(v) => WriteOp::Value(v.into(), None, None),
842                None => WriteOp::Lifecycle {
843                    dispose: r.dispose,
844                    unregister: r.unregister,
845                },
846            };
847            if self.add(r.instance, op, r.timestamp, false, false).is_ok() {
848                self.trim();
849            }
850        }
851        self.restoring = false;
852        self.compact();
853    }
854
855    /// Writes the file of a PERSISTENT writer anew from its history.
856    fn compact(&mut self) {
857        if let Some(store) = &mut self.store {
858            let _ = store.rewrite(self.persisted.values());
859        }
860    }
861
862    /// The changes of an instance still in the history.
863    fn instance_changes(&mut self, h: &InstanceHandle) -> usize {
864        let Some(i) = self.instances.get_mut(h) else {
865            return 0;
866        };
867        let rtps = &self.rtps;
868        i.changes.retain(|sn| rtps.contains(*sn));
869        i.changes.len()
870    }
871
872    /// Whether the history has no room for one more change of instance
873    /// `h`, so that a write must wait: a reliable KEEP_ALL writer at
874    /// `max_samples` or `max_samples_per_instance`.
875    fn is_full(&mut self, h: &InstanceHandle) -> bool {
876        if self.qos.reliability.kind != ReliabilityKind::Reliable
877            || self.qos.history != History::KeepAll
878        {
879            return false;
880        }
881        let limits = self.qos.resource_limits;
882        limits
883            .max_samples
884            .is_some_and(|m| self.rtps.len() >= m.max(1))
885            || limits
886                .max_samples_per_instance
887                .is_some_and(|m| self.instance_changes(h) >= m.max(1))
888    }
889
890    fn transient_local(&self) -> bool {
891        self.qos.durability >= DurabilityKind::TransientLocal
892    }
893
894    /// Drops what the history no longer needs: changes every reader has,
895    /// unless the writer is TRANSIENT_LOCAL and keeps them for later
896    /// readers, and those beyond the KEEP_LAST depth of their instance.
897    ///
898    /// An orphan writer also keeps to the RESOURCE_LIMITS of its
899    /// DURABILITY_SERVICE, dropping the oldest changes (and instances)
900    /// beyond them.
901    fn trim(&mut self) {
902        if !self.transient_local() {
903            self.rtps.remove_acknowledged();
904        }
905        let mut depth = match self.qos.history {
906            History::KeepLast(d) => Some(d.max(1)),
907            History::KeepAll => None,
908        };
909        let limits = self.orphan.then_some(self.qos.resource_limits);
910        if let Some(m) = limits.and_then(|l| l.max_samples_per_instance) {
911            depth = Some(depth.map_or(m, |d| d.min(m)).max(1));
912        }
913        if let Some(depth) = depth {
914            let handles: Vec<InstanceHandle> = self.instances.keys().copied().collect();
915            for h in handles {
916                while self.instance_changes(&h) > depth {
917                    let i = self.instances.get_mut(&h).expect("listed above");
918                    if let Some(sn) = i.changes.pop_front() {
919                        self.rtps.remove_change(sn);
920                    }
921                }
922            }
923        }
924        if let Some(m) = limits.and_then(|l| l.max_instances) {
925            while self.instances.len() > m {
926                // The instance changed longest ago.
927                let rtps = &self.rtps;
928                let Some(h) = self
929                    .instances
930                    .iter_mut()
931                    .map(|(h, i)| {
932                        i.changes.retain(|sn| rtps.contains(*sn));
933                        (*h, i.changes.back().copied())
934                    })
935                    .min_by_key(|(_, sn)| *sn)
936                    .map(|(h, _)| h)
937                else {
938                    break;
939                };
940                if let Some(i) = self.instances.remove(&h) {
941                    for sn in i.changes {
942                        self.rtps.remove_change(sn);
943                    }
944                }
945            }
946        }
947        if let Some(m) = limits.and_then(|l| l.max_samples) {
948            while self.rtps.len() > m.max(1) {
949                if self.rtps.remove_oldest().is_none() {
950                    break;
951                }
952            }
953        }
954        let rtps = &self.rtps;
955        self.change_instance.retain(|sn, _| rtps.contains(*sn));
956        #[cfg(feature = "shm")]
957        {
958            let old = self.loans.len().saturating_sub(LOANS_KEPT);
959            let mut i = 0;
960            self.loans.retain(|(sn, _)| {
961                i += 1;
962                i > old || rtps.contains(*sn)
963            });
964        }
965        if self.store.is_some() {
966            self.persisted.retain(|sn, _| rtps.contains(*sn));
967            let records = self.store.as_ref().map_or(0, Store::records);
968            if records > 2 * self.persisted.len() + 64 {
969                self.compact();
970            }
971        }
972    }
973
974    /// Registers an instance, if it is not already.
975    fn register(&mut self, h: InstanceHandle) -> Result<()> {
976        if self.instances.contains_key(&h) {
977            return Ok(());
978        }
979        if self
980            .qos
981            .resource_limits
982            .max_instances
983            .is_some_and(|m| self.instances.len() >= m)
984        {
985            return Err(Error::OutOfResources);
986        }
987        self.instances.insert(
988            h,
989            WriterInstance {
990                changes: VecDeque::new(),
991                key: None,
992            },
993        );
994        Ok(())
995    }
996
997    /// Adds a change for instance `h` to the history, registering the
998    /// instance or unregistering it as `op` says. Returns the change for
999    /// the local readers.
1000    ///
1001    /// A loaned sample goes by reference if `by_reference`, else copied.
1002    fn add(
1003        &mut self,
1004        h: InstanceHandle,
1005        op: WriteOp,
1006        timestamp: Time,
1007        key_payload: bool,
1008        #[allow(unused_variables)] by_reference: bool,
1009    ) -> Result<(SequenceNumber, instance::Change)> {
1010        let unregister = matches!(
1011            op,
1012            WriteOp::Lifecycle {
1013                unregister: true,
1014                ..
1015            }
1016        );
1017        if !self.instances.contains_key(&h) {
1018            if unregister {
1019                return Err(Error::PreconditionNotMet);
1020            }
1021            self.register(h)?;
1022        }
1023        let restoring = self.restoring;
1024        let record = self.store.as_mut().map(|store| {
1025            let (value, dispose) = match &op {
1026                WriteOp::Value(v, ..) => (Some(v.to_vec()), false),
1027                WriteOp::Lifecycle { dispose, .. } => (None, *dispose),
1028            };
1029            let r = Record {
1030                instance: h,
1031                timestamp,
1032                value,
1033                dispose,
1034                unregister,
1035            };
1036            if restoring {
1037                Ok(r)
1038            } else {
1039                store.append(&r).map(|()| r)
1040            }
1041        });
1042        let record = record.transpose()?;
1043        match &op {
1044            WriteOp::Value(..) => {
1045                self.disposed.remove(&h);
1046            }
1047            WriteOp::Lifecycle { dispose: true, .. } => {
1048                self.disposed.insert(h);
1049            }
1050            WriteOp::Lifecycle { .. } => {}
1051        }
1052        let mut q = ParameterList::new();
1053        if self.keyed {
1054            q.push(Parameter::new(pid::KEY_HASH, h.0));
1055        }
1056        let mut directed = None;
1057        #[cfg(feature = "shm")]
1058        let mut lent = None;
1059        let (payload, change) = match op {
1060            WriteOp::Value(v, related, to) => {
1061                directed = to;
1062                if self.keyed {
1063                    let inst = self.instances.get_mut(&h).expect("registered above");
1064                    if inst.key.is_none() {
1065                        inst.key = self.keys.key_payload(&v);
1066                    }
1067                }
1068                if let Some(id) = related {
1069                    // In the byte order the message is sent in.
1070                    q.push(Parameter::new(
1071                        pid::RELATED_SAMPLE_IDENTITY,
1072                        id.to_bytes(Endianness::NATIVE),
1073                    ));
1074                }
1075                #[cfg(feature = "shm")]
1076                if let instance::Payload::Loaned(l) = &v
1077                    && by_reference
1078                {
1079                    lent = Some(l.clone());
1080                }
1081                let bytes = || {
1082                    #[cfg(feature = "security")]
1083                    if let Some(e) = &self.payload_encoder {
1084                        return e.encode_payload(&v);
1085                    }
1086                    v.to_vec()
1087                };
1088                #[cfg(feature = "shm")]
1089                let bytes = match &lent {
1090                    Some(l) => l.reference(),
1091                    None => bytes(),
1092                };
1093                #[cfg(not(feature = "shm"))]
1094                let bytes = bytes();
1095                (
1096                    Some(SerializedPayload {
1097                        kind: PayloadKind::Data,
1098                        bytes,
1099                    }),
1100                    instance::Change::Write(v),
1101                )
1102            }
1103            WriteOp::Lifecycle {
1104                dispose,
1105                unregister,
1106            } => {
1107                let mut flags = 0;
1108                if dispose {
1109                    flags |= STATUS_DISPOSED;
1110                }
1111                if unregister {
1112                    flags |= STATUS_UNREGISTERED;
1113                }
1114                q.push(Parameter::new(pid::STATUS_INFO, [0, 0, 0, flags]));
1115                // The key hash tells the instance. Fast DDS 2.11.2 takes
1116                // the wrong instance for a DATA with a key payload, even
1117                // with the key hash inline, while Cyclone DDS 0.10.4
1118                // accepts either; OpenDDS 3.31 needs the key payload. So
1119                // it goes only when `key_payload` asks for it.
1120                let key = if key_payload && self.keyed {
1121                    self.instances.get(&h).and_then(|i| i.key.clone())
1122                } else {
1123                    None
1124                };
1125                (
1126                    key.map(|bytes| SerializedPayload {
1127                        kind: PayloadKind::Key,
1128                        bytes,
1129                    }),
1130                    instance::Change::Lifecycle {
1131                        disposed: dispose,
1132                        unregistered: unregister,
1133                    },
1134                )
1135            }
1136        };
1137        // Cyclone DDS 0.10 drops a DATA with in-line QoS but no key hash,
1138        // even on a keyless topic (whose key hash is zero): a keyless
1139        // writer sends it whenever it sends in-line QoS.
1140        if !self.keyed && !q.parameters.is_empty() {
1141            q.parameters.insert(0, Parameter::new(pid::KEY_HASH, h.0));
1142        }
1143        let inline_qos = (!q.parameters.is_empty()).then_some(q);
1144        if matches!(change, instance::Change::Write(_)) {
1145            self.deadlines.renew(h, Instant::now());
1146        } else {
1147            // Disposed or unregistered: no more updates are due.
1148            self.deadlines.remove(&h);
1149        }
1150        let sn = self
1151            .rtps
1152            .add_change_at(inline_qos, payload, Some(timestamp));
1153        if let Some(r) = directed {
1154            self.rtps.direct(sn, r);
1155        }
1156        self.change_instance.insert(sn, h);
1157        #[cfg(feature = "shm")]
1158        if let Some(l) = lent {
1159            self.loans.push_back((sn, l));
1160        }
1161        if let Some(r) = record {
1162            self.persisted.insert(sn, r);
1163        }
1164        if unregister {
1165            self.instances.remove(&h);
1166        } else {
1167            self.instances
1168                .get_mut(&h)
1169                .expect("registered above")
1170                .changes
1171                .push_back(sn);
1172        }
1173        Ok((sn, change))
1174    }
1175}
1176
1177pub(crate) struct Inner {
1178    spdp: Spdp,
1179    pub(crate) sedp: Sedp,
1180    wlp: Wlp,
1181    /// The secure liveliness endpoints, under DDS Security liveliness
1182    /// protection.
1183    wlp_secure: Option<Wlp>,
1184    /// The DCPSParticipantsSecure endpoints, under DDS Security
1185    /// discovery protection.
1186    spdp_secure: Option<SpdpSecure>,
1187    typelookup: TypeLookup,
1188    /// The TypeObjects asked for, and the participant asked: each is
1189    /// asked for once from each participant.
1190    type_requests: HashSet<(TypeIdentifier, GuidPrefix)>,
1191    /// The COMPLETE types whose dependencies were asked for, and of whom.
1192    dependency_requests: HashSet<(TypeIdentifier, GuidPrefix)>,
1193    /// How many TypeObjects came by TypeLookup.
1194    learnt_types: usize,
1195    /// When to write the next automatic liveliness message, while there
1196    /// are AUTOMATIC writers with a finite lease.
1197    next_automatic: Option<Instant>,
1198    /// A MANUAL_BY_PARTICIPANT writer asserted its liveliness since the
1199    /// last manual liveliness message.
1200    manual_pending: bool,
1201    /// The earliest time for the next manual liveliness message.
1202    next_manual: Instant,
1203    /// Where PERSISTENT writers keep their files.
1204    persistence_directory: std::path::PathBuf,
1205    writer_config: WriterConfig,
1206    reader_config: ReaderConfig,
1207    next_entity: u32,
1208    pub(crate) writers: HashMap<Guid, WriterState>,
1209    pub(crate) readers: HashMap<Guid, ReaderState>,
1210    deleted: bool,
1211    /// Status changes of local writers and readers, for
1212    /// [`Shared::flush`] to hand to their listeners, or else to mark as
1213    /// changed for their StatusConditions.
1214    pending: Vec<(Guid, StatusMask)>,
1215    /// The TypeObjects of the registered types, by type name.
1216    types: HashMap<String, TypeObjects>,
1217    /// The registered types, by type name, for content filters.
1218    dynamic_types: HashMap<String, DynamicType>,
1219    /// INCONSISTENT_TOPIC, by topic name.
1220    pub(crate) inconsistent_topics: HashMap<String, InconsistentTopicStatus>,
1221    /// The topics whose INCONSISTENT_TOPIC changed, for [`Shared::flush`].
1222    pending_topics: Vec<String>,
1223    /// The listeners of the topics, by topic name.
1224    pub(crate) topic_listeners: HashMap<String, (Arc<dyn TopicListener>, StatusMask)>,
1225    /// The participant's listener.
1226    pub(crate) listener: Option<(Arc<dyn DomainParticipantListener>, StatusMask)>,
1227    /// DDS Security, when it is on.
1228    #[cfg(feature = "security")]
1229    pub(crate) security: Option<Arc<Security>>,
1230}
1231
1232/// Writes a liveliness message on the plain and the secure endpoints.
1233fn assert_wlp(wlp: &mut Wlp, secure: &mut Option<Wlp>, kind: [u8; 4]) {
1234    wlp.assert_liveliness(kind);
1235    if let Some(w) = secure.as_mut() {
1236        w.assert_liveliness(kind);
1237    }
1238}
1239
1240/// The shortest interval between two liveliness messages of a kind.
1241const MIN_LIVELINESS_PERIOD: Duration = Duration::from_millis(10);
1242
1243impl Inner {
1244    /// Announces a local writer, on the secure SEDP endpoints if its
1245    /// topic has discovery protection.
1246    fn sedp_add_writer(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1247        #[cfg(feature = "security")]
1248        if self
1249            .security
1250            .as_ref()
1251            .is_some_and(|s| s.topic_discovery_protected(&data.topic_name))
1252        {
1253            return self.sedp.add_writer_secure(data);
1254        }
1255        self.sedp.add_writer(data)
1256    }
1257
1258    /// Announces a local reader, like [`Self::sedp_add_writer`].
1259    fn sedp_add_reader(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1260        #[cfg(feature = "security")]
1261        if self
1262            .security
1263            .as_ref()
1264            .is_some_and(|s| s.topic_discovery_protected(&data.topic_name))
1265        {
1266            return self.sedp.add_reader_secure(data);
1267        }
1268        self.sedp.add_reader(data)
1269    }
1270
1271    /// Notes that the statuses `k` of the local writer or reader `g`
1272    /// changed.
1273    fn changed(&mut self, g: Guid, k: StatusMask) {
1274        if !k.is_empty() {
1275            self.pending.push((g, k));
1276        }
1277    }
1278
1279    /// A local writer asserted its liveliness, by writing or with
1280    /// `assert_liveliness`. For a MANUAL_BY_PARTICIPANT writer, that
1281    /// asserts every such writer of the participant (DDS 1.4, 2.2.3.11).
1282    fn local_writer_asserted(&mut self, writer: Guid, now: Instant) {
1283        let Some(kind) = self.writers.get(&writer).map(|w| w.qos.liveliness.kind) else {
1284            return;
1285        };
1286        if kind == LivelinessKind::ManualByParticipant {
1287            self.participant_asserted(now);
1288        } else {
1289            self.local_asserted(writer, now);
1290        }
1291    }
1292
1293    /// The participant asserted its liveliness: its MANUAL_BY_PARTICIPANT
1294    /// writers are alive, and the others are told with a manual
1295    /// liveliness message (DDSI-RTPS 2.5, 8.4.13.5).
1296    fn participant_asserted(&mut self, now: Instant) {
1297        let guids: Vec<Guid> = self
1298            .writers
1299            .iter()
1300            .filter(|(_, w)| w.qos.liveliness.kind == LivelinessKind::ManualByParticipant)
1301            .map(|(g, _)| *g)
1302            .collect();
1303        if !guids.is_empty() {
1304            self.manual_pending = true;
1305        }
1306        for g in guids {
1307            self.local_asserted(g, now);
1308        }
1309    }
1310
1311    fn local_asserted(&mut self, writer: Guid, now: Instant) {
1312        if let Some(w) = self.writers.get_mut(&writer) {
1313            w.last_asserted = now;
1314            w.alive = true;
1315        }
1316        self.remote_writer_asserted(&writer, now);
1317    }
1318
1319    /// A writer asserted its liveliness, as seen by the local readers.
1320    fn remote_writer_asserted(&mut self, writer: &Guid, now: Instant) {
1321        for (g, r) in self.readers.iter_mut() {
1322            if r.writer_asserted(writer, now) {
1323                self.pending.push((*g, StatusMask::LIVELINESS_CHANGED));
1324            }
1325        }
1326    }
1327
1328    /// A liveliness message from another participant: an automatic one
1329    /// asserts its AUTOMATIC writers, a manual one those and its
1330    /// MANUAL_BY_PARTICIPANT writers.
1331    fn remote_participant_asserted(&mut self, prefix: GuidPrefix, kind: [u8; 4], now: Instant) {
1332        let manual = kind == wlp::kind::MANUAL_LIVELINESS_UPDATE;
1333        for (rg, r) in self.readers.iter_mut() {
1334            let guids: Vec<Guid> = r
1335                .liveliness
1336                .iter()
1337                .filter(|(g, l)| {
1338                    g.prefix == prefix
1339                        && (l.kind == LivelinessKind::Automatic
1340                            || (manual && l.kind == LivelinessKind::ManualByParticipant))
1341                })
1342                .map(|(g, _)| *g)
1343                .collect();
1344            for g in guids {
1345                if r.writer_asserted(&g, now) {
1346                    self.pending.push((*rg, StatusMask::LIVELINESS_CHANGED));
1347                }
1348            }
1349        }
1350    }
1351
1352    /// Liveliness and deadlines: leases that passed, deadlines missed,
1353    /// and the liveliness messages due (DDSI-RTPS 2.5, 8.7.2.2.3).
1354    fn check_timers(&mut self, now: Instant) {
1355        for (g, w) in self.writers.iter_mut() {
1356            let k = w.check(now);
1357            if !k.is_empty() {
1358                self.pending.push((*g, k));
1359            }
1360        }
1361        for (g, r) in self.readers.iter_mut() {
1362            let k = r.check(now);
1363            if !k.is_empty() {
1364                self.pending.push((*g, k));
1365            }
1366        }
1367        let min_lease = |kind: LivelinessKind| {
1368            self.writers
1369                .values()
1370                .filter(|w| w.qos.liveliness.kind == kind)
1371                .filter_map(|w| w.qos.liveliness.lease_duration)
1372                .min()
1373        };
1374        // AUTOMATIC: a message at a rate faster than the shortest lease.
1375        match min_lease(LivelinessKind::Automatic) {
1376            None => self.next_automatic = None,
1377            Some(lease) => {
1378                if self.next_automatic.is_none_or(|t| t <= now) {
1379                    assert_wlp(
1380                        &mut self.wlp,
1381                        &mut self.wlp_secure,
1382                        wlp::kind::AUTOMATIC_LIVELINESS_UPDATE,
1383                    );
1384                    self.next_automatic = Some(now + (lease / 3).max(MIN_LIVELINESS_PERIOD));
1385                }
1386            }
1387        }
1388        // MANUAL_BY_PARTICIPANT: a message when some writer asserted,
1389        // at most once a third of the shortest lease.
1390        if self.manual_pending && now >= self.next_manual {
1391            self.manual_pending = false;
1392            assert_wlp(
1393                &mut self.wlp,
1394                &mut self.wlp_secure,
1395                wlp::kind::MANUAL_LIVELINESS_UPDATE,
1396            );
1397            let period = min_lease(LivelinessKind::ManualByParticipant)
1398                .map_or(Duration::from_secs(1), |l| l / 3);
1399            self.next_manual = now + period.max(MIN_LIVELINESS_PERIOD);
1400        }
1401    }
1402}
1403
1404/// What the participant handle and its entities share with the thread.
1405pub(crate) struct Shared {
1406    /// The `Arc` this is in, to hand to listeners.
1407    this: Weak<Shared>,
1408    /// The WaitSets that have a condition of this participant attached,
1409    /// to wake when a status changes.
1410    pub(crate) waitsets: Mutex<Vec<Weak<Waker>>>,
1411    pub(crate) transport: UdpTransport,
1412    /// The shared memory transport, if it is on.
1413    #[cfg(feature = "shm")]
1414    shm: Option<rustorb_rtps::shm::ShmTransport>,
1415    pub(crate) prefix: GuidPrefix,
1416    domain_id: u32,
1417    inner: Mutex<Inner>,
1418    /// Signalled when a reader gets data.
1419    pub(crate) data_arrived: Condvar,
1420    /// Signalled when a writer's readers acknowledge changes or go away.
1421    pub(crate) acknowledged: Condvar,
1422    stop: AtomicBool,
1423    drop_one_in: Option<u32>,
1424    /// DDS Security, when it is on.
1425    #[cfg(feature = "security")]
1426    pub(crate) security: Option<Arc<Security>>,
1427    /// The state of the generator that picks the datagrams to drop.
1428    drop_state: AtomicU64,
1429}
1430
1431impl Shared {
1432    /// Sends a message to one destination, given by its locators:
1433    /// through shared memory if the peer has a locator of it that can be
1434    /// used, else to its other locators. Whether some send went, and the
1435    /// last error.
1436    pub(crate) fn send(&self, bytes: &[u8], locators: &[Locator]) -> (bool, Option<io::Error>) {
1437        #[cfg(feature = "security")]
1438        let encoded;
1439        #[cfg(feature = "security")]
1440        let bytes: &[u8] = match &self.security {
1441            Some(sec) => match sec.encode(bytes) {
1442                Some(b) => {
1443                    encoded = b;
1444                    &encoded
1445                }
1446                None => return (false, None),
1447            },
1448            None => bytes,
1449        };
1450        let mut sent = false;
1451        let mut last_err = None;
1452        #[cfg(feature = "shm")]
1453        if let Some(shm) = &self.shm {
1454            for l in shm.select(locators) {
1455                let r = if l.kind == Locator::KIND_SHM {
1456                    shm.send(bytes, l)
1457                } else {
1458                    self.transport.send(bytes, l)
1459                };
1460                match r {
1461                    Ok(()) => sent = true,
1462                    Err(e) => last_err = Some(e),
1463                }
1464            }
1465            return (sent, last_err);
1466        }
1467        for l in locators.iter().filter(|l| l.kind != Locator::KIND_SHM) {
1468            match self.transport.send(bytes, l) {
1469                Ok(()) => sent = true,
1470                Err(e) => last_err = Some(e),
1471            }
1472        }
1473        (sent, last_err)
1474    }
1475
1476    /// The vendor of a discovered participant.
1477    pub(crate) fn vendor_of(&self, prefix: &GuidPrefix) -> Option<VendorId> {
1478        self.lock_any()
1479            .spdp
1480            .participant(prefix)
1481            .map(|p| p.vendor_id)
1482    }
1483
1484    pub(crate) fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
1485        let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
1486        if g.deleted {
1487            return Err(Error::AlreadyDeleted);
1488        }
1489        Ok(g)
1490    }
1491
1492    /// Hands the status changes noted since the last call to the
1493    /// listeners that take them, and marks the others as changed (DDS
1494    /// 1.4, 2.2.4.2.1); then wakes the threads waiting for data and the
1495    /// WaitSets. Called without the lock held, after each change.
1496    ///
1497    /// A listener runs on the thread that made the change (the
1498    /// participant's thread, or the one that wrote), without the lock: it
1499    /// may call any operation, but should be quick.
1500    pub(crate) fn flush(&self) {
1501        let mut calls: Vec<ListenerCall> = Vec::new();
1502        let mut any = false;
1503        {
1504            let mut g = self.lock_any();
1505            let inner = &mut *g;
1506            if inner.pending.is_empty() && inner.pending_topics.is_empty() {
1507                return;
1508            }
1509            let participant = inner.listener.clone();
1510            let participant_for = |bit: StatusMask| {
1511                participant
1512                    .as_ref()
1513                    .filter(|(_, m)| m.contains(bit))
1514                    .map(|(l, _)| l.clone())
1515            };
1516            // The subscribers whose on_data_on_readers is called.
1517            let mut on_readers: Vec<Arc<SubscriberEntity>> = Vec::new();
1518            for (guid, k) in std::mem::take(&mut inner.pending) {
1519                any = true;
1520                for bit in k.bits() {
1521                    if let Some(w) = inner.writers.get_mut(&guid) {
1522                        let own = w
1523                            .listener
1524                            .as_ref()
1525                            .filter(|(_, m)| m.contains(bit))
1526                            .map(|(l, _)| l.clone());
1527                        if let Some(l) = own
1528                            && let Some(ev) = w.take_event(bit)
1529                        {
1530                            w.changes = w.changes & !bit;
1531                            calls.push(Box::new(move |s| l(s, guid, ev)));
1532                            continue;
1533                        }
1534                        let group = w.publisher.as_ref().and_then(|p| p.listener_for(bit));
1535                        let call: Option<ListenerCall> = if let Some(l) = group {
1536                            w.take_event(bit).map(|ev| -> ListenerCall {
1537                                Box::new(move |s| writer_event(&*l, s, guid, ev))
1538                            })
1539                        } else if let Some(l) = participant_for(bit) {
1540                            w.take_event(bit).map(|ev| -> ListenerCall {
1541                                Box::new(move |s| writer_event(&*l, s, guid, ev))
1542                            })
1543                        } else {
1544                            None
1545                        };
1546                        match call {
1547                            Some(c) => {
1548                                w.changes = w.changes & !bit;
1549                                calls.push(c);
1550                            }
1551                            None => w.changes |= bit,
1552                        }
1553                    } else if let Some(r) = inner.readers.get_mut(&guid) {
1554                        if bit == StatusMask::DATA_AVAILABLE {
1555                            // 2.2.4.3.2: DATA_ON_READERS first, on the
1556                            // subscriber's listener, else the
1557                            // participant's. The reader keeps
1558                            // DATA_AVAILABLE.
1559                            let on = StatusMask::DATA_ON_READERS;
1560                            if let Some(sub) = r.subscriber.clone() {
1561                                let call: Option<ListenerCall> =
1562                                    match (sub.listener_for(on), participant_for(on)) {
1563                                        (Some(l), _) => {
1564                                            let sub = sub.clone();
1565                                            Some(Box::new(move |s| data_on_readers(&*l, s, sub)))
1566                                        }
1567                                        (None, Some(l)) => {
1568                                            let sub = sub.clone();
1569                                            Some(Box::new(move |s| data_on_readers(&*l, s, sub)))
1570                                        }
1571                                        (None, None) => None,
1572                                    };
1573                                if let Some(c) = call {
1574                                    r.changes |= bit;
1575                                    if !on_readers.iter().any(|s| Arc::ptr_eq(s, &sub)) {
1576                                        on_readers.push(sub);
1577                                        calls.push(c);
1578                                    }
1579                                    continue;
1580                                }
1581                            }
1582                        }
1583                        let own = r
1584                            .listener
1585                            .as_ref()
1586                            .filter(|(_, m)| m.contains(bit))
1587                            .map(|(l, _)| l.clone());
1588                        if let Some(l) = own
1589                            && let Some(ev) = r.take_event(bit)
1590                        {
1591                            r.changes = r.changes & !bit;
1592                            calls.push(Box::new(move |s| l(s, guid, ev)));
1593                            continue;
1594                        }
1595                        let group = r.subscriber.as_ref().and_then(|p| p.listener_for(bit));
1596                        let call: Option<ListenerCall> = if let Some(l) = group {
1597                            r.take_event(bit).map(|ev| -> ListenerCall {
1598                                Box::new(move |s| reader_event(&*l, s, guid, ev))
1599                            })
1600                        } else if let Some(l) = participant_for(bit) {
1601                            r.take_event(bit).map(|ev| -> ListenerCall {
1602                                Box::new(move |s| reader_event(&*l, s, guid, ev))
1603                            })
1604                        } else {
1605                            None
1606                        };
1607                        match call {
1608                            Some(c) => {
1609                                r.changes = r.changes & !bit;
1610                                calls.push(c);
1611                            }
1612                            None => r.changes |= bit,
1613                        }
1614                    }
1615                }
1616            }
1617            let bit = StatusMask::INCONSISTENT_TOPIC;
1618            for topic in std::mem::take(&mut inner.pending_topics) {
1619                let own = inner
1620                    .topic_listeners
1621                    .get(&topic)
1622                    .filter(|(_, m)| m.contains(bit))
1623                    .map(|(l, _)| l.clone());
1624                let status = |inner: &mut Inner| {
1625                    inner
1626                        .inconsistent_topics
1627                        .get_mut(&topic)
1628                        .map(|s| s.take())
1629                        .unwrap_or_default()
1630                };
1631                if let Some(l) = own {
1632                    let status = status(inner);
1633                    calls.push(Box::new(move |_| l.on_inconsistent_topic(&topic, status)));
1634                } else if let Some(l) = participant_for(bit) {
1635                    let status = status(inner);
1636                    calls.push(Box::new(move |_| l.on_inconsistent_topic(&topic, status)));
1637                }
1638            }
1639        }
1640        if any {
1641            self.data_arrived.notify_all();
1642            self.wake_waitsets();
1643        }
1644        if calls.is_empty() {
1645            return;
1646        }
1647        if let Some(this) = self.this.upgrade() {
1648            for c in calls {
1649                c(&this);
1650            }
1651        }
1652    }
1653
1654    /// Calls the listeners of the readers of `subscriber` that have
1655    /// DATA_AVAILABLE (`notify_datareaders`, DDS 1.4, 2.2.2.5.2.8): their
1656    /// own listeners, if they take it.
1657    pub(crate) fn notify_datareaders(&self, subscriber: &Arc<SubscriberEntity>) {
1658        let bit = StatusMask::DATA_AVAILABLE;
1659        let mut calls: Vec<ListenerCall> = Vec::new();
1660        {
1661            let mut g = self.lock_any();
1662            for (guid, r) in g.readers.iter_mut() {
1663                let mine = r
1664                    .subscriber
1665                    .as_ref()
1666                    .is_some_and(|s| Arc::ptr_eq(s, subscriber));
1667                if !mine || !r.changes.contains(bit) {
1668                    continue;
1669                }
1670                let own = r
1671                    .listener
1672                    .as_ref()
1673                    .filter(|(_, m)| m.contains(bit))
1674                    .map(|(l, _)| l.clone());
1675                if let Some(l) = own {
1676                    r.changes = r.changes & !bit;
1677                    let guid = *guid;
1678                    calls.push(Box::new(move |s| l(s, guid, ReaderEvent::DataAvailable)));
1679                }
1680            }
1681        }
1682        if let Some(this) = self.this.upgrade() {
1683            for c in calls {
1684                c(&this);
1685            }
1686        }
1687    }
1688
1689    /// Wakes the WaitSets attached to some condition of the participant,
1690    /// to check their conditions again.
1691    pub(crate) fn wake_waitsets(&self) {
1692        let mut w = self.waitsets.lock().unwrap_or_else(|e| e.into_inner());
1693        w.retain(|w| match w.upgrade() {
1694            Some(w) => {
1695                w.wake();
1696                true
1697            }
1698            None => false,
1699        });
1700    }
1701
1702    /// Like [`Shared::lock`], for clean-up that runs even after the
1703    /// participant is deleted.
1704    pub(crate) fn lock_any(&self) -> MutexGuard<'_, Inner> {
1705        self.inner.lock().unwrap_or_else(|e| e.into_inner())
1706    }
1707
1708    /// Whether to drop a received user datagram, for
1709    /// [`ParticipantConfig::drop_one_in`]. A fixed pattern would line up
1710    /// with the peer's (one datagram for new data, one for a repair, say)
1711    /// and drop the same kind every time, so this draws from xorshift64.
1712    fn should_drop(&self) -> bool {
1713        let Some(n) = self.drop_one_in else {
1714            return false;
1715        };
1716        let mut x = self.drop_state.load(Ordering::Relaxed);
1717        x ^= x << 13;
1718        x ^= x >> 7;
1719        x ^= x << 17;
1720        self.drop_state.store(x, Ordering::Relaxed);
1721        x.is_multiple_of(u64::from(n))
1722    }
1723
1724    pub(crate) fn new_guid(&self, kind: u8) -> Result<Guid> {
1725        let mut g = self.lock()?;
1726        let n = g.next_entity;
1727        if n >= 1 << 24 {
1728            return Err(Error::OutOfResources);
1729        }
1730        g.next_entity += 1;
1731        let key = [(n >> 16) as u8, (n >> 8) as u8, n as u8];
1732        Ok(Guid::new(self.prefix, EntityId::user(key, kind)))
1733    }
1734
1735    /// The TypeInformation of a registered type.
1736    pub(crate) fn type_information(
1737        &self,
1738        type_name: &str,
1739    ) -> Result<Option<rustorb_xtypes::type_object::TypeInformation>> {
1740        Ok(self
1741            .lock()?
1742            .types
1743            .get(type_name)
1744            .map(|o| o.information.clone()))
1745    }
1746
1747    /// Adds a local writer: announces it, and matches it with the local
1748    /// readers.
1749    pub(crate) fn add_writer(
1750        &self,
1751        #[allow(unused_mut)] mut data: EndpointData,
1752        qos: DataWriterQos,
1753        keys: Arc<dyn KeyOps>,
1754        listener: Option<(WriterListener, StatusMask)>,
1755        publisher: Arc<PublisherEntity>,
1756    ) -> Result<()> {
1757        {
1758            let mut g = self.lock()?;
1759            let inner = &mut *g;
1760            let guid = data.guid;
1761            let now = Instant::now();
1762            #[cfg(feature = "security")]
1763            let payload_encoder = match &inner.security {
1764                Some(sec) => sec.local_endpoint(&mut data, true)?,
1765                None => None,
1766            };
1767            let rtps = ReliableWriter::new(guid, VENDOR_ID, inner.writer_config.clone());
1768            let liveliness_kind = qos.liveliness.kind;
1769            let deadline = qos.deadline;
1770            let mut w = WriterState {
1771                data: data.clone(),
1772                qos,
1773                keyed: keys.keyed(),
1774                keys,
1775                rtps,
1776                matched: BTreeSet::new(),
1777                instances: BTreeMap::new(),
1778                change_instance: HashMap::new(),
1779                incompatible: IncompatibleQosStatus::default(),
1780                last_asserted: now,
1781                alive: true,
1782                liveliness_lost: LivelinessLostStatus::default(),
1783                deadlines: Deadlines::new(deadline),
1784                matched_status: MatchedStatus::default(),
1785                changes: StatusMask::NONE,
1786                enabled: StatusMask::ALL,
1787                listener,
1788                publisher: Some(publisher),
1789                #[cfg(feature = "security")]
1790                payload_encoder,
1791                disposed: BTreeSet::new(),
1792                orphan: false,
1793                cleanup_at: None,
1794                store: None,
1795                #[cfg(feature = "shm")]
1796                pool: None,
1797                #[cfg(feature = "shm")]
1798                loans: VecDeque::new(),
1799                persisted: BTreeMap::new(),
1800                restoring: false,
1801            };
1802            if w.qos.durability == DurabilityKind::Persistent {
1803                let (store, records) = Store::open(
1804                    &inner.persistence_directory,
1805                    &data.topic_name,
1806                    &data.type_name,
1807                )?;
1808                w.store = Some(store);
1809                w.restore(records);
1810            }
1811            let lease = w.local_lease();
1812            let mut changes = StatusMask::NONE;
1813            for (rg, r) in inner.readers.iter_mut() {
1814                match match_endpoints(&data, &r.data, inner.sedp.registry()) {
1815                    Match::Matched => {
1816                        w.add_match(*rg);
1817                        changes |= StatusMask::PUBLICATION_MATCHED;
1818                        let mut k = StatusMask::NONE;
1819                        if r.add_match(guid) {
1820                            k |= StatusMask::SUBSCRIPTION_MATCHED;
1821                        }
1822                        if r.writer_matched(guid, liveliness_kind, lease, now) {
1823                            k |= StatusMask::LIVELINESS_CHANGED;
1824                        }
1825                        // What a PERSISTENT writer took up from its file.
1826                        if w.transient_local()
1827                            && r.data.durability >= DurabilityKind::TransientLocal
1828                        {
1829                            let kept: Vec<Change> = w
1830                                .rtps
1831                                .changes()
1832                                .filter(|c| w.rtps.is_for(c.sequence_number, rg))
1833                                .cloned()
1834                                .collect();
1835                            for c in kept {
1836                                if let Some(c) = r.incoming(c) {
1837                                    k |= r.accept(c);
1838                                }
1839                            }
1840                        }
1841                        inner.pending.push((*rg, k));
1842                    }
1843                    Match::Incompatible(policies) => {
1844                        w.incompatible.add(&policies);
1845                        changes |= StatusMask::OFFERED_INCOMPATIBLE_QOS;
1846                        r.incompatible.add(&policies);
1847                        inner
1848                            .pending
1849                            .push((*rg, StatusMask::REQUESTED_INCOMPATIBLE_QOS));
1850                    }
1851                    // Local types are all known, and a local pair counts
1852                    // only once remote endpoints are found (DDS 1.4,
1853                    // 2.2.4.1: INCONSISTENT_TOPIC is about other
1854                    // participants).
1855                    Match::Inconsistent | Match::Unresolved(_) | Match::Unrelated => {}
1856                }
1857            }
1858            inner.writers.insert(guid, w);
1859            inner.changed(guid, changes);
1860            let events = inner.sedp_add_writer(data);
1861            apply_sedp_events(inner, events, now);
1862        }
1863        self.flush();
1864        Ok(())
1865    }
1866
1867    /// Adds a local reader: announces it, and matches it with the local
1868    /// writers.
1869    pub(crate) fn add_reader(
1870        &self,
1871        #[allow(unused_mut)] mut data: EndpointData,
1872        qos: DataReaderQos,
1873        keys: Arc<dyn KeyOps>,
1874        listener: Option<(ReaderListener, StatusMask)>,
1875        filter: Option<ContentFilter>,
1876        subscriber: Arc<SubscriberEntity>,
1877    ) -> Result<()> {
1878        {
1879            let mut g = self.lock()?;
1880            let inner = &mut *g;
1881            let guid = data.guid;
1882            let now = Instant::now();
1883            #[cfg(feature = "security")]
1884            if let Some(sec) = &inner.security {
1885                sec.local_endpoint(&mut data, false)?;
1886            }
1887            let mut r = ReaderState::new(data.clone(), &qos, keys, &inner.reader_config);
1888            #[cfg(feature = "shm")]
1889            {
1890                r.pools = self.shm.as_ref().map(|s| s.pools());
1891            }
1892            #[cfg(feature = "security")]
1893            {
1894                r.payload_security = inner
1895                    .security
1896                    .clone()
1897                    .filter(|s| s.payload_protected(&data.topic_name));
1898            }
1899            r.listener = listener;
1900            r.subscriber = Some(subscriber);
1901            r.filter = filter;
1902            let mut changes = StatusMask::NONE;
1903            // What TRANSIENT_LOCAL writers kept, for a TRANSIENT_LOCAL
1904            // reader.
1905            let mut kept = Vec::new();
1906            for (wg, w) in inner.writers.iter_mut() {
1907                match match_endpoints(&w.data, &data, inner.sedp.registry()) {
1908                    Match::Matched => {
1909                        r.add_match(*wg);
1910                        changes |= StatusMask::SUBSCRIPTION_MATCHED;
1911                        if r.writer_matched(*wg, w.qos.liveliness.kind, w.local_lease(), now) {
1912                            changes |= StatusMask::LIVELINESS_CHANGED;
1913                        }
1914                        if w.add_match(guid) {
1915                            inner.pending.push((*wg, StatusMask::PUBLICATION_MATCHED));
1916                        }
1917                        if w.transient_local() && qos.durability >= DurabilityKind::TransientLocal {
1918                            kept.extend(
1919                                w.rtps
1920                                    .changes()
1921                                    .filter(|c| w.rtps.is_for(c.sequence_number, &guid))
1922                                    .cloned(),
1923                            );
1924                        }
1925                    }
1926                    Match::Incompatible(policies) => {
1927                        r.incompatible.add(&policies);
1928                        changes |= StatusMask::REQUESTED_INCOMPATIBLE_QOS;
1929                        w.incompatible.add(&policies);
1930                        inner
1931                            .pending
1932                            .push((*wg, StatusMask::OFFERED_INCOMPATIBLE_QOS));
1933                    }
1934                    Match::Inconsistent | Match::Unresolved(_) | Match::Unrelated => {}
1935                }
1936            }
1937            for c in kept {
1938                if let Some(c) = r.incoming(c) {
1939                    changes |= r.accept(c);
1940                }
1941            }
1942            inner.readers.insert(guid, r);
1943            inner.changed(guid, changes);
1944            let events = inner.sedp_add_reader(data);
1945            apply_sedp_events(inner, events, now);
1946        }
1947        self.flush();
1948        Ok(())
1949    }
1950
1951    /// The registered type named `type_name`.
1952    pub(crate) fn dynamic_type(&self, type_name: &str) -> Result<Option<DynamicType>> {
1953        Ok(self.lock()?.dynamic_types.get(type_name).cloned())
1954    }
1955
1956    /// Changes the expression parameters of the filters of the readers
1957    /// `readers`, and announces them (DDSI-RTPS 2.5, 8.7.3.1: as for a
1958    /// change of QoS). Readers that are gone are skipped.
1959    pub(crate) fn set_filter_parameters(
1960        &self,
1961        readers: &[Guid],
1962        parameters: &[String],
1963    ) -> Result<()> {
1964        {
1965            let mut g = self.lock()?;
1966            let inner = &mut *g;
1967            let now = Instant::now();
1968            for guid in readers {
1969                let Some(r) = inner.readers.get_mut(guid) else {
1970                    continue;
1971                };
1972                if let Some(f) = &mut r.filter {
1973                    f.set_parameters(parameters)?;
1974                }
1975                if let Some(cf) = &mut r.data.content_filter {
1976                    cf.expression_parameters = parameters.to_vec();
1977                }
1978                let data = r.data.clone();
1979                let events = inner.sedp_add_reader(data);
1980                apply_sedp_events(inner, events, now);
1981            }
1982        }
1983        self.flush();
1984        Ok(())
1985    }
1986
1987    /// Deletes a local writer. Deleting a writer unregisters its
1988    /// instances (DDS 1.4, 2.2.3.21), disposing them too when
1989    /// `autodispose_unregistered_instances` is set; then its readers lose
1990    /// it.
1991    ///
1992    /// A TRANSIENT or PERSISTENT writer is not unregistered nor removed:
1993    /// the participant keeps it, with its samples, until it is deleted
1994    /// itself (DDS 1.4, 2.2.3.4).
1995    pub(crate) fn remove_writer(&self, guid: &Guid) {
1996        {
1997            let mut g = self.lock_any();
1998            let deleted = g.deleted;
1999            if let Some(w) = g.writers.get_mut(guid)
2000                && !deleted
2001                && !w.orphan
2002                && w.qos.durability >= DurabilityKind::Transient
2003            {
2004                w.orphan(Instant::now());
2005                return;
2006            }
2007        }
2008        let handles: Vec<InstanceHandle> = {
2009            let g = self.lock_any();
2010            match g.writers.get(guid) {
2011                Some(w) if !g.deleted => w.instances.keys().copied().collect(),
2012                _ => Vec::new(),
2013            }
2014        };
2015        for h in handles {
2016            let _ = self.write(
2017                *guid,
2018                h,
2019                WriteOp::Lifecycle {
2020                    dispose: self.autodispose_of(guid),
2021                    unregister: true,
2022                },
2023                Time::now(),
2024            );
2025        }
2026        {
2027            let mut g = self.lock_any();
2028            let inner = &mut *g;
2029            #[cfg(feature = "security")]
2030            if let Some(sec) = &inner.security {
2031                sec.remove_local_endpoint(guid);
2032            }
2033            if inner.writers.remove(guid).is_none() {
2034                return;
2035            }
2036            for (rg, r) in inner.readers.iter_mut() {
2037                let k = r.writer_removed(guid);
2038                if !k.is_empty() {
2039                    inner.pending.push((*rg, k));
2040                }
2041            }
2042            if !inner.deleted {
2043                inner.sedp.remove_writer(guid);
2044            }
2045        }
2046        self.flush();
2047    }
2048
2049    /// Registers an instance of a local writer, as a write would.
2050    pub(crate) fn register_instance(&self, writer: &Guid, h: InstanceHandle) -> Result<()> {
2051        let mut g = self.lock()?;
2052        let Some(w) = g.writers.get_mut(writer) else {
2053            return Ok(());
2054        };
2055        w.register(h)
2056    }
2057
2058    pub(crate) fn autodispose_of(&self, writer: &Guid) -> bool {
2059        self.lock_any().writers.get(writer).is_some_and(|w| {
2060            w.qos
2061                .writer_data_lifecycle
2062                .autodispose_unregistered_instances
2063        })
2064    }
2065
2066    pub(crate) fn remove_reader(&self, guid: &Guid) {
2067        {
2068            let mut g = self.lock_any();
2069            let inner = &mut *g;
2070            if inner.readers.remove(guid).is_none() {
2071                return;
2072            }
2073            #[cfg(feature = "security")]
2074            if let Some(sec) = &inner.security {
2075                sec.remove_local_endpoint(guid);
2076            }
2077            for (wg, w) in inner.writers.iter_mut() {
2078                if w.remove_match(guid) {
2079                    inner.pending.push((*wg, StatusMask::PUBLICATION_MATCHED));
2080                }
2081            }
2082            if !inner.deleted {
2083                inner.sedp.remove_reader(guid);
2084            }
2085        }
2086        self.acknowledged.notify_all();
2087        self.flush();
2088    }
2089
2090    /// Writes a change of instance `h` from a local writer (a value, a
2091    /// dispose or an unregister): delivers it to the matched local
2092    /// readers, adds it to the writer's history and sends it to the
2093    /// matched remote readers.
2094    ///
2095    /// A reliable KEEP_ALL writer whose history is full waits up to
2096    /// `max_blocking_time` for its readers to acknowledge changes.
2097    pub(crate) fn write(
2098        &self,
2099        writer: Guid,
2100        h: InstanceHandle,
2101        op: WriteOp,
2102        timestamp: Time,
2103    ) -> Result<SequenceNumber> {
2104        let out;
2105        let (related, directed) = match &op {
2106            WriteOp::Value(_, r, d) => (*r, *d),
2107            WriteOp::Lifecycle { .. } => (None, None),
2108        };
2109        let sn;
2110        {
2111            let mut g = self.lock()?;
2112            let Some(blocking) = g
2113                .writers
2114                .get(&writer)
2115                .map(|w| w.qos.reliability.max_blocking_time)
2116            else {
2117                return Err(Error::AlreadyDeleted);
2118            };
2119            let deadline = Instant::now() + blocking;
2120            loop {
2121                let Some(w) = g.writers.get_mut(&writer) else {
2122                    return Err(Error::AlreadyDeleted);
2123                };
2124                if !w.is_full(&h) {
2125                    break;
2126                }
2127                let now = Instant::now();
2128                if now >= deadline {
2129                    return Err(Error::Timeout);
2130                }
2131                g = match self.acknowledged.wait_timeout(g, deadline - now) {
2132                    Ok((g, _)) => g,
2133                    Err(e) => e.into_inner().0,
2134                };
2135                if g.deleted {
2136                    return Err(Error::AlreadyDeleted);
2137                }
2138            }
2139            let inner = &mut *g;
2140            let w = inner.writers.get_mut(&writer).expect("checked above");
2141            let change;
2142            // A dispose or an unregister carries the key payload when an
2143            // OpenDDS reader is matched (see `WriterState::add`).
2144            let key_payload = matches!(op, WriteOp::Lifecycle { .. })
2145                && w.matched.iter().any(|r| {
2146                    inner
2147                        .spdp
2148                        .participant(&r.prefix)
2149                        .is_some_and(|p| p.vendor_id == OPENDDS)
2150                });
2151            #[cfg(feature = "shm")]
2152            let by_reference = matches!(&op, WriteOp::Value(p, ..) if p.is_loaned())
2153                && self.by_reference(inner, &writer);
2154            #[cfg(not(feature = "shm"))]
2155            let by_reference = false;
2156            let w = inner.writers.get_mut(&writer).expect("checked above");
2157            (sn, change) = w.add(h, op, timestamp, key_payload, by_reference)?;
2158            let now = Instant::now();
2159            out = w.rtps.poll(now);
2160            w.trim();
2161            inner.local_writer_asserted(writer, now);
2162            let w = inner.writers.get_mut(&writer).expect("checked above");
2163            let matched: Vec<Guid> = w.matched.iter().copied().collect();
2164            for r in matched {
2165                if r.prefix != self.prefix || directed.is_some_and(|d| d != r) {
2166                    continue;
2167                }
2168                if let Some(st) = inner.readers.get_mut(&r) {
2169                    let c = Incoming {
2170                        writer,
2171                        sequence_number: sn,
2172                        source_timestamp: Some(timestamp),
2173                        related_sample_identity: related,
2174                        instance: h,
2175                        change: change.clone(),
2176                    };
2177                    let k = st.accept(c);
2178                    inner.changed(r, k);
2179                }
2180            }
2181        }
2182        self.flush();
2183        // A datagram that cannot be sent now is like one lost on the way:
2184        // a reliable reader gets it repaired, a best-effort one does not.
2185        // The write fails only when nothing could be sent at all.
2186        let mut last_err = None;
2187        let mut sent = false;
2188        for o in &out {
2189            let (ok, err) = self.send(&o.bytes, &o.locators);
2190            sent |= ok;
2191            if err.is_some() {
2192                last_err = err;
2193            }
2194        }
2195        match last_err {
2196            Some(e) if !sent => Err(e.into()),
2197            _ => Ok(sn),
2198        }
2199    }
2200
2201    /// Whether local writer `writer` sends its loaned samples by
2202    /// reference: when every reader it matches is of this participant or
2203    /// reached by shared memory, the writer is VOLATILE (no late joiner
2204    /// needs one) and DDS Security is off.
2205    #[cfg(feature = "shm")]
2206    fn by_reference(&self, inner: &Inner, writer: &Guid) -> bool {
2207        let (Some(shm), Some(w)) = (&self.shm, inner.writers.get(writer)) else {
2208            return false;
2209        };
2210        #[cfg(feature = "security")]
2211        if self.security.is_some() {
2212            return false;
2213        }
2214        w.qos.durability == DurabilityKind::Volatile
2215            && w.matched.iter().all(|r| {
2216                // Only rustorb-dds has shared memory locators.
2217                r.prefix == self.prefix
2218                    || w.rtps
2219                        .reader_destination(r)
2220                        .is_some_and(|l| shm.reaches(&l))
2221            })
2222    }
2223
2224    /// The pool of local writer `writer` for loaned samples of up to
2225    /// `size` octets, made on first use: `None` without shared memory, or
2226    /// with DDS Security on (whose samples stay out of files that other
2227    /// processes can map).
2228    #[cfg(feature = "shm")]
2229    pub(crate) fn writer_pool(
2230        &self,
2231        writer: &Guid,
2232        size: usize,
2233    ) -> Result<Option<Arc<rustorb_rtps::shm::Pool>>> {
2234        let Some(shm) = &self.shm else {
2235            return Ok(None);
2236        };
2237        #[cfg(feature = "security")]
2238        if self.security.is_some() {
2239            return Ok(None);
2240        }
2241        let mut g = self.lock()?;
2242        let w = g.writers.get_mut(writer).ok_or(Error::AlreadyDeleted)?;
2243        if let Some(p) = &w.pool
2244            && p.slot_size() >= size
2245        {
2246            return Ok(Some(p.clone()));
2247        }
2248        // Room for the history, the readers' samples and the newest
2249        // loans kept.
2250        let slots = match w.qos.history {
2251            History::KeepLast(d) => 2 * d.max(1) + 2 * LOANS_KEPT,
2252            History::KeepAll => w.qos.resource_limits.max_samples.unwrap_or(32) + 2 * LOANS_KEPT,
2253        }
2254        .min(MAX_POOL_SLOTS);
2255        let pool = shm.create_pool(slots as u32, size)?;
2256        w.pool = Some(pool.clone());
2257        Ok(Some(pool))
2258    }
2259
2260    /// The discovery data of a writer or reader, local or remote.
2261    pub(crate) fn endpoint_data(&self, guid: &Guid) -> Option<EndpointData> {
2262        let g = self.lock_any();
2263        g.writers
2264            .get(guid)
2265            .map(|w| &w.data)
2266            .or_else(|| g.readers.get(guid).map(|r| &r.data))
2267            .or_else(|| g.sedp.remote_writer(guid))
2268            .or_else(|| g.sedp.remote_reader(guid))
2269            .cloned()
2270    }
2271
2272    /// The sequence number of the last change of local writer `writer`
2273    /// (0 if none): the next is one more.
2274    pub(crate) fn last_sequence_number(&self, writer: &Guid) -> Result<SequenceNumber> {
2275        self.lock_any()
2276            .writers
2277            .get(writer)
2278            .map(|w| w.rtps.last_sn())
2279            .ok_or(Error::AlreadyDeleted)
2280    }
2281
2282    /// Whether participant `prefix` has acknowledged the latest SEDP
2283    /// announcement of local writer or reader `local`.
2284    pub(crate) fn is_announced_to(&self, local: &Guid, prefix: &GuidPrefix) -> bool {
2285        self.lock_any().sedp.is_announced_to(local, prefix)
2286    }
2287
2288    /// Changes the discovery data of a local writer or reader with `f`,
2289    /// and announces it again.
2290    pub(crate) fn update_endpoint(
2291        &self,
2292        guid: &Guid,
2293        f: impl FnOnce(&mut EndpointData),
2294    ) -> Result<()> {
2295        {
2296            let mut g = self.lock()?;
2297            let inner = &mut *g;
2298            let events = if let Some(w) = inner.writers.get_mut(guid) {
2299                f(&mut w.data);
2300                let data = w.data.clone();
2301                inner.sedp_add_writer(data)
2302            } else if let Some(r) = inner.readers.get_mut(guid) {
2303                f(&mut r.data);
2304                let data = r.data.clone();
2305                inner.sedp_add_reader(data)
2306            } else {
2307                return Err(Error::AlreadyDeleted);
2308            };
2309            apply_sedp_events(inner, events, Instant::now());
2310        }
2311        self.flush();
2312        Ok(())
2313    }
2314
2315    /// `assert_liveliness` of a local writer. A MANUAL_BY_TOPIC writer
2316    /// sends a HEARTBEAT with the liveliness flag to its readers
2317    /// (DDSI-RTPS 2.5, 8.7.2.2.3); a MANUAL_BY_PARTICIPANT one asserts
2318    /// the participant; it does nothing for an AUTOMATIC writer.
2319    pub(crate) fn assert_writer_liveliness(&self, writer: &Guid) -> Result<()> {
2320        let out = {
2321            let mut g = self.lock()?;
2322            let inner = &mut *g;
2323            let Some(kind) = inner.writers.get(writer).map(|w| w.qos.liveliness.kind) else {
2324                return Ok(());
2325            };
2326            if kind == LivelinessKind::Automatic {
2327                return Ok(());
2328            }
2329            inner.local_writer_asserted(*writer, Instant::now());
2330            match inner.writers.get_mut(writer) {
2331                Some(w) if kind == LivelinessKind::ManualByTopic => w.rtps.liveliness_heartbeat(),
2332                _ => Vec::new(),
2333            }
2334        };
2335        self.flush();
2336        // Like a HEARTBEAT that is lost on the way, one that cannot be
2337        // sent (to a locator kind not supported here, say) is not an
2338        // error of the call.
2339        for o in &out {
2340            let _ = self.send(&o.bytes, &o.locators);
2341        }
2342        Ok(())
2343    }
2344
2345    /// Waits until every matched reliable reader has acknowledged every
2346    /// sample `writer` wrote, or `timeout` passes.
2347    pub(crate) fn wait_for_acknowledgments(&self, writer: &Guid, timeout: Duration) -> Result<()> {
2348        let deadline = Instant::now() + timeout;
2349        let mut g = self.lock()?;
2350        loop {
2351            match g.writers.get(writer) {
2352                None => return Ok(()),
2353                Some(w) if w.rtps.is_all_acked() => return Ok(()),
2354                Some(_) => {}
2355            }
2356            let now = Instant::now();
2357            if now >= deadline {
2358                return Err(Error::Timeout);
2359            }
2360            g = match self.acknowledged.wait_timeout(g, deadline - now) {
2361                Ok((g, _)) => g,
2362                Err(e) => e.into_inner().0,
2363            };
2364            if g.deleted {
2365                return Err(Error::AlreadyDeleted);
2366            }
2367        }
2368    }
2369}
2370
2371/// Applies SEDP match events to the local endpoints: a local writer
2372/// starts or stops sending to a remote reader, a local reliable reader
2373/// starts or stops tracking a remote writer.
2374fn apply_sedp_events(inner: &mut Inner, events: Vec<SedpEvent>, now: Instant) {
2375    for e in events {
2376        match e {
2377            SedpEvent::Matched { local, remote } => {
2378                #[cfg(feature = "security")]
2379                if let Some(sec) = &inner.security
2380                    && remote.prefix != local.prefix
2381                {
2382                    let writer = inner.writers.contains_key(&local);
2383                    let data = if writer {
2384                        inner.sedp.remote_reader(&remote)
2385                    } else {
2386                        inner.sedp.remote_writer(&remote)
2387                    };
2388                    if !data.is_some_and(|d| sec.remote_allowed(d, !writer)) {
2389                        continue;
2390                    }
2391                    sec.matched(local, remote, writer);
2392                }
2393                if let Some(w) = inner.writers.get_mut(&local) {
2394                    if w.add_match(remote) {
2395                        inner.pending.push((local, StatusMask::PUBLICATION_MATCHED));
2396                    }
2397                    if let Some(d) = inner.sedp.remote_reader(&remote) {
2398                        w.rtps.add_matched_reader(
2399                            remote,
2400                            MatchedReader {
2401                                unicast: d.unicast_locators.clone(),
2402                                multicast: d.multicast_locators.clone(),
2403                                reliable: d.reliability.kind == ReliabilityKind::Reliable,
2404                                // A TRANSIENT_LOCAL writer sends what it
2405                                // kept to the readers that ask for it.
2406                                history: w.transient_local()
2407                                    && d.durability >= DurabilityKind::TransientLocal,
2408                            },
2409                        );
2410                    }
2411                } else if let Some(r) = inner.readers.get_mut(&local) {
2412                    let mut k = StatusMask::NONE;
2413                    if r.add_match(remote) {
2414                        k |= StatusMask::SUBSCRIPTION_MATCHED;
2415                    }
2416                    if let Some(d) = inner.sedp.remote_writer(&remote)
2417                        && r.writer_matched(
2418                            remote,
2419                            d.liveliness.kind,
2420                            d.liveliness.lease_duration.to_std(),
2421                            now,
2422                        )
2423                    {
2424                        k |= StatusMask::LIVELINESS_CHANGED;
2425                    }
2426                    if !k.is_empty() {
2427                        inner.pending.push((local, k));
2428                    }
2429                    if let (Some(rtps), Some(d)) =
2430                        (r.rtps.as_mut(), inner.sedp.remote_writer(&remote))
2431                    {
2432                        rtps.add_writer(
2433                            remote,
2434                            d.unicast_locators.clone(),
2435                            d.multicast_locators.clone(),
2436                            now,
2437                        );
2438                    }
2439                }
2440            }
2441            SedpEvent::Unmatched { local, remote } => {
2442                #[cfg(feature = "security")]
2443                if let Some(sec) = &inner.security {
2444                    sec.unmatched(local, remote);
2445                }
2446                if let Some(w) = inner.writers.get_mut(&local) {
2447                    if w.remove_match(&remote) {
2448                        inner.pending.push((local, StatusMask::PUBLICATION_MATCHED));
2449                    }
2450                    w.rtps.remove_reader(&remote);
2451                    w.trim();
2452                } else if let Some(r) = inner.readers.get_mut(&local) {
2453                    r.fragments.remove(&remote);
2454                    let k = r.writer_removed(&remote);
2455                    if !k.is_empty() {
2456                        inner.pending.push((local, k));
2457                    }
2458                    if let Some(rtps) = r.rtps.as_mut() {
2459                        rtps.remove_writer(&remote);
2460                    }
2461                }
2462            }
2463            SedpEvent::IncompatibleQos {
2464                local, policies, ..
2465            } => {
2466                if let Some(w) = inner.writers.get_mut(&local) {
2467                    w.incompatible.add(&policies);
2468                    inner
2469                        .pending
2470                        .push((local, StatusMask::OFFERED_INCOMPATIBLE_QOS));
2471                } else if let Some(r) = inner.readers.get_mut(&local) {
2472                    r.incompatible.add(&policies);
2473                    inner
2474                        .pending
2475                        .push((local, StatusMask::REQUESTED_INCOMPATIBLE_QOS));
2476                }
2477            }
2478            SedpEvent::InconsistentTopic { local, .. } => {
2479                let topic = if let Some(w) = inner.writers.get(&local) {
2480                    Some(w.data.topic_name.clone())
2481                } else {
2482                    inner.readers.get(&local).map(|r| r.data.topic_name.clone())
2483                };
2484                if let Some(topic) = topic {
2485                    inner
2486                        .inconsistent_topics
2487                        .entry(topic.clone())
2488                        .or_default()
2489                        .add();
2490                    inner.pending_topics.push(topic);
2491                }
2492            }
2493            _ => {}
2494        }
2495    }
2496    request_missing_types(inner);
2497}
2498
2499/// Asks the participants whose endpoints announced types whose TypeObjects
2500/// are missing for them (TypeLookup getTypes, DDS-XTypes 1.3, 7.6.3.3.4),
2501/// with the other missing types their TypeInformation lists. When the
2502/// TypeInformation does not list all the types the type depends on, asks
2503/// for those too (getTypeDependencies).
2504fn request_missing_types(inner: &mut Inner) {
2505    let mut asks: BTreeMap<GuidPrefix, Vec<TypeIdentifier>> = BTreeMap::new();
2506    let mut dependencies: BTreeMap<GuidPrefix, Vec<TypeIdentifier>> = BTreeMap::new();
2507    for (id, remote) in inner.sedp.unresolved_types() {
2508        let registry = inner.sedp.registry();
2509        let info = inner
2510            .sedp
2511            .remote_writer(&remote)
2512            .or_else(|| inner.sedp.remote_reader(&remote))
2513            .and_then(|d| d.type_information.as_ref());
2514        let mut ids = vec![id];
2515        if let Some(info) = info {
2516            ids.extend(registry.missing(info));
2517            let m = &info.minimal;
2518            let listed = i32::try_from(m.dependent_typeids.len()).unwrap_or(i32::MAX);
2519            let root = &m.typeid_with_size.type_id;
2520            if m.dependent_typeid_count > listed
2521                && inner.type_requests.insert((root.clone(), remote.prefix))
2522            {
2523                dependencies
2524                    .entry(remote.prefix)
2525                    .or_default()
2526                    .push(root.clone());
2527            }
2528        }
2529        for id in ids {
2530            // A type of a strongly connected component is asked for as the
2531            // component (DDS-XTypes 1.3, 7.6.3.3.4.2).
2532            let id = id.scc_identifier().unwrap_or(id);
2533            if !registry.knows(&id) && inner.type_requests.insert((id.clone(), remote.prefix)) {
2534                asks.entry(remote.prefix).or_default().push(id);
2535            }
2536        }
2537    }
2538    for (server, type_ids) in asks {
2539        inner
2540            .typelookup
2541            .request(server, TypeLookupCall::GetTypes(GetTypesIn { type_ids }));
2542    }
2543    for (server, type_ids) in dependencies {
2544        inner.typelookup.request(
2545            server,
2546            TypeLookupCall::GetTypeDependencies(GetTypeDependenciesIn {
2547                type_ids,
2548                continuation_point: None,
2549            }),
2550        );
2551    }
2552}
2553
2554/// Asks `server` for the COMPLETE TypeObjects of the type of `info` and
2555/// of those it depends on that are missing, for
2556/// [`DomainParticipant::discover_topic_type`]; and for the types it
2557/// depends on when `info` does not list them all.
2558fn request_complete_types(inner: &mut Inner, server: GuidPrefix, info: &TypeInformation) {
2559    let c = &info.complete;
2560    let root = &c.typeid_with_size.type_id;
2561    let registry = inner.sedp.registry();
2562    let requests = &mut inner.type_requests;
2563    let type_ids: Vec<TypeIdentifier> = std::iter::once(&c.typeid_with_size)
2564        .chain(&c.dependent_typeids)
2565        .map(|t| {
2566            t.type_id
2567                .scc_identifier()
2568                .unwrap_or_else(|| t.type_id.clone())
2569        })
2570        .filter(|id| !registry.knows(id))
2571        .filter(|id| requests.insert((id.clone(), server)))
2572        .collect();
2573    let listed = i32::try_from(c.dependent_typeids.len()).unwrap_or(i32::MAX);
2574    let dependencies = c.dependent_typeid_count > listed
2575        && inner.dependency_requests.insert((root.clone(), server));
2576    if !type_ids.is_empty() {
2577        inner
2578            .typelookup
2579            .request(server, TypeLookupCall::GetTypes(GetTypesIn { type_ids }));
2580    }
2581    if dependencies {
2582        inner.typelookup.request(
2583            server,
2584            TypeLookupCall::GetTypeDependencies(GetTypeDependenciesIn {
2585                type_ids: vec![root.clone()],
2586                continuation_point: None,
2587            }),
2588        );
2589    }
2590}
2591
2592/// Takes in a TypeLookup reply: keeps the TypeObjects it brings and
2593/// matches again the endpoints that waited for them, or asks for the
2594/// types it says a type depends on.
2595fn type_lookup_replied(inner: &mut Inner, r: TypeLookupReplied, now: Instant) {
2596    match r.reply.data {
2597        TypeLookupReturn::GetTypes(Ok(out)) => {
2598            // Each TypeObject is checked against its TypeIdentifier.
2599            let added = inner.sedp.registry_mut().add_pairs(&out.types).unwrap_or(0);
2600            inner.learnt_types += added;
2601            if added > 0 {
2602                let events = inner.sedp.rematch_unresolved();
2603                apply_sedp_events(inner, events, now);
2604            }
2605        }
2606        TypeLookupReturn::GetTypeDependencies(Ok(out)) if r.call.is_some() => {
2607            let registry = inner.sedp.registry();
2608            let type_ids: Vec<TypeIdentifier> = out
2609                .dependent_typeids
2610                .into_iter()
2611                .map(|t| t.type_id.scc_identifier().unwrap_or(t.type_id))
2612                .filter(|id| !registry.knows(id))
2613                .collect();
2614            let type_ids: Vec<TypeIdentifier> = type_ids
2615                .into_iter()
2616                .filter(|id| inner.type_requests.insert((id.clone(), r.server)))
2617                .collect();
2618            if !type_ids.is_empty() {
2619                inner
2620                    .typelookup
2621                    .request(r.server, TypeLookupCall::GetTypes(GetTypesIn { type_ids }));
2622            }
2623        }
2624        _ => {}
2625    }
2626}
2627
2628/// A DDS domain participant (DDS 1.4, 2.2.2.2.1): the entry point that
2629/// creates topics, publishers and subscribers in one domain.
2630///
2631/// It runs a thread for discovery (SPDP and SEDP) and for receiving data.
2632/// Dropping the participant stops the thread; writers and readers made
2633/// from it stop working then.
2634pub struct DomainParticipant {
2635    shared: Arc<Shared>,
2636    thread: Option<JoinHandle<()>>,
2637    /// The thread that publishes the messages of the security logging
2638    /// plugin, when they are distributed.
2639    #[cfg(feature = "security")]
2640    log_thread: Option<JoinHandle<()>>,
2641    /// The thread that asks OCSP again for the statuses, and what stops
2642    /// it.
2643    #[cfg(feature = "security")]
2644    ocsp_thread: Option<(JoinHandle<()>, std::sync::mpsc::Sender<()>)>,
2645}
2646
2647impl std::fmt::Debug for DomainParticipant {
2648    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2649        f.debug_struct("DomainParticipant")
2650            .field("domain_id", &self.shared.domain_id)
2651            .field("guid_prefix", &self.shared.prefix)
2652            .finish()
2653    }
2654}
2655
2656impl DomainParticipant {
2657    /// Joins a domain with the default settings.
2658    pub fn new(domain_id: u32) -> Result<Self> {
2659        Self::with_config(ParticipantConfig::new(domain_id))
2660    }
2661
2662    /// Joins a domain.
2663    pub fn with_config(config: ParticipantConfig) -> Result<Self> {
2664        let domain_id = config.udp.domain_id;
2665        let (transport, incoming) = UdpTransport::open(&config.udp)?;
2666        #[allow(unused_mut)]
2667        let mut prefix = GuidPrefix::generate(VENDOR_ID);
2668        #[cfg(feature = "security")]
2669        let security = match &config.security {
2670            Some(c) => {
2671                let s = Security::new(
2672                    c,
2673                    domain_id,
2674                    prefix,
2675                    SedpConfig::default().writer,
2676                    SedpConfig::default().reader,
2677                )?;
2678                prefix = s.prefix();
2679                Some(Arc::new(s))
2680            }
2681            None => None,
2682        };
2683        let mut data = ParticipantData::new(prefix, VENDOR_ID);
2684        data.domain_id = Some(domain_id);
2685        data.available_builtin_endpoints.0 |=
2686            Sedp::BUILTIN_ENDPOINTS | Wlp::BUILTIN_ENDPOINTS | TypeLookup::BUILTIN_ENDPOINTS;
2687        data.metatraffic_unicast_locators = transport.discovery_unicast_locators();
2688        data.metatraffic_multicast_locators = transport.discovery_multicast_locators();
2689        data.default_unicast_locators = transport.user_unicast_locators();
2690        data.default_multicast_locators = transport.user_multicast_locators();
2691        #[cfg(feature = "shm")]
2692        let shm = if config.shared_memory {
2693            // Without shared memory (no /dev/shm, say), UDP alone.
2694            rustorb_rtps::shm::ShmTransport::open(
2695                &rustorb_rtps::shm::ShmConfig::default(),
2696                prefix,
2697                transport.injector(),
2698            )
2699            .ok()
2700        } else {
2701            None
2702        };
2703        #[cfg(feature = "shm")]
2704        if let Some(shm) = &shm {
2705            data.metatraffic_unicast_locators
2706                .push(shm.metatraffic_locator());
2707            data.default_unicast_locators.push(shm.user_locator());
2708        }
2709        data.lease_duration = rustorb_rtps::Duration::from_std(config.lease_duration);
2710        data.user_data = config.user_data.clone();
2711        #[cfg(feature = "security")]
2712        if let Some(s) = &security {
2713            s.announce(&mut data);
2714        }
2715        let mut spdp_config = SpdpConfig::new(domain_id, transport.discovery_multicast_locators());
2716        spdp_config.announce_period = config.announce_period;
2717        let inner = Inner {
2718            spdp: Spdp::new(data, spdp_config),
2719            sedp: Sedp::new(prefix, VENDOR_ID, SedpConfig::default()),
2720            wlp: Wlp::new(
2721                prefix,
2722                VENDOR_ID,
2723                SedpConfig::default().writer,
2724                SedpConfig::default().reader,
2725            ),
2726            wlp_secure: None,
2727            spdp_secure: None,
2728            typelookup: TypeLookup::new(
2729                prefix,
2730                VENDOR_ID,
2731                SedpConfig::default().writer,
2732                SedpConfig::default().reader,
2733            ),
2734            type_requests: HashSet::new(),
2735            dependency_requests: HashSet::new(),
2736            learnt_types: 0,
2737            next_automatic: None,
2738            manual_pending: false,
2739            next_manual: Instant::now(),
2740            persistence_directory: config.effective_persistence_directory(),
2741            writer_config: config.writer,
2742            reader_config: config.reader,
2743            next_entity: 1,
2744            writers: HashMap::new(),
2745            readers: HashMap::new(),
2746            deleted: false,
2747            pending: Vec::new(),
2748            types: HashMap::new(),
2749            dynamic_types: HashMap::new(),
2750            inconsistent_topics: HashMap::new(),
2751            pending_topics: Vec::new(),
2752            topic_listeners: HashMap::new(),
2753            listener: None,
2754            #[cfg(feature = "security")]
2755            security: security.clone(),
2756        };
2757        #[cfg(feature = "security")]
2758        let inner = {
2759            let mut inner = inner;
2760            if let Some(s) = &inner.security {
2761                if s.discovery_protected() {
2762                    inner.sedp.enable_secure();
2763                    let mut secure = SpdpSecure::new(
2764                        prefix,
2765                        VENDOR_ID,
2766                        SedpConfig::default().writer,
2767                        SedpConfig::default().reader,
2768                    );
2769                    secure.write(inner.spdp.local());
2770                    inner.spdp_secure = Some(secure);
2771                }
2772                if s.liveliness_protected() {
2773                    inner.wlp_secure = Some(Wlp::new_secure(
2774                        prefix,
2775                        VENDOR_ID,
2776                        SedpConfig::default().writer,
2777                        SedpConfig::default().reader,
2778                    ));
2779                }
2780            }
2781            inner
2782        };
2783        let shared = Arc::new_cyclic(|this| Shared {
2784            this: this.clone(),
2785            waitsets: Mutex::new(Vec::new()),
2786            transport,
2787            #[cfg(feature = "shm")]
2788            shm,
2789            prefix,
2790            domain_id,
2791            inner: Mutex::new(inner),
2792            data_arrived: Condvar::new(),
2793            acknowledged: Condvar::new(),
2794            stop: AtomicBool::new(false),
2795            drop_one_in: config.drop_one_in.filter(|n| *n > 0),
2796            #[cfg(feature = "security")]
2797            security,
2798            drop_state: AtomicU64::new(
2799                u64::from_le_bytes(prefix.0[4..12].try_into().expect("8 bytes")) | 1,
2800            ),
2801        });
2802        let s = shared.clone();
2803        let thread = std::thread::Builder::new()
2804            .name(format!("rustorb-dds-{domain_id}"))
2805            .spawn(move || run(s, incoming))?;
2806        #[allow(unused_mut)]
2807        let mut participant = DomainParticipant {
2808            shared,
2809            thread: Some(thread),
2810            #[cfg(feature = "security")]
2811            log_thread: None,
2812            #[cfg(feature = "security")]
2813            ocsp_thread: None,
2814        };
2815        #[cfg(feature = "security")]
2816        participant.start_security_log()?;
2817        #[cfg(feature = "security")]
2818        participant.start_ocsp_refresh()?;
2819        Ok(participant)
2820    }
2821
2822    /// With OCSP and a refresh period: a thread that asks again, each
2823    /// period, for this participant's status and those of its
2824    /// authenticated peers, and revokes the peers found revoked.
2825    #[cfg(feature = "security")]
2826    fn start_ocsp_refresh(&mut self) -> Result<()> {
2827        let Some(period) = self.shared.security.as_ref().and_then(|s| s.ocsp_refresh()) else {
2828            return Ok(());
2829        };
2830        let (tx, rx) = std::sync::mpsc::channel::<()>();
2831        let shared = self.shared.clone();
2832        let t = std::thread::Builder::new()
2833            .name(format!("rustorb-dds-{}-ocsp", self.shared.domain_id))
2834            .spawn(move || {
2835                while let Err(std::sync::mpsc::RecvTimeoutError::Timeout) = rx.recv_timeout(period)
2836                {
2837                    let Some(sec) = shared.security.clone() else {
2838                        return;
2839                    };
2840                    for prefix in sec.check_ocsp() {
2841                        let _ = revoke(&shared, &sec, prefix);
2842                    }
2843                }
2844            })?;
2845        self.ocsp_thread = Some((t, tx));
2846        Ok(())
2847    }
2848
2849    /// With the logging plugin of DDS Security distributing its messages
2850    /// (10.6): a writer of [`LOG_TOPIC`](crate::security_log::LOG_TOPIC),
2851    /// and a thread that writes there what the plugin logs.
2852    #[cfg(feature = "security")]
2853    fn start_security_log(&mut self) -> Result<()> {
2854        use crate::security_log::{BuiltinLoggingTypeV2, LOG_TOPIC};
2855        let Some(logger) = self
2856            .shared
2857            .security
2858            .as_ref()
2859            .and_then(|s| s.logger())
2860            .filter(|l| l.options().distribute)
2861            .cloned()
2862        else {
2863            return Ok(());
2864        };
2865        let topic = self.create_topic::<BuiltinLoggingTypeV2>(LOG_TOPIC)?;
2866        let writer = self.create_publisher()?.create_datawriter_with_qos(
2867            &topic,
2868            DataWriterQos {
2869                history: History::KeepLast(64),
2870                ..DataWriterQos::default()
2871            },
2872        )?;
2873        let (tx, rx) = std::sync::mpsc::channel::<BuiltinLoggingTypeV2>();
2874        logger.attach(tx);
2875        self.log_thread = Some(
2876            std::thread::Builder::new()
2877                .name(format!("rustorb-dds-{}-log", self.shared.domain_id))
2878                .spawn(move || {
2879                    for m in rx {
2880                        let _ = writer.write(&m);
2881                    }
2882                })?,
2883        );
2884        Ok(())
2885    }
2886
2887    /// The domain id.
2888    pub fn domain_id(&self) -> u32 {
2889        self.shared.domain_id
2890    }
2891
2892    /// The participant's GUID.
2893    pub fn guid(&self) -> Guid {
2894        Guid::new(self.shared.prefix, EntityId::PARTICIPANT)
2895    }
2896
2897    /// Registers the type `T` with its DDS-XTypes description
2898    /// (`register_type`, DDS-XTypes 1.3, 7.6.3.2): the writers and readers
2899    /// of `T` created afterwards announce its TypeInformation, and are
2900    /// matched with remote endpoints by type assignability rather than by
2901    /// type name (see [`crate::DataReaderQos::type_consistency`]).
2902    /// rustorb-idl writes [`DescribeType`] with `-Wbxtypes`.
2903    ///
2904    /// Registering a type again does nothing. Fails with
2905    /// [`Error::Unsupported`] for a type that has no TypeObjects (one that
2906    /// depends on itself).
2907    pub fn register_type<T: TopicType + DescribeType>(&self) -> Result<()> {
2908        let objects = TypeObjects::of::<T>()
2909            .map_err(|_| Error::Unsupported("a type that cannot be described"))?;
2910        let ty = DynamicType::new(T::describe_type());
2911        self.add_type(T::TYPE_NAME, objects, ty).map(|_| ())
2912    }
2913
2914    /// Registers a type known at run time (`register_type` with a
2915    /// DynamicType, DDS-XTypes 1.3, 7.6.3.2), under its name: as
2916    /// [`register_type`](Self::register_type) does for a type the program
2917    /// was built with. Registering the same type again does nothing; a
2918    /// different type of a name already registered fails with
2919    /// [`Error::PreconditionNotMet`].
2920    pub fn register_dynamic_type(&self, ty: &DynamicType) -> Result<()> {
2921        let objects = TypeObjects::new(ty.as_type())?;
2922        if !self.add_type(&ty.get_name(), objects, ty.clone())? {
2923            return Err(Error::PreconditionNotMet);
2924        }
2925        Ok(())
2926    }
2927
2928    /// Registers `objects` under `name`. False when another type has that
2929    /// name.
2930    fn add_type(&self, name: &str, objects: TypeObjects, ty: DynamicType) -> Result<bool> {
2931        {
2932            let mut g = self.shared.lock()?;
2933            let inner = &mut *g;
2934            if let Some(known) = inner.types.get(name) {
2935                return Ok(known.information == objects.information);
2936            }
2937            inner.sedp.registry_mut().add_type(&objects);
2938            inner.types.insert(name.to_owned(), objects);
2939            inner.dynamic_types.insert(name.to_owned(), ty);
2940            let events = inner.sedp.rematch_unresolved();
2941            apply_sedp_events(inner, events, Instant::now());
2942        }
2943        self.shared.flush();
2944        Ok(true)
2945    }
2946
2947    /// Creates a topic named `name` of a type known at run time, whose
2948    /// samples are [`DynamicData`]: its writers and readers are a
2949    /// `DynamicDataWriter` and a `DynamicDataReader` (DDS-XTypes 1.3,
2950    /// 7.5.2.12). The type is registered as by
2951    /// [`register_dynamic_type`](Self::register_dynamic_type), so that
2952    /// endpoints match by type assignability.
2953    pub fn create_dynamic_topic(&self, name: &str, ty: &DynamicType) -> Result<Topic<DynamicData>> {
2954        self.register_dynamic_type(ty)?;
2955        Ok(Topic::new(
2956            name,
2957            self.shared.clone(),
2958            Arc::new(Dynamic::new(ty)),
2959        ))
2960    }
2961
2962    /// The type of the topic `topic_name` as the other participants know
2963    /// it, for a program that was not built with it: the type of a remote
2964    /// writer (or else reader) of the topic that announced its
2965    /// TypeInformation, made from its COMPLETE TypeObjects, which the
2966    /// participant asks the remote participant for with the TypeLookup
2967    /// service (DDS-XTypes 1.3, 7.6.3.3). `None` when no such endpoint
2968    /// was discovered, or its TypeObjects did not come, within `timeout`.
2969    ///
2970    /// Then [`create_dynamic_topic`](Self::create_dynamic_topic) makes a
2971    /// topic of it, whose readers read the samples of that writer.
2972    pub fn discover_topic_type(
2973        &self,
2974        topic_name: &str,
2975        timeout: Duration,
2976    ) -> Result<Option<DynamicType>> {
2977        let deadline = Instant::now() + timeout;
2978        loop {
2979            {
2980                let mut g = self.shared.lock()?;
2981                let inner = &mut *g;
2982                let infos: Vec<(GuidPrefix, TypeInformation)> = inner
2983                    .sedp
2984                    .remote_writers()
2985                    .chain(inner.sedp.remote_readers())
2986                    .filter(|d| d.topic_name == topic_name)
2987                    .filter_map(|d| Some((d.guid.prefix, d.type_information.clone()?)))
2988                    .collect();
2989                for (_, info) in &infos {
2990                    let root = &info.complete.typeid_with_size.type_id;
2991                    if let Ok(ty) = DynamicTypeBuilderFactory::create_type_w_type_identifier(
2992                        root,
2993                        inner.sedp.registry(),
2994                    ) {
2995                        return Ok(Some(ty));
2996                    }
2997                }
2998                for (server, info) in &infos {
2999                    request_complete_types(inner, *server, info);
3000                }
3001            }
3002            self.shared.flush();
3003            if Instant::now() >= deadline {
3004                return Ok(None);
3005            }
3006            std::thread::sleep(Duration::from_millis(20));
3007        }
3008    }
3009
3010    /// How many TypeObjects of remote types this participant got from
3011    /// other participants with the TypeLookup service (DDS-XTypes 1.3,
3012    /// 7.6.3.3). It asks for them when an endpoint announces a type whose
3013    /// TypeObject it does not have, to check assignability.
3014    pub fn learnt_types(&self) -> usize {
3015        self.shared.lock_any().learnt_types
3016    }
3017
3018    /// Creates a topic of type `T`, named `name`.
3019    pub fn create_topic<T: TopicType + 'static>(&self, name: &str) -> Result<Topic<T>> {
3020        Ok(Topic::new(
3021            name,
3022            self.shared.clone(),
3023            Arc::new(Typed::<T>::new()),
3024        ))
3025    }
3026
3027    /// Creates a content filtered topic named `name` (DDS 1.4,
3028    /// 2.2.2.2.1.7): its readers get the samples of `related` that pass
3029    /// the filter `filter_expression` (DDS 1.4, Annex B; see
3030    /// [`ContentFilter`]) with `expression_parameters` for its `%n`.
3031    ///
3032    /// The filter reads the fields of the samples by their names in the
3033    /// type's description, so the type must be registered: a dynamic
3034    /// topic's is, and a [`TopicType`] needs
3035    /// [`register_type`](Self::register_type) first, or this fails with
3036    /// [`Error::PreconditionNotMet`]. A filter expression that is not
3037    /// valid for the type fails with [`Error::Dynamic`].
3038    pub fn create_contentfilteredtopic<T>(
3039        &self,
3040        name: &str,
3041        related: &Topic<T>,
3042        filter_expression: &str,
3043        expression_parameters: &[String],
3044    ) -> Result<ContentFilteredTopic<T>> {
3045        let ty = self
3046            .shared
3047            .dynamic_type(related.type_name())?
3048            .ok_or(Error::PreconditionNotMet)?;
3049        let filter = ContentFilter::new(&ty, filter_expression, expression_parameters)?;
3050        Ok(ContentFilteredTopic::new(name, related, filter))
3051    }
3052
3053    /// Creates a publisher in the default partition.
3054    pub fn create_publisher(&self) -> Result<Publisher> {
3055        self.create_publisher_with_qos(PublisherQos::default())
3056    }
3057
3058    /// Creates a publisher with the given QoS (its partitions).
3059    pub fn create_publisher_with_qos(&self, qos: PublisherQos) -> Result<Publisher> {
3060        Ok(Publisher::new(
3061            self.shared.clone(),
3062            PublisherEntity::new(qos),
3063        ))
3064    }
3065
3066    /// Creates a subscriber in the default partition.
3067    pub fn create_subscriber(&self) -> Result<Subscriber> {
3068        self.create_subscriber_with_qos(SubscriberQos::default())
3069    }
3070
3071    /// Creates a subscriber with the given QoS (its partitions).
3072    pub fn create_subscriber_with_qos(&self, qos: SubscriberQos) -> Result<Subscriber> {
3073        Ok(Subscriber::from_entity(
3074            self.shared.clone(),
3075            SubscriberEntity::new(qos),
3076        ))
3077    }
3078
3079    /// Sets the participant's listener (`set_listener`, DDS 1.4,
3080    /// 2.2.2.1.1), replacing any earlier one: it is called for the
3081    /// statuses in `mask` of its entities that their own listeners, and
3082    /// those of their publishers, subscribers or topics, do not take
3083    /// (2.2.4.3.1). See [`DomainParticipantListener`].
3084    pub fn set_listener(
3085        &self,
3086        listener: impl DomainParticipantListener + 'static,
3087        mask: StatusMask,
3088    ) {
3089        self.shared.lock_any().listener = Some((Arc::new(listener), mask));
3090    }
3091
3092    /// Removes the participant's listener.
3093    pub fn clear_listener(&self) {
3094        self.shared.lock_any().listener = None;
3095    }
3096
3097    /// Asserts the liveliness of the participant's MANUAL_BY_PARTICIPANT
3098    /// writers (`assert_liveliness`, DDS 1.4, 2.2.2.2.1.19). Writing with
3099    /// any of them does too.
3100    pub fn assert_liveliness(&self) -> Result<()> {
3101        self.shared.lock()?.participant_asserted(Instant::now());
3102        self.shared.flush();
3103        Ok(())
3104    }
3105
3106    /// The GUID prefixes of the other participants discovered.
3107    pub fn discovered_participants(&self) -> Vec<GuidPrefix> {
3108        let g = self.shared.lock_any();
3109        let mut v: Vec<GuidPrefix> = g.spdp.participants().map(|p| p.guid_prefix).collect();
3110        v.sort();
3111        v
3112    }
3113
3114    /// Revokes the identity of the authenticated participant `prefix`
3115    /// (DDS Security 1.2, on_revoke_identity, 9.3.2.12.2): communication
3116    /// with it ends and its certificate is not authenticated again. When
3117    /// the governance has `<enable_key_revision>true</enable_key_revision>`,
3118    /// the key material it had is revised as [`Self::revise_keys`] does,
3119    /// so that it cannot read what is sent from now on. Whether `prefix`
3120    /// was an authenticated participant; `PreconditionNotMet` without
3121    /// DDS Security.
3122    #[cfg(feature = "security")]
3123    pub fn revoke_participant(&self, prefix: GuidPrefix) -> Result<bool> {
3124        let sec = self
3125            .shared
3126            .security
3127            .clone()
3128            .ok_or(Error::PreconditionNotMet)?;
3129        revoke(&self.shared, &sec, prefix)
3130    }
3131
3132    /// Revises the key material of the participant and of its endpoints
3133    /// (DDS Security 1.2, revise_local_entity_keys, 9.8.9.5): the new
3134    /// revision goes to the authenticated participants matched, and is
3135    /// used once they acknowledge it or after 2 seconds. The volatile
3136    /// message endpoints keep their keys, which belong to one peer each.
3137    /// Readers keep the last 8 revisions of what they receive, and writers
3138    /// send the earlier revisions to readers that match later, for the
3139    /// changes kept in their history. The revision number of the
3140    /// participant's key material (0 without RTPS protection);
3141    /// `PreconditionNotMet` without DDS Security.
3142    #[cfg(feature = "security")]
3143    pub fn revise_keys(&self) -> Result<i32> {
3144        let sec = self
3145            .shared
3146            .security
3147            .as_ref()
3148            .ok_or(Error::PreconditionNotMet)?;
3149        Ok(sec.revise_keys(Instant::now()))
3150    }
3151}
3152
3153/// Revokes the identity of `prefix` and forgets it.
3154#[cfg(feature = "security")]
3155fn revoke(shared: &Shared, sec: &Security, prefix: GuidPrefix) -> Result<bool> {
3156    let now = Instant::now();
3157    if !sec.revoke_participant(&prefix, now) {
3158        return Ok(false);
3159    }
3160    {
3161        let mut g = shared.lock()?;
3162        participant_event(
3163            &mut g,
3164            ParticipantEvent::Removed(prefix, rustorb_rtps::spdp::RemovalReason::Disposed),
3165            now,
3166        );
3167    }
3168    shared.flush();
3169    Ok(true)
3170}
3171
3172impl Drop for DomainParticipant {
3173    fn drop(&mut self) {
3174        #[cfg(feature = "security")]
3175        if let Some((t, stop)) = self.ocsp_thread.take() {
3176            drop(stop);
3177            let _ = t.join();
3178        }
3179        // The security log writer goes first, while the participant still
3180        // works.
3181        #[cfg(feature = "security")]
3182        if let Some(t) = self.log_thread.take() {
3183            if let Some(l) = self.shared.security.as_ref().and_then(|s| s.logger()) {
3184                l.close();
3185            }
3186            let _ = t.join();
3187        }
3188        // The authenticated participants take the deletion only from
3189        // DCPSParticipantsSecure (DDS Security 1.2, 7.5.1.6): it is
3190        // written there, and the thread is given a moment to deliver it.
3191        let disposed = {
3192            let mut g = self.shared.lock_any();
3193            g.spdp_secure.as_mut().map(SpdpSecure::dispose)
3194        };
3195        if let Some(sn) = disposed {
3196            let deadline = Instant::now() + SECURE_DISPOSE_WAIT;
3197            while Instant::now() < deadline
3198                && !self
3199                    .shared
3200                    .lock_any()
3201                    .spdp_secure
3202                    .as_ref()
3203                    .is_none_or(|s| s.is_acked_by_all(sn))
3204            {
3205                std::thread::sleep(Duration::from_millis(5));
3206            }
3207        }
3208        self.shared.stop.store(true, Ordering::Relaxed);
3209        if let Some(t) = self.thread.take() {
3210            let _ = t.join();
3211        }
3212        let mut g = self.shared.lock_any();
3213        g.deleted = true;
3214        // The files of PERSISTENT writers are let go of now, for the
3215        // writers of a participant created next, rather than when the
3216        // last handle of an entity of this one is dropped.
3217        for w in g.writers.values_mut() {
3218            w.store = None;
3219        }
3220        // Tell the others at once, rather than letting the lease run out
3221        // (8.5.3.1).
3222        let (bytes, to) = g.spdp.dispose();
3223        let to = to.to_vec();
3224        drop(g);
3225        let _ = self.shared.send(&bytes, &to);
3226        self.shared.data_arrived.notify_all();
3227        self.shared.acknowledged.notify_all();
3228        self.shared.wake_waitsets();
3229    }
3230}
3231
3232/// How long deleting a participant waits for its dispose on
3233/// DCPSParticipantsSecure to be acknowledged.
3234const SECURE_DISPOSE_WAIT: Duration = Duration::from_millis(300);
3235
3236/// The longest the thread sleeps, so that it sees the stop flag.
3237const MAX_WAIT: Duration = Duration::from_millis(50);
3238
3239fn run(shared: Arc<Shared>, incoming: UdpIncoming) {
3240    while !shared.stop.load(Ordering::Relaxed) {
3241        let wait = {
3242            let g = shared.lock_any();
3243            let manual = g.manual_pending.then_some(g.next_manual);
3244            let next = [
3245                g.spdp.next_deadline(),
3246                g.sedp.next_deadline(),
3247                g.wlp.next_deadline(),
3248                g.wlp_secure.as_ref().and_then(Wlp::next_deadline),
3249                g.spdp_secure.as_ref().and_then(SpdpSecure::next_deadline),
3250                g.typelookup.next_deadline(),
3251                g.next_automatic,
3252                manual,
3253                #[cfg(feature = "security")]
3254                g.security.as_ref().and_then(|s| s.next_deadline()),
3255            ]
3256            .into_iter()
3257            .chain(g.writers.values().map(|w| w.rtps.next_deadline()))
3258            .chain(
3259                g.readers
3260                    .values()
3261                    .map(|r| r.rtps.as_ref().and_then(|r| r.next_deadline())),
3262            )
3263            .flatten()
3264            .min();
3265            next.map_or(MAX_WAIT, |t| {
3266                t.saturating_duration_since(Instant::now()).min(MAX_WAIT)
3267            })
3268        };
3269        let mut datagrams = Vec::new();
3270        if let Some(d) = incoming.recv_timeout(wait) {
3271            datagrams.push(d);
3272            while let Some(d) = incoming.try_recv() {
3273                datagrams.push(d);
3274            }
3275        }
3276        step(&shared, datagrams);
3277    }
3278}
3279
3280/// Handles received datagrams and sends what discovery has due.
3281fn step(shared: &Shared, datagrams: Vec<Datagram>) {
3282    let now = Instant::now();
3283    let mut out: Vec<(Vec<u8>, Vec<Locator>)> = Vec::new();
3284    {
3285        let mut g = shared.lock_any();
3286        let inner = &mut *g;
3287        let mut acked = false;
3288        for d in datagrams {
3289            #[cfg(feature = "security")]
3290            let d = match &inner.security {
3291                Some(sec) => match sec.decode(&d.data) {
3292                    Some(b) => {
3293                        let b = b.into_owned();
3294                        if matches!(
3295                            d.channel,
3296                            Channel::DiscoveryMulticast | Channel::DiscoveryUnicast
3297                        ) {
3298                            sec.handle_discovery(&b, now);
3299                        }
3300                        Datagram { data: b, ..d }
3301                    }
3302                    None => continue,
3303                },
3304                None => d,
3305            };
3306            match d.channel {
3307                Channel::DiscoveryMulticast | Channel::DiscoveryUnicast => {
3308                    for e in inner.spdp.handle_message(&d.data, now) {
3309                        participant_event(inner, e, now);
3310                    }
3311                    let events = inner.sedp.handle_message(&d.data, now);
3312                    apply_sedp_events(inner, events, now);
3313                    for a in inner.wlp.handle_message(&d.data, now) {
3314                        inner.remote_participant_asserted(a.participant, a.kind, now);
3315                    }
3316                    if let Some(w) = inner.wlp_secure.as_mut() {
3317                        for a in w.handle_message(&d.data, now) {
3318                            inner.remote_participant_asserted(a.participant, a.kind, now);
3319                        }
3320                    }
3321                    if let Some(s) = inner.spdp_secure.as_mut() {
3322                        for e in s.handle_message(&d.data, now) {
3323                            if let Some(e) = inner.spdp.handle_secure(e, now) {
3324                                participant_event(inner, e, now);
3325                            }
3326                        }
3327                    }
3328                    let replies =
3329                        inner
3330                            .typelookup
3331                            .handle_message(&d.data, now, inner.sedp.registry());
3332                    for r in replies {
3333                        type_lookup_replied(inner, r, now);
3334                    }
3335                }
3336                Channel::UserMulticast | Channel::UserUnicast => {
3337                    if shared.should_drop() {
3338                        continue;
3339                    }
3340                    acked |= user_traffic(shared.prefix, inner, &d.data, now);
3341                }
3342            }
3343        }
3344        for e in inner.spdp.remove_expired(now) {
3345            participant_event(inner, e, now);
3346        }
3347        inner.check_timers(now);
3348        if let Some((bytes, to)) = inner.spdp.poll_announce(now) {
3349            out.push((bytes, to.to_vec()));
3350        }
3351        for o in inner.sedp.poll(now) {
3352            out.push((o.bytes, o.locators));
3353        }
3354        for o in inner.wlp.poll(now) {
3355            out.push((o.bytes, o.locators));
3356        }
3357        if let Some(w) = inner.wlp_secure.as_mut() {
3358            for o in w.poll(now) {
3359                out.push((o.bytes, o.locators));
3360            }
3361        }
3362        if let Some(s) = inner.spdp_secure.as_mut() {
3363            for o in s.poll(now) {
3364                out.push((o.bytes, o.locators));
3365            }
3366        }
3367        for o in inner.typelookup.poll(now) {
3368            out.push((o.bytes, o.locators));
3369        }
3370        #[cfg(feature = "security")]
3371        if let Some(sec) = inner.security.clone() {
3372            let (o, events) = sec.poll(now);
3373            out.extend(o.into_iter().map(|o| (o.bytes, o.locators)));
3374            for e in events {
3375                match e {
3376                    PeerEvent::Ready(p) => participant_ready(inner, &p, now),
3377                }
3378            }
3379        }
3380        for w in inner.writers.values_mut() {
3381            for o in w.rtps.poll(now) {
3382                out.push((o.bytes, o.locators));
3383            }
3384            w.trim();
3385        }
3386        for r in inner.readers.values_mut() {
3387            if let Some(rtps) = r.rtps.as_mut() {
3388                for o in rtps.poll(now) {
3389                    out.push((o.bytes, o.locators));
3390                }
3391            }
3392        }
3393        if acked {
3394            shared.acknowledged.notify_all();
3395        }
3396    }
3397    for (bytes, to) in out {
3398        // Discovery and reliable traffic are repeated, so a datagram
3399        // that cannot be sent now is sent again later.
3400        let _ = shared.send(&bytes, &to);
3401    }
3402    shared.flush();
3403}
3404
3405fn participant_event(inner: &mut Inner, e: ParticipantEvent, now: Instant) {
3406    match e {
3407        ParticipantEvent::Discovered(p) | ParticipantEvent::Updated(p) => {
3408            #[cfg(feature = "security")]
3409            if let Some(sec) = &inner.security
3410                && !sec.participant_discovered(&p, now)
3411            {
3412                return;
3413            }
3414            participant_ready(inner, &p, now);
3415        }
3416        ParticipantEvent::Removed(prefix, _) => {
3417            #[cfg(feature = "security")]
3418            if let Some(sec) = &inner.security {
3419                sec.participant_removed(&prefix);
3420            }
3421            inner.wlp.remove_participant(&prefix);
3422            if let Some(w) = inner.wlp_secure.as_mut() {
3423                w.remove_participant(&prefix);
3424            }
3425            if let Some(s) = inner.spdp_secure.as_mut() {
3426                s.remove_participant(&prefix);
3427            }
3428            inner.typelookup.remove_participant(&prefix);
3429            inner.type_requests.retain(|(_, p)| *p != prefix);
3430            let events = inner.sedp.remove_participant(&prefix);
3431            apply_sedp_events(inner, events, now);
3432        }
3433    }
3434}
3435
3436/// Discovery goes on with a participant (after authentication, with
3437/// security).
3438fn participant_ready(inner: &mut Inner, p: &ParticipantData, now: Instant) {
3439    inner.sedp.add_participant(p, now);
3440    inner.wlp.add_participant(p, now);
3441    if let Some(w) = inner.wlp_secure.as_mut() {
3442        w.add_participant(p, now);
3443    }
3444    if let Some(s) = inner.spdp_secure.as_mut() {
3445        s.add_participant(p, now);
3446    }
3447    inner.typelookup.add_participant(p, now);
3448}
3449
3450/// Handles a user-traffic message: DATA, DATA_FRAG, GAP, HEARTBEAT and
3451/// HEARTBEAT_FRAG for the local readers, ACKNACK and NACK_FRAG for the
3452/// local writers. Returns whether some writer got an ACKNACK.
3453fn user_traffic(local: GuidPrefix, inner: &mut Inner, bytes: &[u8], now: Instant) -> bool {
3454    let mut acked = false;
3455    let Some((_, received)) = receive(bytes, local) else {
3456        return false;
3457    };
3458    for r in received {
3459        let src = r.source_prefix;
3460        match r.submessage {
3461            Submessage::AckNack(a) => {
3462                if let Some(w) = inner.writers.get_mut(&Guid::new(local, a.writer_id)) {
3463                    w.rtps.handle_acknack(Guid::new(src, a.reader_id), &a, now);
3464                    w.trim();
3465                    acked = true;
3466                }
3467            }
3468            Submessage::Data(d) => {
3469                let writer = Guid::new(src, d.writer_id);
3470                inner.remote_writer_asserted(&writer, now);
3471                for_readers(inner, d.reader_id, |st| match st.rtps.as_mut() {
3472                    Some(rtps) => rtps.handle_data(writer, &d, r.timestamp),
3473                    None => vec![Change {
3474                        writer,
3475                        sequence_number: d.writer_sn,
3476                        inline_qos: d.inline_qos.clone(),
3477                        payload: d.serialized_payload.clone(),
3478                        timestamp: r.timestamp,
3479                    }],
3480                });
3481            }
3482            Submessage::DataFrag(d) => {
3483                let writer = Guid::new(src, d.writer_id);
3484                inner.remote_writer_asserted(&writer, now);
3485                for_readers(inner, d.reader_id, |st| match st.rtps.as_mut() {
3486                    Some(rtps) => rtps.handle_data_frag(writer, &d, r.timestamp),
3487                    // Best effort: the newest incomplete samples are
3488                    // kept, and only those of matched writers.
3489                    None if st.matched.contains(&writer) => {
3490                        let limits = st.reassembly;
3491                        st.fragments
3492                            .entry(writer)
3493                            .or_insert_with(|| Reassembler::new(limits, Keep::Highest))
3494                            .add(writer, &d, r.timestamp)
3495                            .into_iter()
3496                            .collect()
3497                    }
3498                    None => Vec::new(),
3499                });
3500            }
3501            Submessage::HeartbeatFrag(h) => {
3502                let writer = Guid::new(src, h.writer_id);
3503                for_readers(inner, h.reader_id, |st| {
3504                    if let Some(rtps) = st.rtps.as_mut() {
3505                        rtps.handle_heartbeat_frag(writer, &h, now);
3506                    }
3507                    Vec::new()
3508                });
3509            }
3510            Submessage::NackFrag(n) => {
3511                if let Some(w) = inner.writers.get_mut(&Guid::new(local, n.writer_id)) {
3512                    w.rtps.handle_nackfrag(Guid::new(src, n.reader_id), &n, now);
3513                }
3514            }
3515            Submessage::Gap(gap) => {
3516                let writer = Guid::new(src, gap.writer_id);
3517                for_readers(inner, gap.reader_id, |st| match st.rtps.as_mut() {
3518                    Some(rtps) => rtps.handle_gap(writer, &gap),
3519                    None => Vec::new(),
3520                });
3521            }
3522            Submessage::Heartbeat(h) => {
3523                let writer = Guid::new(src, h.writer_id);
3524                if h.liveliness_flag {
3525                    // MANUAL_BY_TOPIC assert_liveliness (8.7.2.2.3).
3526                    inner.remote_writer_asserted(&writer, now);
3527                }
3528                for_readers(inner, h.reader_id, |st| match st.rtps.as_mut() {
3529                    Some(rtps) => rtps.handle_heartbeat(writer, &h, now),
3530                    None => Vec::new(),
3531                });
3532            }
3533            _ => {}
3534        }
3535    }
3536    acked
3537}
3538
3539/// Runs `f` on the local readers a submessage is for (`reader_id`, or
3540/// every reader when it is `ENTITYID_UNKNOWN`) and keeps the changes it
3541/// returns.
3542fn for_readers(
3543    inner: &mut Inner,
3544    reader_id: EntityId,
3545    mut f: impl FnMut(&mut ReaderState) -> Vec<Change>,
3546) {
3547    for (rg, st) in inner.readers.iter_mut() {
3548        if reader_id != EntityId::UNKNOWN && reader_id != rg.entity_id {
3549            continue;
3550        }
3551        for c in f(st) {
3552            let Some(c) = st.incoming(c) else {
3553                continue;
3554            };
3555            let k = st.accept(c);
3556            if !k.is_empty() {
3557                inner.pending.push((*rg, k));
3558            }
3559        }
3560    }
3561}
3562
3563#[cfg(test)]
3564mod padding_tests {
3565    use super::drop_missing_padding;
3566
3567    #[test]
3568    fn padding_counted_but_not_sent_is_dropped() {
3569        // OpenDDS: "Hello, world!" (22 octets of data), 2 counted, none sent.
3570        let mut p = vec![0, 1, 0, 2, 1, 0, 0, 0, 14, 0, 0, 0];
3571        p.extend_from_slice(b"Hello, world!\0");
3572        drop_missing_padding(&mut p);
3573        assert_eq!(p[3], 0);
3574        // The same with the 2 octets sent: kept as it is.
3575        let mut q = vec![0, 1, 0, 2, 1, 0, 0, 0, 14, 0, 0, 0];
3576        q.extend_from_slice(b"Hello, world!\0\0\0");
3577        drop_missing_padding(&mut q);
3578        assert_eq!(q[3], 2);
3579    }
3580}
3581
3582#[cfg(test)]
3583mod property_tests {
3584    use super::*;
3585
3586    #[test]
3587    fn properties_without_dds_sec_are_ignored() {
3588        let mut c = ParticipantConfig::new(0);
3589        c.set_properties([("some.vendor.thing", "1")]).unwrap();
3590        #[cfg(feature = "security")]
3591        assert!(c.security.is_none());
3592    }
3593
3594    #[cfg(not(feature = "security"))]
3595    #[test]
3596    fn dds_sec_properties_need_the_feature() {
3597        let mut c = ParticipantConfig::new(0);
3598        let e = c
3599            .set_properties([("dds.sec.auth.identity_ca", "file:ca.pem")])
3600            .unwrap_err();
3601        assert!(matches!(e, Error::Unsupported(_)));
3602    }
3603
3604    #[cfg(feature = "security")]
3605    #[test]
3606    fn dds_sec_properties_make_the_security_config() {
3607        let mut c = ParticipantConfig::new(0);
3608        let e = c
3609            .set_properties([("dds.sec.auth.identity_ca", "file:ca.pem")])
3610            .unwrap_err();
3611        assert!(e.to_string().contains("dds.sec.access.permissions"), "{e}");
3612        let props: Vec<(&str, String)> = SecurityConfig::PROPERTIES
3613            .iter()
3614            .map(|n| (*n, format!("file:{n}")))
3615            .collect();
3616        c.set_properties(props.iter().map(|(n, v)| (*n, v.as_str())))
3617            .unwrap();
3618        let s = c.security.unwrap();
3619        assert_eq!(s.identity_ca, "file:dds.sec.auth.identity_ca");
3620        assert_eq!(s.permissions, "file:dds.sec.access.permissions");
3621    }
3622}