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