1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
5use std::io;
6use std::net::Ipv4Addr;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak};
9use std::thread::JoinHandle;
10use std::time::{Duration, Instant};
11
12use rustorb_rtps::frag::{Keep, Reassembler, ReassemblyLimits};
13use rustorb_rtps::pl::pid;
14use rustorb_rtps::qos::{DurabilityKind, LivelinessKind, ReliabilityKind};
15use rustorb_rtps::receiver::receive;
16use rustorb_rtps::reliable::{
17 Change, MatchedReader, ReaderConfig, ReliableReader, ReliableWriter, WriterConfig,
18};
19use rustorb_rtps::sedp::{EndpointData, Match, Sedp, SedpConfig, SedpEvent, match_endpoints};
20use rustorb_rtps::spdp::{ParticipantData, ParticipantEvent, Spdp, SpdpConfig};
21use rustorb_rtps::spdp_secure::SpdpSecure;
22use rustorb_rtps::typelookup::{TypeLookup, TypeLookupReplied};
23use rustorb_rtps::udp::{Channel, Datagram, Incoming as UdpIncoming, UdpConfig, UdpTransport};
24use rustorb_rtps::wlp::{self, Wlp};
25use rustorb_rtps::{
26 Endianness, EntityId, Guid, GuidPrefix, Locator, Parameter, ParameterList, PayloadKind,
27 SampleIdentity, SequenceNumber, SerializedPayload, Submessage, Time, VendorId,
28};
29use rustorb_typesupport::TopicType;
30use rustorb_xtypes::dynamic::{ContentFilter, DynamicData, DynamicType, DynamicTypeBuilderFactory};
31use rustorb_xtypes::type_object::{TypeIdentifier, TypeInformation};
32use rustorb_xtypes::typelookup::{
33 GetTypeDependenciesIn, GetTypesIn, TypeLookupCall, TypeLookupReturn,
34};
35use rustorb_xtypes::types::{DescribeType, TypeObjects};
36
37use crate::condition::Waker;
38use crate::error::{Error, Result};
39use crate::instance::{self, Incoming, InstanceHandle, ReaderHistory};
40use crate::listener::{
41 AnyDataReader, AnyDataWriter, DomainParticipantListener, PublisherEntity, PublisherListener,
42 SubscriberEntity, SubscriberListener, TopicListener,
43};
44use crate::persistent::{Record, Store};
45use crate::publisher::Publisher;
46use crate::qos::{DataReaderQos, DataWriterQos, History, PublisherQos, SubscriberQos};
47#[cfg(feature = "security")]
48use crate::security::{PeerEvent, Security, SecurityConfig};
49use crate::status::{
50 DeadlineMissedStatus, Deadlines, IncompatibleQosStatus, InconsistentTopicStatus,
51 LivelinessChangedStatus, LivelinessLostStatus, MatchedStatus, SampleLostStatus,
52 SampleRejectedStatus, StatusMask,
53};
54use crate::subscriber::Subscriber;
55use crate::topic::{ContentFilteredTopic, Topic};
56use crate::typed::{Dynamic, KeyOps, Typed};
57#[cfg(feature = "security")]
58use rustorb_dds_security::access::ProtectionKind;
59#[cfg(feature = "security")]
60use rustorb_dds_security::psk::{PskConfig, PskProtection};
61
62pub const VENDOR_ID: VendorId = VendorId::UNKNOWN;
65
66#[derive(Clone, Debug)]
68pub struct ParticipantConfig {
69 pub udp: UdpConfig,
71 pub announce_period: Duration,
73 pub lease_duration: Duration,
76 pub writer: WriterConfig,
79 pub reader: ReaderConfig,
82 pub drop_one_in: Option<u32>,
86 pub user_data: Vec<u8>,
90 pub shared_memory: bool,
94 pub persistence_directory: Option<std::path::PathBuf>,
100 #[cfg(feature = "security")]
104 pub security: Option<SecurityConfig>,
105 #[cfg(feature = "security")]
114 pub psk: Option<PskConfig>,
115}
116
117impl ParticipantConfig {
118 pub fn new(domain_id: u32) -> Self {
126 ParticipantConfig {
127 udp: UdpConfig::new(domain_id),
128 announce_period: Duration::from_secs(3),
129 lease_duration: Duration::from_secs(20),
130 writer: WriterConfig {
131 heartbeat_period: Duration::from_millis(200),
132 ..WriterConfig::default()
133 },
134 reader: ReaderConfig::default(),
135 drop_one_in: None,
136 user_data: Vec::new(),
137 shared_memory: true,
138 persistence_directory: None,
139 #[cfg(feature = "security")]
140 security: None,
141 #[cfg(feature = "security")]
142 psk: None,
143 }
144 }
145
146 pub const PERSISTENCE_DIRECTORY: &'static str = "rustorb.dds.persistence.directory";
148
149 pub fn effective_persistence_directory(&self) -> std::path::PathBuf {
152 self.persistence_directory
153 .clone()
154 .or_else(|| std::env::var_os("RUSTORB_DDS_PERSISTENCE_DIR").map(Into::into))
155 .unwrap_or_else(|| "rustorb-dds-persistent".into())
156 }
157
158 pub fn localhost(domain_id: u32) -> Self {
160 let mut c = Self::new(domain_id);
161 c.udp.interfaces = vec![Ipv4Addr::LOCALHOST];
162 c
163 }
164
165 #[cfg_attr(not(feature = "security"), allow(unused_mut))]
180 pub fn set_properties<'a>(
181 &mut self,
182 properties: impl IntoIterator<Item = (&'a str, &'a str)>,
183 ) -> Result<()> {
184 let mut sec: Vec<(&str, &str)> = Vec::new();
185 for (n, v) in properties {
186 if n.starts_with("dds.sec.") || n.starts_with("rustorb.dds.sec.") {
187 sec.push((n, v));
188 } else if n == Self::PERSISTENCE_DIRECTORY {
189 self.persistence_directory = Some(v.into());
190 }
191 }
192 if sec.is_empty() {
193 return Ok(());
194 }
195 #[cfg(feature = "security")]
196 {
197 let (psk, sec): (Vec<_>, Vec<_>) = sec
198 .into_iter()
199 .partition(|(n, _)| PskConfig::is_property(n));
200 let psk_props = psk
203 .iter()
204 .copied()
205 .chain(sec.iter().copied().filter(|(n, _)| {
206 *n == rustorb_dds_security::psk::DEFAULT_SYMMETRIC_CIPHER_ALGORITHM
207 }));
208 let psk_config = PskConfig::from_properties(psk_props)
209 .map_err(|e| Error::Security(format!("PSK: {e}")))?;
210 if psk_config.is_none() && !psk.is_empty() {
211 return Err(Error::Security(format!(
212 "PSK: {} is missing",
213 rustorb_dds_security::psk::SECRET_PASSPHRASE
214 )));
215 }
216 let sec: Vec<_> = sec
217 .into_iter()
218 .filter(|(n, _)| {
219 *n != rustorb_dds_security::psk::DEFAULT_SYMMETRIC_CIPHER_ALGORITHM
220 })
221 .collect();
222 if !sec.is_empty() || psk_config.is_none() {
223 self.security =
224 Some(SecurityConfig::try_from_properties(sec).map_err(Error::Security)?);
225 }
226 if psk_config.is_some() {
227 self.psk = psk_config;
228 }
229 Ok(())
230 }
231 #[cfg(not(feature = "security"))]
232 Err(Error::Unsupported(
233 "DDS Security: rustorb-dds was built without the feature `security`",
234 ))
235 }
236}
237
238pub(crate) enum ReaderEvent {
240 DataAvailable,
241 SubscriptionMatched(MatchedStatus),
242 LivelinessChanged(LivelinessChangedStatus),
243 RequestedDeadlineMissed(DeadlineMissedStatus),
244 RequestedIncompatibleQos(IncompatibleQosStatus),
245 SampleRejected(SampleRejectedStatus),
246 SampleLost(SampleLostStatus),
247}
248
249pub(crate) enum WriterEvent {
251 PublicationMatched(MatchedStatus),
252 LivelinessLost(LivelinessLostStatus),
253 OfferedDeadlineMissed(DeadlineMissedStatus),
254 OfferedIncompatibleQos(IncompatibleQosStatus),
255}
256
257pub(crate) type ReaderListener = Arc<dyn Fn(&Arc<Shared>, Guid, ReaderEvent) + Send + Sync>;
260pub(crate) type WriterListener = Arc<dyn Fn(&Arc<Shared>, Guid, WriterEvent) + Send + Sync>;
262
263type ListenerCall = Box<dyn FnOnce(&Arc<Shared>)>;
265
266fn writer_event<L: PublisherListener + ?Sized>(
269 l: &L,
270 shared: &Arc<Shared>,
271 guid: Guid,
272 ev: WriterEvent,
273) {
274 let w = AnyDataWriter {
275 shared: shared.clone(),
276 guid,
277 };
278 match ev {
279 WriterEvent::PublicationMatched(s) => l.on_publication_matched(&w, s),
280 WriterEvent::LivelinessLost(s) => l.on_liveliness_lost(&w, s),
281 WriterEvent::OfferedDeadlineMissed(s) => l.on_offered_deadline_missed(&w, s),
282 WriterEvent::OfferedIncompatibleQos(s) => l.on_offered_incompatible_qos(&w, s),
283 }
284}
285
286fn data_on_readers<L: SubscriberListener + ?Sized>(
289 l: &L,
290 shared: &Arc<Shared>,
291 sub: Arc<SubscriberEntity>,
292) {
293 l.on_data_on_readers(&Subscriber::from_entity(shared.clone(), sub));
294}
295
296fn reader_event<L: SubscriberListener + ?Sized>(
299 l: &L,
300 shared: &Arc<Shared>,
301 guid: Guid,
302 ev: ReaderEvent,
303) {
304 let r = AnyDataReader {
305 shared: shared.clone(),
306 guid,
307 };
308 match ev {
309 ReaderEvent::DataAvailable => l.on_data_available(&r),
310 ReaderEvent::SubscriptionMatched(s) => l.on_subscription_matched(&r, s),
311 ReaderEvent::LivelinessChanged(s) => l.on_liveliness_changed(&r, s),
312 ReaderEvent::RequestedDeadlineMissed(s) => l.on_requested_deadline_missed(&r, s),
313 ReaderEvent::RequestedIncompatibleQos(s) => l.on_requested_incompatible_qos(&r, s),
314 ReaderEvent::SampleRejected(s) => l.on_sample_rejected(&r, s),
315 ReaderEvent::SampleLost(s) => l.on_sample_lost(&r, s),
316 }
317}
318
319const STATUS_DISPOSED: u8 = 0x01;
321const STATUS_UNREGISTERED: u8 = 0x02;
322
323pub(crate) struct ReaderState {
324 pub(crate) data: EndpointData,
325 pub(crate) rtps: Option<ReliableReader>,
328 pub(crate) matched: BTreeSet<Guid>,
330 pub(crate) fragments: HashMap<Guid, Reassembler>,
334 pub(crate) reassembly: ReassemblyLimits,
335 pub(crate) incompatible: IncompatibleQosStatus,
337 pub(crate) liveliness: HashMap<Guid, WriterLiveliness>,
339 pub(crate) liveliness_changed: LivelinessChangedStatus,
341 pub(crate) deadlines: Deadlines,
344 pub(crate) samples: ReaderHistory,
346 pub(crate) keys: Arc<dyn KeyOps>,
347 pub(crate) matched_status: MatchedStatus,
349 pub(crate) changes: StatusMask,
352 pub(crate) enabled: StatusMask,
354 pub(crate) listener: Option<(ReaderListener, StatusMask)>,
356 pub(crate) subscriber: Option<Arc<SubscriberEntity>>,
358 pub(crate) filter: Option<ContentFilter>,
361 #[cfg(feature = "security")]
364 pub(crate) payload_security: Option<Arc<Security>>,
365 #[cfg(feature = "shm")]
368 pub(crate) pools: Option<Arc<rustorb_rtps::shm::Pools>>,
369}
370
371#[derive(Clone, Copy, Debug)]
373pub(crate) struct WriterLiveliness {
374 kind: LivelinessKind,
375 lease: Option<Duration>,
378 last: Instant,
379 alive: bool,
380}
381
382impl ReaderState {
383 fn new(
384 data: EndpointData,
385 qos: &DataReaderQos,
386 keys: Arc<dyn KeyOps>,
387 config: &ReaderConfig,
388 ) -> Self {
389 let rtps = (qos.reliability.kind == ReliabilityKind::Reliable)
390 .then(|| ReliableReader::new(data.guid, VENDOR_ID, config.clone()));
391 ReaderState {
392 data,
393 rtps,
394 matched: BTreeSet::new(),
395 fragments: HashMap::new(),
396 reassembly: config.reassembly,
397 incompatible: IncompatibleQosStatus::default(),
398 liveliness: HashMap::new(),
399 liveliness_changed: LivelinessChangedStatus::default(),
400 deadlines: Deadlines::new(qos.deadline),
401 samples: ReaderHistory::with_limits(qos.history, qos.resource_limits),
402 keys,
403 matched_status: MatchedStatus::default(),
404 changes: StatusMask::NONE,
405 enabled: StatusMask::ALL,
406 listener: None,
407 subscriber: None,
408 filter: None,
409 #[cfg(feature = "security")]
410 payload_security: None,
411 #[cfg(feature = "shm")]
412 pools: None,
413 }
414 }
415
416 fn accept(&mut self, c: Incoming) -> StatusMask {
420 if !self.matched.contains(&c.writer) {
421 return StatusMask::NONE;
422 }
423 if let (Some(f), instance::Change::Write(bytes)) = (&self.filter, &c.change) {
424 let passes =
426 DynamicData::from_payload(f.get_type(), bytes).is_ok_and(|d| f.evaluate(&d));
427 if !passes {
428 return StatusMask::NONE;
429 }
430 }
431 let h = c.instance;
432 let value = matches!(c.change, instance::Change::Write(_));
433 let rejected = self.samples.rejected_count();
434 let lost = self.samples.lost.total_count;
435 let mut changes = StatusMask::NONE;
436 if self.samples.accept(c) {
437 changes |= StatusMask::DATA_AVAILABLE;
438 if value {
439 self.deadlines.renew(h, Instant::now());
440 }
441 }
442 if self.samples.rejected_count() != rejected {
443 changes |= StatusMask::SAMPLE_REJECTED;
444 }
445 if self.samples.lost.total_count != lost {
446 changes |= StatusMask::SAMPLE_LOST;
447 }
448 changes
449 }
450
451 fn add_match(&mut self, writer: Guid) -> bool {
453 let new = self.matched.insert(writer);
454 if new {
455 self.matched_status.matched(writer);
456 }
457 new
458 }
459
460 fn remove_match(&mut self, writer: &Guid) -> bool {
462 let was = self.matched.remove(writer);
463 if was {
464 self.matched_status.unmatched(*writer);
465 }
466 was
467 }
468
469 fn writer_removed(&mut self, writer: &Guid) -> StatusMask {
473 let mut k = StatusMask::NONE;
474 if self.writer_unmatched(writer) {
475 k |= StatusMask::LIVELINESS_CHANGED;
476 }
477 if self.remove_match(writer) {
478 k |= StatusMask::SUBSCRIPTION_MATCHED;
479 if self.samples.writer_gone(writer) {
480 k |= StatusMask::DATA_AVAILABLE;
481 }
482 }
483 k
484 }
485
486 fn take_event(&mut self, k: StatusMask) -> Option<ReaderEvent> {
489 Some(match k {
490 StatusMask::DATA_AVAILABLE => ReaderEvent::DataAvailable,
491 StatusMask::SUBSCRIPTION_MATCHED => {
492 ReaderEvent::SubscriptionMatched(self.matched_status.take())
493 }
494 StatusMask::LIVELINESS_CHANGED => {
495 ReaderEvent::LivelinessChanged(self.liveliness_changed.take())
496 }
497 StatusMask::REQUESTED_DEADLINE_MISSED => {
498 ReaderEvent::RequestedDeadlineMissed(self.deadlines.missed.take())
499 }
500 StatusMask::REQUESTED_INCOMPATIBLE_QOS => {
501 ReaderEvent::RequestedIncompatibleQos(self.incompatible.take())
502 }
503 StatusMask::SAMPLE_REJECTED => {
504 ReaderEvent::SampleRejected(self.samples.take_rejected_status())
505 }
506 StatusMask::SAMPLE_LOST => ReaderEvent::SampleLost(self.samples.lost.take()),
507 _ => return None,
508 })
509 }
510
511 fn writer_matched(
514 &mut self,
515 writer: Guid,
516 kind: LivelinessKind,
517 lease: Option<Duration>,
518 now: Instant,
519 ) -> bool {
520 let l = WriterLiveliness {
521 kind,
522 lease,
523 last: now,
524 alive: true,
525 };
526 if self.liveliness.insert(writer, l).is_none() {
527 self.liveliness_changed.update(writer, None, Some(true));
528 return true;
529 }
530 false
531 }
532
533 fn writer_unmatched(&mut self, writer: &Guid) -> bool {
536 match self.liveliness.remove(writer) {
537 Some(l) => {
538 self.liveliness_changed.update(*writer, Some(l.alive), None);
539 true
540 }
541 None => false,
542 }
543 }
544
545 fn writer_asserted(&mut self, writer: &Guid, now: Instant) -> bool {
548 if let Some(l) = self.liveliness.get_mut(writer) {
549 l.last = now;
550 if !l.alive {
551 l.alive = true;
552 self.liveliness_changed
553 .update(*writer, Some(false), Some(true));
554 return true;
555 }
556 }
557 false
558 }
559
560 fn check(&mut self, now: Instant) -> StatusMask {
564 let mut changes = StatusMask::NONE;
565 let lost: Vec<Guid> = self
566 .liveliness
567 .iter()
568 .filter(|(_, l)| l.alive && l.lease.is_some_and(|d| now > l.last + d))
569 .map(|(g, _)| *g)
570 .collect();
571 for g in lost {
572 self.liveliness.get_mut(&g).expect("listed above").alive = false;
573 self.liveliness_changed.update(g, Some(true), Some(false));
574 changes |= StatusMask::LIVELINESS_CHANGED;
575 if self.samples.writer_lost(&g) {
576 changes |= StatusMask::DATA_AVAILABLE;
577 }
578 }
579 let samples = &self.samples;
580 if self.deadlines.check(now, |h| samples.is_alive(h)) {
581 changes |= StatusMask::REQUESTED_DEADLINE_MISSED;
582 }
583 changes
584 }
585
586 fn incoming(&self, c: Change) -> Option<Incoming> {
590 let mut key_hash = None;
591 let mut status = 0u8;
592 let mut related_sample_identity = None;
593 if let Some(q) = &c.inline_qos {
594 for p in &q.parameters {
595 if p.id == pid::RELATED_SAMPLE_IDENTITY {
596 related_sample_identity = SampleIdentity::from_bytes(
597 &p.value,
598 q.endianness().unwrap_or(Endianness::NATIVE),
599 )
600 .ok();
601 } else if p.id == pid::KEY_HASH && p.value.len() >= 16 {
602 key_hash = Some(InstanceHandle(p.value[..16].try_into().expect("16 octets")));
603 } else if p.id == pid::STATUS_INFO && p.value.len() >= 4 {
604 status = p.value[3];
606 }
607 }
608 }
609 let lifecycle = status & (STATUS_DISPOSED | STATUS_UNREGISTERED) != 0;
610 #[allow(unused_mut)]
611 let mut payload = c.payload;
612 #[cfg(feature = "security")]
613 if let (Some(sec), Some(p)) = (&self.payload_security, payload.as_mut()) {
614 p.bytes = sec.decode_payload(&c.writer, &p.bytes)?;
615 }
616 if let Some(p) = payload.as_mut() {
617 drop_missing_padding(&mut p.bytes);
618 }
619 let change = if lifecycle {
620 instance::Change::Lifecycle {
621 disposed: status & STATUS_DISPOSED != 0,
622 unregistered: status & STATUS_UNREGISTERED != 0,
623 }
624 } else {
625 match &payload {
626 #[cfg(feature = "shm")]
627 Some(p)
628 if p.kind == PayloadKind::Data && rustorb_rtps::shm::is_reference(&p.bytes) =>
629 {
630 instance::Change::Write(instance::Payload::Loaned(
633 self.pools.as_ref()?.resolve(&p.bytes)?,
634 ))
635 }
636 Some(p) if p.kind == PayloadKind::Data => {
637 instance::Change::Write(instance::Payload::Owned(p.bytes.clone()))
638 }
639 _ => return None,
640 }
641 };
642 let instance = if !self.keys.keyed() {
643 InstanceHandle::KEYLESS
644 } else if let Some(h) = key_hash {
645 h
646 } else {
647 match (&change, &payload) {
648 (instance::Change::Write(v), _) => self.keys.instance_of_value(v)?,
649 (_, Some(p)) => self
650 .samples
651 .last_values()
652 .find(|(_, v)| self.keys.key_matches(&p.bytes, v))
653 .map(|(h, _)| h)?,
654 _ => return None,
655 }
656 };
657 Some(Incoming {
658 writer: c.writer,
659 sequence_number: c.sequence_number,
660 source_timestamp: c.timestamp,
661 related_sample_identity,
662 instance,
663 change,
664 })
665 }
666}
667
668fn drop_missing_padding(bytes: &mut [u8]) {
674 if bytes.len() > 4 && bytes[3] & 3 != 0 && !(bytes.len() - 4).is_multiple_of(4) {
675 bytes[3] &= !3;
676 }
677}
678
679#[cfg(feature = "shm")]
683const LOANS_KEPT: usize = 8;
684
685#[cfg(feature = "shm")]
687const MAX_POOL_SLOTS: usize = 256;
688
689const OPENDDS: VendorId = VendorId([0x01, 0x03]);
691
692#[derive(Debug)]
694pub(crate) struct WriterInstance {
695 changes: VecDeque<SequenceNumber>,
697 key: Option<Vec<u8>>,
701}
702
703#[derive(Debug)]
705pub(crate) enum WriteOp {
706 Value(instance::Payload, Option<SampleIdentity>, Option<Guid>),
710 Lifecycle { dispose: bool, unregister: bool },
712}
713
714pub(crate) struct WriterState {
715 pub(crate) data: EndpointData,
716 pub(crate) qos: DataWriterQos,
717 keyed: bool,
718 keys: Arc<dyn KeyOps>,
720 pub(crate) rtps: ReliableWriter,
723 pub(crate) matched: BTreeSet<Guid>,
725 pub(crate) instances: BTreeMap<InstanceHandle, WriterInstance>,
727 change_instance: HashMap<SequenceNumber, InstanceHandle>,
729 pub(crate) incompatible: IncompatibleQosStatus,
731 last_asserted: Instant,
733 alive: bool,
735 pub(crate) liveliness_lost: LivelinessLostStatus,
737 pub(crate) deadlines: Deadlines,
740 pub(crate) matched_status: MatchedStatus,
742 pub(crate) changes: StatusMask,
745 pub(crate) enabled: StatusMask,
747 pub(crate) listener: Option<(WriterListener, StatusMask)>,
749 pub(crate) publisher: Option<Arc<PublisherEntity>>,
751 #[cfg(feature = "security")]
753 pub(crate) payload_encoder: Option<Arc<rustorb_dds_security::crypto::Encoder>>,
754 disposed: BTreeSet<InstanceHandle>,
756 orphan: bool,
759 cleanup_at: Option<Instant>,
762 store: Option<Store>,
764 #[cfg(feature = "shm")]
766 pool: Option<Arc<rustorb_rtps::shm::Pool>>,
767 #[cfg(feature = "shm")]
771 loans: VecDeque<(SequenceNumber, rustorb_rtps::shm::PoolLoan)>,
772 persisted: BTreeMap<SequenceNumber, Record>,
775 restoring: bool,
777}
778
779impl WriterState {
780 fn add_match(&mut self, reader: Guid) -> bool {
782 let new = self.matched.insert(reader);
783 if new {
784 self.matched_status.matched(reader);
785 }
786 new
787 }
788
789 fn remove_match(&mut self, reader: &Guid) -> bool {
791 let was = self.matched.remove(reader);
792 if was {
793 self.matched_status.unmatched(*reader);
794 }
795 was
796 }
797
798 fn take_event(&mut self, k: StatusMask) -> Option<WriterEvent> {
801 Some(match k {
802 StatusMask::PUBLICATION_MATCHED => {
803 WriterEvent::PublicationMatched(self.matched_status.take())
804 }
805 StatusMask::LIVELINESS_LOST => WriterEvent::LivelinessLost(self.liveliness_lost.take()),
806 StatusMask::OFFERED_DEADLINE_MISSED => {
807 WriterEvent::OfferedDeadlineMissed(self.deadlines.missed.take())
808 }
809 StatusMask::OFFERED_INCOMPATIBLE_QOS => {
810 WriterEvent::OfferedIncompatibleQos(self.incompatible.take())
811 }
812 _ => return None,
813 })
814 }
815
816 fn local_lease(&self) -> Option<Duration> {
820 match self.qos.liveliness.kind {
821 LivelinessKind::Automatic => None,
822 _ => self.qos.liveliness.lease_duration,
823 }
824 }
825
826 fn check(&mut self, now: Instant) -> StatusMask {
830 let mut changes = StatusMask::NONE;
831 if let Some(lease) = self.local_lease()
832 && self.alive
833 && now > self.last_asserted + lease
834 {
835 self.alive = false;
836 self.liveliness_lost.add();
837 changes |= StatusMask::LIVELINESS_LOST;
838 }
839 let instances = &self.instances;
840 if self.deadlines.check(now, |h| instances.contains_key(h)) {
841 changes |= StatusMask::OFFERED_DEADLINE_MISSED;
842 }
843 if self.cleanup_at.is_some_and(|t| now >= t) {
844 self.cleanup_at = None;
845 self.clean_up();
846 }
847 changes
848 }
849
850 fn clean_up(&mut self) {
853 let disposed = std::mem::take(&mut self.disposed);
854 let sns: Vec<SequenceNumber> = self
855 .change_instance
856 .iter()
857 .filter(|(_, h)| disposed.contains(h))
858 .map(|(sn, _)| *sn)
859 .collect();
860 for sn in sns {
861 self.rtps.remove_change(sn);
862 }
863 for h in &disposed {
864 self.instances.remove(h);
865 }
866 self.trim();
867 }
868
869 fn orphan(&mut self, now: Instant) {
873 self.orphan = true;
874 self.listener = None;
875 self.publisher = None;
876 let ds = self.qos.durability_service;
877 self.qos.history = ds.history;
878 self.qos.resource_limits = ds.resource_limits;
879 self.deadlines = Deadlines::new(None);
880 self.cleanup_at = now.checked_add(ds.service_cleanup_delay);
882 self.trim();
883 }
884
885 fn restore(&mut self, records: Vec<Record>) {
887 self.restoring = true;
888 for r in records {
889 let op = match r.value {
890 Some(v) => WriteOp::Value(v.into(), None, None),
891 None => WriteOp::Lifecycle {
892 dispose: r.dispose,
893 unregister: r.unregister,
894 },
895 };
896 if self.add(r.instance, op, r.timestamp, false, false).is_ok() {
897 self.trim();
898 }
899 }
900 self.restoring = false;
901 self.compact();
902 }
903
904 fn compact(&mut self) {
906 if let Some(store) = &mut self.store {
907 let _ = store.rewrite(self.persisted.values());
908 }
909 }
910
911 fn instance_changes(&mut self, h: &InstanceHandle) -> usize {
913 let Some(i) = self.instances.get_mut(h) else {
914 return 0;
915 };
916 let rtps = &self.rtps;
917 i.changes.retain(|sn| rtps.contains(*sn));
918 i.changes.len()
919 }
920
921 fn is_full(&mut self, h: &InstanceHandle) -> bool {
925 if self.qos.reliability.kind != ReliabilityKind::Reliable
926 || self.qos.history != History::KeepAll
927 {
928 return false;
929 }
930 let limits = self.qos.resource_limits;
931 limits
932 .max_samples
933 .is_some_and(|m| self.rtps.len() >= m.max(1))
934 || limits
935 .max_samples_per_instance
936 .is_some_and(|m| self.instance_changes(h) >= m.max(1))
937 }
938
939 fn transient_local(&self) -> bool {
940 self.qos.durability >= DurabilityKind::TransientLocal
941 }
942
943 fn trim(&mut self) {
951 if !self.transient_local() {
952 self.rtps.remove_acknowledged();
953 }
954 let mut depth = match self.qos.history {
955 History::KeepLast(d) => Some(d.max(1)),
956 History::KeepAll => None,
957 };
958 let limits = self.orphan.then_some(self.qos.resource_limits);
959 if let Some(m) = limits.and_then(|l| l.max_samples_per_instance) {
960 depth = Some(depth.map_or(m, |d| d.min(m)).max(1));
961 }
962 if let Some(depth) = depth {
963 let handles: Vec<InstanceHandle> = self.instances.keys().copied().collect();
964 for h in handles {
965 while self.instance_changes(&h) > depth {
966 let i = self.instances.get_mut(&h).expect("listed above");
967 if let Some(sn) = i.changes.pop_front() {
968 self.rtps.remove_change(sn);
969 }
970 }
971 }
972 }
973 if let Some(m) = limits.and_then(|l| l.max_instances) {
974 while self.instances.len() > m {
975 let rtps = &self.rtps;
977 let Some(h) = self
978 .instances
979 .iter_mut()
980 .map(|(h, i)| {
981 i.changes.retain(|sn| rtps.contains(*sn));
982 (*h, i.changes.back().copied())
983 })
984 .min_by_key(|(_, sn)| *sn)
985 .map(|(h, _)| h)
986 else {
987 break;
988 };
989 if let Some(i) = self.instances.remove(&h) {
990 for sn in i.changes {
991 self.rtps.remove_change(sn);
992 }
993 }
994 }
995 }
996 if let Some(m) = limits.and_then(|l| l.max_samples) {
997 while self.rtps.len() > m.max(1) {
998 if self.rtps.remove_oldest().is_none() {
999 break;
1000 }
1001 }
1002 }
1003 let rtps = &self.rtps;
1004 self.change_instance.retain(|sn, _| rtps.contains(*sn));
1005 #[cfg(feature = "shm")]
1006 {
1007 let old = self.loans.len().saturating_sub(LOANS_KEPT);
1008 let mut i = 0;
1009 self.loans.retain(|(sn, _)| {
1010 i += 1;
1011 i > old || rtps.contains(*sn)
1012 });
1013 }
1014 if self.store.is_some() {
1015 self.persisted.retain(|sn, _| rtps.contains(*sn));
1016 let records = self.store.as_ref().map_or(0, Store::records);
1017 if records > 2 * self.persisted.len() + 64 {
1018 self.compact();
1019 }
1020 }
1021 }
1022
1023 fn register(&mut self, h: InstanceHandle) -> Result<()> {
1025 if self.instances.contains_key(&h) {
1026 return Ok(());
1027 }
1028 if self
1029 .qos
1030 .resource_limits
1031 .max_instances
1032 .is_some_and(|m| self.instances.len() >= m)
1033 {
1034 return Err(Error::OutOfResources);
1035 }
1036 self.instances.insert(
1037 h,
1038 WriterInstance {
1039 changes: VecDeque::new(),
1040 key: None,
1041 },
1042 );
1043 Ok(())
1044 }
1045
1046 fn add(
1052 &mut self,
1053 h: InstanceHandle,
1054 op: WriteOp,
1055 timestamp: Time,
1056 key_payload: bool,
1057 #[allow(unused_variables)] by_reference: bool,
1058 ) -> Result<(SequenceNumber, instance::Change)> {
1059 let unregister = matches!(
1060 op,
1061 WriteOp::Lifecycle {
1062 unregister: true,
1063 ..
1064 }
1065 );
1066 if !self.instances.contains_key(&h) {
1067 if unregister {
1068 return Err(Error::PreconditionNotMet);
1069 }
1070 self.register(h)?;
1071 }
1072 let restoring = self.restoring;
1073 let record = self.store.as_mut().map(|store| {
1074 let (value, dispose) = match &op {
1075 WriteOp::Value(v, ..) => (Some(v.to_vec()), false),
1076 WriteOp::Lifecycle { dispose, .. } => (None, *dispose),
1077 };
1078 let r = Record {
1079 instance: h,
1080 timestamp,
1081 value,
1082 dispose,
1083 unregister,
1084 };
1085 if restoring {
1086 Ok(r)
1087 } else {
1088 store.append(&r).map(|()| r)
1089 }
1090 });
1091 let record = record.transpose()?;
1092 match &op {
1093 WriteOp::Value(..) => {
1094 self.disposed.remove(&h);
1095 }
1096 WriteOp::Lifecycle { dispose: true, .. } => {
1097 self.disposed.insert(h);
1098 }
1099 WriteOp::Lifecycle { .. } => {}
1100 }
1101 let mut q = ParameterList::new();
1102 if self.keyed {
1103 q.push(Parameter::new(pid::KEY_HASH, h.0));
1104 }
1105 let mut directed = None;
1106 #[cfg(feature = "shm")]
1107 let mut lent = None;
1108 let (payload, change) = match op {
1109 WriteOp::Value(v, related, to) => {
1110 directed = to;
1111 if self.keyed {
1112 let inst = self.instances.get_mut(&h).expect("registered above");
1113 if inst.key.is_none() {
1114 inst.key = self.keys.key_payload(&v);
1115 }
1116 }
1117 if let Some(id) = related {
1118 q.push(Parameter::new(
1120 pid::RELATED_SAMPLE_IDENTITY,
1121 id.to_bytes(Endianness::NATIVE),
1122 ));
1123 }
1124 #[cfg(feature = "shm")]
1125 if let instance::Payload::Loaned(l) = &v
1126 && by_reference
1127 {
1128 lent = Some(l.clone());
1129 }
1130 let bytes = || {
1131 #[cfg(feature = "security")]
1132 if let Some(e) = &self.payload_encoder {
1133 return e.encode_payload(&v);
1134 }
1135 v.to_vec()
1136 };
1137 #[cfg(feature = "shm")]
1138 let bytes = match &lent {
1139 Some(l) => l.reference(),
1140 None => bytes(),
1141 };
1142 #[cfg(not(feature = "shm"))]
1143 let bytes = bytes();
1144 (
1145 Some(SerializedPayload {
1146 kind: PayloadKind::Data,
1147 bytes,
1148 }),
1149 instance::Change::Write(v),
1150 )
1151 }
1152 WriteOp::Lifecycle {
1153 dispose,
1154 unregister,
1155 } => {
1156 let mut flags = 0;
1157 if dispose {
1158 flags |= STATUS_DISPOSED;
1159 }
1160 if unregister {
1161 flags |= STATUS_UNREGISTERED;
1162 }
1163 q.push(Parameter::new(pid::STATUS_INFO, [0, 0, 0, flags]));
1164 let key = if key_payload && self.keyed {
1170 self.instances.get(&h).and_then(|i| i.key.clone())
1171 } else {
1172 None
1173 };
1174 (
1175 key.map(|bytes| SerializedPayload {
1176 kind: PayloadKind::Key,
1177 bytes,
1178 }),
1179 instance::Change::Lifecycle {
1180 disposed: dispose,
1181 unregistered: unregister,
1182 },
1183 )
1184 }
1185 };
1186 if !self.keyed && !q.parameters.is_empty() {
1190 q.parameters.insert(0, Parameter::new(pid::KEY_HASH, h.0));
1191 }
1192 let inline_qos = (!q.parameters.is_empty()).then_some(q);
1193 if matches!(change, instance::Change::Write(_)) {
1194 self.deadlines.renew(h, Instant::now());
1195 } else {
1196 self.deadlines.remove(&h);
1198 }
1199 let sn = self
1200 .rtps
1201 .add_change_at(inline_qos, payload, Some(timestamp));
1202 if let Some(r) = directed {
1203 self.rtps.direct(sn, r);
1204 }
1205 self.change_instance.insert(sn, h);
1206 #[cfg(feature = "shm")]
1207 if let Some(l) = lent {
1208 self.loans.push_back((sn, l));
1209 }
1210 if let Some(r) = record {
1211 self.persisted.insert(sn, r);
1212 }
1213 if unregister {
1214 self.instances.remove(&h);
1215 } else {
1216 self.instances
1217 .get_mut(&h)
1218 .expect("registered above")
1219 .changes
1220 .push_back(sn);
1221 }
1222 Ok((sn, change))
1223 }
1224}
1225
1226pub(crate) struct Inner {
1227 spdp: Spdp,
1228 pub(crate) sedp: Sedp,
1229 wlp: Wlp,
1230 wlp_secure: Option<Wlp>,
1233 spdp_secure: Option<SpdpSecure>,
1236 typelookup: TypeLookup,
1237 type_requests: HashSet<(TypeIdentifier, GuidPrefix)>,
1240 dependency_requests: HashSet<(TypeIdentifier, GuidPrefix)>,
1242 learnt_types: usize,
1244 next_automatic: Option<Instant>,
1247 manual_pending: bool,
1250 next_manual: Instant,
1252 persistence_directory: std::path::PathBuf,
1254 writer_config: WriterConfig,
1255 reader_config: ReaderConfig,
1256 next_entity: u32,
1257 pub(crate) writers: HashMap<Guid, WriterState>,
1258 pub(crate) readers: HashMap<Guid, ReaderState>,
1259 deleted: bool,
1260 pending: Vec<(Guid, StatusMask)>,
1264 types: HashMap<String, TypeObjects>,
1266 dynamic_types: HashMap<String, DynamicType>,
1268 pub(crate) inconsistent_topics: HashMap<String, InconsistentTopicStatus>,
1270 pending_topics: Vec<String>,
1272 pub(crate) topic_listeners: HashMap<String, (Arc<dyn TopicListener>, StatusMask)>,
1274 pub(crate) listener: Option<(Arc<dyn DomainParticipantListener>, StatusMask)>,
1276 #[cfg(feature = "security")]
1278 pub(crate) security: Option<Arc<Security>>,
1279}
1280
1281fn assert_wlp(wlp: &mut Wlp, secure: &mut Option<Wlp>, kind: [u8; 4]) {
1283 wlp.assert_liveliness(kind);
1284 if let Some(w) = secure.as_mut() {
1285 w.assert_liveliness(kind);
1286 }
1287}
1288
1289const MIN_LIVELINESS_PERIOD: Duration = Duration::from_millis(10);
1291
1292impl Inner {
1293 fn sedp_add_writer(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1296 #[cfg(feature = "security")]
1297 if self
1298 .security
1299 .as_ref()
1300 .is_some_and(|s| s.topic_discovery_protected(&data.topic_name))
1301 {
1302 return self.sedp.add_writer_secure(data);
1303 }
1304 self.sedp.add_writer(data)
1305 }
1306
1307 fn sedp_add_reader(&mut self, data: EndpointData) -> Vec<SedpEvent> {
1309 #[cfg(feature = "security")]
1310 if self
1311 .security
1312 .as_ref()
1313 .is_some_and(|s| s.topic_discovery_protected(&data.topic_name))
1314 {
1315 return self.sedp.add_reader_secure(data);
1316 }
1317 self.sedp.add_reader(data)
1318 }
1319
1320 fn changed(&mut self, g: Guid, k: StatusMask) {
1323 if !k.is_empty() {
1324 self.pending.push((g, k));
1325 }
1326 }
1327
1328 fn local_writer_asserted(&mut self, writer: Guid, now: Instant) {
1332 let Some(kind) = self.writers.get(&writer).map(|w| w.qos.liveliness.kind) else {
1333 return;
1334 };
1335 if kind == LivelinessKind::ManualByParticipant {
1336 self.participant_asserted(now);
1337 } else {
1338 self.local_asserted(writer, now);
1339 }
1340 }
1341
1342 fn participant_asserted(&mut self, now: Instant) {
1346 let guids: Vec<Guid> = self
1347 .writers
1348 .iter()
1349 .filter(|(_, w)| w.qos.liveliness.kind == LivelinessKind::ManualByParticipant)
1350 .map(|(g, _)| *g)
1351 .collect();
1352 if !guids.is_empty() {
1353 self.manual_pending = true;
1354 }
1355 for g in guids {
1356 self.local_asserted(g, now);
1357 }
1358 }
1359
1360 fn local_asserted(&mut self, writer: Guid, now: Instant) {
1361 if let Some(w) = self.writers.get_mut(&writer) {
1362 w.last_asserted = now;
1363 w.alive = true;
1364 }
1365 self.remote_writer_asserted(&writer, now);
1366 }
1367
1368 fn remote_writer_asserted(&mut self, writer: &Guid, now: Instant) {
1370 for (g, r) in self.readers.iter_mut() {
1371 if r.writer_asserted(writer, now) {
1372 self.pending.push((*g, StatusMask::LIVELINESS_CHANGED));
1373 }
1374 }
1375 }
1376
1377 fn remote_participant_asserted(&mut self, prefix: GuidPrefix, kind: [u8; 4], now: Instant) {
1381 let manual = kind == wlp::kind::MANUAL_LIVELINESS_UPDATE;
1382 for (rg, r) in self.readers.iter_mut() {
1383 let guids: Vec<Guid> = r
1384 .liveliness
1385 .iter()
1386 .filter(|(g, l)| {
1387 g.prefix == prefix
1388 && (l.kind == LivelinessKind::Automatic
1389 || (manual && l.kind == LivelinessKind::ManualByParticipant))
1390 })
1391 .map(|(g, _)| *g)
1392 .collect();
1393 for g in guids {
1394 if r.writer_asserted(&g, now) {
1395 self.pending.push((*rg, StatusMask::LIVELINESS_CHANGED));
1396 }
1397 }
1398 }
1399 }
1400
1401 fn check_timers(&mut self, now: Instant) {
1404 for (g, w) in self.writers.iter_mut() {
1405 let k = w.check(now);
1406 if !k.is_empty() {
1407 self.pending.push((*g, k));
1408 }
1409 }
1410 for (g, r) in self.readers.iter_mut() {
1411 let k = r.check(now);
1412 if !k.is_empty() {
1413 self.pending.push((*g, k));
1414 }
1415 }
1416 let min_lease = |kind: LivelinessKind| {
1417 self.writers
1418 .values()
1419 .filter(|w| w.qos.liveliness.kind == kind)
1420 .filter_map(|w| w.qos.liveliness.lease_duration)
1421 .min()
1422 };
1423 match min_lease(LivelinessKind::Automatic) {
1425 None => self.next_automatic = None,
1426 Some(lease) => {
1427 if self.next_automatic.is_none_or(|t| t <= now) {
1428 assert_wlp(
1429 &mut self.wlp,
1430 &mut self.wlp_secure,
1431 wlp::kind::AUTOMATIC_LIVELINESS_UPDATE,
1432 );
1433 self.next_automatic = Some(now + (lease / 3).max(MIN_LIVELINESS_PERIOD));
1434 }
1435 }
1436 }
1437 if self.manual_pending && now >= self.next_manual {
1440 self.manual_pending = false;
1441 assert_wlp(
1442 &mut self.wlp,
1443 &mut self.wlp_secure,
1444 wlp::kind::MANUAL_LIVELINESS_UPDATE,
1445 );
1446 let period = min_lease(LivelinessKind::ManualByParticipant)
1447 .map_or(Duration::from_secs(1), |l| l / 3);
1448 self.next_manual = now + period.max(MIN_LIVELINESS_PERIOD);
1449 }
1450 }
1451}
1452
1453pub(crate) struct Shared {
1455 this: Weak<Shared>,
1457 pub(crate) waitsets: Mutex<Vec<Weak<Waker>>>,
1460 pub(crate) transport: UdpTransport,
1461 #[cfg(feature = "shm")]
1463 shm: Option<rustorb_rtps::shm::ShmTransport>,
1464 pub(crate) prefix: GuidPrefix,
1465 domain_id: u32,
1466 inner: Mutex<Inner>,
1467 pub(crate) data_arrived: Condvar,
1469 pub(crate) acknowledged: Condvar,
1471 stop: AtomicBool,
1472 drop_one_in: Option<u32>,
1473 #[cfg(feature = "security")]
1475 pub(crate) security: Option<Arc<Security>>,
1476 #[cfg(feature = "security")]
1479 pub(crate) psk: Option<Arc<PskProtection>>,
1480 drop_state: AtomicU64,
1482}
1483
1484impl Shared {
1485 pub(crate) fn send(&self, bytes: &[u8], locators: &[Locator]) -> (bool, Option<io::Error>) {
1490 #[cfg(feature = "security")]
1491 let encoded;
1492 #[cfg(feature = "security")]
1493 let bytes: &[u8] = match &self.security {
1494 Some(sec) => match sec.encode(bytes) {
1495 Some(b) => {
1496 encoded = b;
1497 &encoded
1498 }
1499 None => return (false, None),
1500 },
1501 None => bytes,
1502 };
1503 #[cfg(feature = "security")]
1506 let psk_encoded;
1507 #[cfg(feature = "security")]
1508 let bytes: &[u8] = match &self.psk {
1509 Some(psk) if rustorb_dds_security::crypto::message_prefix_flags(bytes).is_none() => {
1510 match psk.encode(bytes) {
1511 Ok(b) => {
1512 psk_encoded = b;
1513 &psk_encoded
1514 }
1515 Err(_) => return (false, None),
1516 }
1517 }
1518 _ => bytes,
1519 };
1520 let mut sent = false;
1521 let mut last_err = None;
1522 #[cfg(feature = "shm")]
1523 if let Some(shm) = &self.shm {
1524 for l in shm.select(locators) {
1525 let r = if l.kind == Locator::KIND_SHM {
1526 shm.send(bytes, l)
1527 } else {
1528 self.transport.send(bytes, l)
1529 };
1530 match r {
1531 Ok(()) => sent = true,
1532 Err(e) => last_err = Some(e),
1533 }
1534 }
1535 return (sent, last_err);
1536 }
1537 for l in locators.iter().filter(|l| l.kind != Locator::KIND_SHM) {
1538 match self.transport.send(bytes, l) {
1539 Ok(()) => sent = true,
1540 Err(e) => last_err = Some(e),
1541 }
1542 }
1543 (sent, last_err)
1544 }
1545
1546 pub(crate) fn vendor_of(&self, prefix: &GuidPrefix) -> Option<VendorId> {
1548 self.lock_any()
1549 .spdp
1550 .participant(prefix)
1551 .map(|p| p.vendor_id)
1552 }
1553
1554 pub(crate) fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
1555 let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
1556 if g.deleted {
1557 return Err(Error::AlreadyDeleted);
1558 }
1559 Ok(g)
1560 }
1561
1562 pub(crate) fn flush(&self) {
1571 let mut calls: Vec<ListenerCall> = Vec::new();
1572 let mut any = false;
1573 {
1574 let mut g = self.lock_any();
1575 let inner = &mut *g;
1576 if inner.pending.is_empty() && inner.pending_topics.is_empty() {
1577 return;
1578 }
1579 let participant = inner.listener.clone();
1580 let participant_for = |bit: StatusMask| {
1581 participant
1582 .as_ref()
1583 .filter(|(_, m)| m.contains(bit))
1584 .map(|(l, _)| l.clone())
1585 };
1586 let mut on_readers: Vec<Arc<SubscriberEntity>> = Vec::new();
1588 for (guid, k) in std::mem::take(&mut inner.pending) {
1589 any = true;
1590 for bit in k.bits() {
1591 if let Some(w) = inner.writers.get_mut(&guid) {
1592 let own = w
1593 .listener
1594 .as_ref()
1595 .filter(|(_, m)| m.contains(bit))
1596 .map(|(l, _)| l.clone());
1597 if let Some(l) = own
1598 && let Some(ev) = w.take_event(bit)
1599 {
1600 w.changes = w.changes & !bit;
1601 calls.push(Box::new(move |s| l(s, guid, ev)));
1602 continue;
1603 }
1604 let group = w.publisher.as_ref().and_then(|p| p.listener_for(bit));
1605 let call: Option<ListenerCall> = if let Some(l) = group {
1606 w.take_event(bit).map(|ev| -> ListenerCall {
1607 Box::new(move |s| writer_event(&*l, s, guid, ev))
1608 })
1609 } else if let Some(l) = participant_for(bit) {
1610 w.take_event(bit).map(|ev| -> ListenerCall {
1611 Box::new(move |s| writer_event(&*l, s, guid, ev))
1612 })
1613 } else {
1614 None
1615 };
1616 match call {
1617 Some(c) => {
1618 w.changes = w.changes & !bit;
1619 calls.push(c);
1620 }
1621 None => w.changes |= bit,
1622 }
1623 } else if let Some(r) = inner.readers.get_mut(&guid) {
1624 if bit == StatusMask::DATA_AVAILABLE {
1625 let on = StatusMask::DATA_ON_READERS;
1630 if let Some(sub) = r.subscriber.clone() {
1631 let call: Option<ListenerCall> =
1632 match (sub.listener_for(on), participant_for(on)) {
1633 (Some(l), _) => {
1634 let sub = sub.clone();
1635 Some(Box::new(move |s| data_on_readers(&*l, s, sub)))
1636 }
1637 (None, Some(l)) => {
1638 let sub = sub.clone();
1639 Some(Box::new(move |s| data_on_readers(&*l, s, sub)))
1640 }
1641 (None, None) => None,
1642 };
1643 if let Some(c) = call {
1644 r.changes |= bit;
1645 if !on_readers.iter().any(|s| Arc::ptr_eq(s, &sub)) {
1646 on_readers.push(sub);
1647 calls.push(c);
1648 }
1649 continue;
1650 }
1651 }
1652 }
1653 let own = r
1654 .listener
1655 .as_ref()
1656 .filter(|(_, m)| m.contains(bit))
1657 .map(|(l, _)| l.clone());
1658 if let Some(l) = own
1659 && let Some(ev) = r.take_event(bit)
1660 {
1661 r.changes = r.changes & !bit;
1662 calls.push(Box::new(move |s| l(s, guid, ev)));
1663 continue;
1664 }
1665 let group = r.subscriber.as_ref().and_then(|p| p.listener_for(bit));
1666 let call: Option<ListenerCall> = if let Some(l) = group {
1667 r.take_event(bit).map(|ev| -> ListenerCall {
1668 Box::new(move |s| reader_event(&*l, s, guid, ev))
1669 })
1670 } else if let Some(l) = participant_for(bit) {
1671 r.take_event(bit).map(|ev| -> ListenerCall {
1672 Box::new(move |s| reader_event(&*l, s, guid, ev))
1673 })
1674 } else {
1675 None
1676 };
1677 match call {
1678 Some(c) => {
1679 r.changes = r.changes & !bit;
1680 calls.push(c);
1681 }
1682 None => r.changes |= bit,
1683 }
1684 }
1685 }
1686 }
1687 let bit = StatusMask::INCONSISTENT_TOPIC;
1688 for topic in std::mem::take(&mut inner.pending_topics) {
1689 let own = inner
1690 .topic_listeners
1691 .get(&topic)
1692 .filter(|(_, m)| m.contains(bit))
1693 .map(|(l, _)| l.clone());
1694 let status = |inner: &mut Inner| {
1695 inner
1696 .inconsistent_topics
1697 .get_mut(&topic)
1698 .map(|s| s.take())
1699 .unwrap_or_default()
1700 };
1701 if let Some(l) = own {
1702 let status = status(inner);
1703 calls.push(Box::new(move |_| l.on_inconsistent_topic(&topic, status)));
1704 } else if let Some(l) = participant_for(bit) {
1705 let status = status(inner);
1706 calls.push(Box::new(move |_| l.on_inconsistent_topic(&topic, status)));
1707 }
1708 }
1709 }
1710 if any {
1711 self.data_arrived.notify_all();
1712 self.wake_waitsets();
1713 }
1714 if calls.is_empty() {
1715 return;
1716 }
1717 if let Some(this) = self.this.upgrade() {
1718 for c in calls {
1719 c(&this);
1720 }
1721 }
1722 }
1723
1724 pub(crate) fn notify_datareaders(&self, subscriber: &Arc<SubscriberEntity>) {
1728 let bit = StatusMask::DATA_AVAILABLE;
1729 let mut calls: Vec<ListenerCall> = Vec::new();
1730 {
1731 let mut g = self.lock_any();
1732 for (guid, r) in g.readers.iter_mut() {
1733 let mine = r
1734 .subscriber
1735 .as_ref()
1736 .is_some_and(|s| Arc::ptr_eq(s, subscriber));
1737 if !mine || !r.changes.contains(bit) {
1738 continue;
1739 }
1740 let own = r
1741 .listener
1742 .as_ref()
1743 .filter(|(_, m)| m.contains(bit))
1744 .map(|(l, _)| l.clone());
1745 if let Some(l) = own {
1746 r.changes = r.changes & !bit;
1747 let guid = *guid;
1748 calls.push(Box::new(move |s| l(s, guid, ReaderEvent::DataAvailable)));
1749 }
1750 }
1751 }
1752 if let Some(this) = self.this.upgrade() {
1753 for c in calls {
1754 c(&this);
1755 }
1756 }
1757 }
1758
1759 pub(crate) fn wake_waitsets(&self) {
1762 let mut w = self.waitsets.lock().unwrap_or_else(|e| e.into_inner());
1763 w.retain(|w| match w.upgrade() {
1764 Some(w) => {
1765 w.wake();
1766 true
1767 }
1768 None => false,
1769 });
1770 }
1771
1772 pub(crate) fn lock_any(&self) -> MutexGuard<'_, Inner> {
1775 self.inner.lock().unwrap_or_else(|e| e.into_inner())
1776 }
1777
1778 fn should_drop(&self) -> bool {
1783 let Some(n) = self.drop_one_in else {
1784 return false;
1785 };
1786 let mut x = self.drop_state.load(Ordering::Relaxed);
1787 x ^= x << 13;
1788 x ^= x >> 7;
1789 x ^= x << 17;
1790 self.drop_state.store(x, Ordering::Relaxed);
1791 x.is_multiple_of(u64::from(n))
1792 }
1793
1794 pub(crate) fn new_guid(&self, kind: u8) -> Result<Guid> {
1795 let mut g = self.lock()?;
1796 let n = g.next_entity;
1797 if n >= 1 << 24 {
1798 return Err(Error::OutOfResources);
1799 }
1800 g.next_entity += 1;
1801 let key = [(n >> 16) as u8, (n >> 8) as u8, n as u8];
1802 Ok(Guid::new(self.prefix, EntityId::user(key, kind)))
1803 }
1804
1805 pub(crate) fn type_information(
1807 &self,
1808 type_name: &str,
1809 ) -> Result<Option<rustorb_xtypes::type_object::TypeInformation>> {
1810 Ok(self
1811 .lock()?
1812 .types
1813 .get(type_name)
1814 .map(|o| o.information.clone()))
1815 }
1816
1817 pub(crate) fn add_writer(
1820 &self,
1821 #[allow(unused_mut)] mut data: EndpointData,
1822 qos: DataWriterQos,
1823 keys: Arc<dyn KeyOps>,
1824 listener: Option<(WriterListener, StatusMask)>,
1825 publisher: Arc<PublisherEntity>,
1826 ) -> Result<()> {
1827 {
1828 let mut g = self.lock()?;
1829 let inner = &mut *g;
1830 let guid = data.guid;
1831 let now = Instant::now();
1832 #[cfg(feature = "security")]
1833 let payload_encoder = match &inner.security {
1834 Some(sec) => sec.local_endpoint(&mut data, true)?,
1835 None => None,
1836 };
1837 let rtps = ReliableWriter::new(guid, VENDOR_ID, inner.writer_config.clone());
1838 let liveliness_kind = qos.liveliness.kind;
1839 let deadline = qos.deadline;
1840 let mut w = WriterState {
1841 data: data.clone(),
1842 qos,
1843 keyed: keys.keyed(),
1844 keys,
1845 rtps,
1846 matched: BTreeSet::new(),
1847 instances: BTreeMap::new(),
1848 change_instance: HashMap::new(),
1849 incompatible: IncompatibleQosStatus::default(),
1850 last_asserted: now,
1851 alive: true,
1852 liveliness_lost: LivelinessLostStatus::default(),
1853 deadlines: Deadlines::new(deadline),
1854 matched_status: MatchedStatus::default(),
1855 changes: StatusMask::NONE,
1856 enabled: StatusMask::ALL,
1857 listener,
1858 publisher: Some(publisher),
1859 #[cfg(feature = "security")]
1860 payload_encoder,
1861 disposed: BTreeSet::new(),
1862 orphan: false,
1863 cleanup_at: None,
1864 store: None,
1865 #[cfg(feature = "shm")]
1866 pool: None,
1867 #[cfg(feature = "shm")]
1868 loans: VecDeque::new(),
1869 persisted: BTreeMap::new(),
1870 restoring: false,
1871 };
1872 if w.qos.durability == DurabilityKind::Persistent {
1873 let (store, records) = Store::open(
1874 &inner.persistence_directory,
1875 &data.topic_name,
1876 &data.type_name,
1877 )?;
1878 w.store = Some(store);
1879 w.restore(records);
1880 }
1881 let lease = w.local_lease();
1882 let mut changes = StatusMask::NONE;
1883 for (rg, r) in inner.readers.iter_mut() {
1884 match match_endpoints(&data, &r.data, inner.sedp.registry()) {
1885 Match::Matched => {
1886 w.add_match(*rg);
1887 changes |= StatusMask::PUBLICATION_MATCHED;
1888 let mut k = StatusMask::NONE;
1889 if r.add_match(guid) {
1890 k |= StatusMask::SUBSCRIPTION_MATCHED;
1891 }
1892 if r.writer_matched(guid, liveliness_kind, lease, now) {
1893 k |= StatusMask::LIVELINESS_CHANGED;
1894 }
1895 if w.transient_local()
1897 && r.data.durability >= DurabilityKind::TransientLocal
1898 {
1899 let kept: Vec<Change> = w
1900 .rtps
1901 .changes()
1902 .filter(|c| w.rtps.is_for(c.sequence_number, rg))
1903 .cloned()
1904 .collect();
1905 for c in kept {
1906 if let Some(c) = r.incoming(c) {
1907 k |= r.accept(c);
1908 }
1909 }
1910 }
1911 inner.pending.push((*rg, k));
1912 }
1913 Match::Incompatible(policies) => {
1914 w.incompatible.add(&policies);
1915 changes |= StatusMask::OFFERED_INCOMPATIBLE_QOS;
1916 r.incompatible.add(&policies);
1917 inner
1918 .pending
1919 .push((*rg, StatusMask::REQUESTED_INCOMPATIBLE_QOS));
1920 }
1921 Match::Inconsistent | Match::Unresolved(_) | Match::Unrelated => {}
1926 }
1927 }
1928 inner.writers.insert(guid, w);
1929 inner.changed(guid, changes);
1930 let events = inner.sedp_add_writer(data);
1931 apply_sedp_events(inner, events, now);
1932 }
1933 self.flush();
1934 Ok(())
1935 }
1936
1937 pub(crate) fn add_reader(
1940 &self,
1941 #[allow(unused_mut)] mut data: EndpointData,
1942 qos: DataReaderQos,
1943 keys: Arc<dyn KeyOps>,
1944 listener: Option<(ReaderListener, StatusMask)>,
1945 filter: Option<ContentFilter>,
1946 subscriber: Arc<SubscriberEntity>,
1947 ) -> Result<()> {
1948 {
1949 let mut g = self.lock()?;
1950 let inner = &mut *g;
1951 let guid = data.guid;
1952 let now = Instant::now();
1953 #[cfg(feature = "security")]
1954 if let Some(sec) = &inner.security {
1955 sec.local_endpoint(&mut data, false)?;
1956 }
1957 let mut r = ReaderState::new(data.clone(), &qos, keys, &inner.reader_config);
1958 #[cfg(feature = "shm")]
1959 {
1960 r.pools = self.shm.as_ref().map(|s| s.pools());
1961 }
1962 #[cfg(feature = "security")]
1963 {
1964 r.payload_security = inner
1965 .security
1966 .clone()
1967 .filter(|s| s.payload_protected(&data.topic_name));
1968 }
1969 r.listener = listener;
1970 r.subscriber = Some(subscriber);
1971 r.filter = filter;
1972 let mut changes = StatusMask::NONE;
1973 let mut kept = Vec::new();
1976 for (wg, w) in inner.writers.iter_mut() {
1977 match match_endpoints(&w.data, &data, inner.sedp.registry()) {
1978 Match::Matched => {
1979 r.add_match(*wg);
1980 changes |= StatusMask::SUBSCRIPTION_MATCHED;
1981 if r.writer_matched(*wg, w.qos.liveliness.kind, w.local_lease(), now) {
1982 changes |= StatusMask::LIVELINESS_CHANGED;
1983 }
1984 if w.add_match(guid) {
1985 inner.pending.push((*wg, StatusMask::PUBLICATION_MATCHED));
1986 }
1987 if w.transient_local() && qos.durability >= DurabilityKind::TransientLocal {
1988 kept.extend(
1989 w.rtps
1990 .changes()
1991 .filter(|c| w.rtps.is_for(c.sequence_number, &guid))
1992 .cloned(),
1993 );
1994 }
1995 }
1996 Match::Incompatible(policies) => {
1997 r.incompatible.add(&policies);
1998 changes |= StatusMask::REQUESTED_INCOMPATIBLE_QOS;
1999 w.incompatible.add(&policies);
2000 inner
2001 .pending
2002 .push((*wg, StatusMask::OFFERED_INCOMPATIBLE_QOS));
2003 }
2004 Match::Inconsistent | Match::Unresolved(_) | Match::Unrelated => {}
2005 }
2006 }
2007 for c in kept {
2008 if let Some(c) = r.incoming(c) {
2009 changes |= r.accept(c);
2010 }
2011 }
2012 inner.readers.insert(guid, r);
2013 inner.changed(guid, changes);
2014 let events = inner.sedp_add_reader(data);
2015 apply_sedp_events(inner, events, now);
2016 }
2017 self.flush();
2018 Ok(())
2019 }
2020
2021 pub(crate) fn dynamic_type(&self, type_name: &str) -> Result<Option<DynamicType>> {
2023 Ok(self.lock()?.dynamic_types.get(type_name).cloned())
2024 }
2025
2026 pub(crate) fn set_filter_parameters(
2030 &self,
2031 readers: &[Guid],
2032 parameters: &[String],
2033 ) -> Result<()> {
2034 {
2035 let mut g = self.lock()?;
2036 let inner = &mut *g;
2037 let now = Instant::now();
2038 for guid in readers {
2039 let Some(r) = inner.readers.get_mut(guid) else {
2040 continue;
2041 };
2042 if let Some(f) = &mut r.filter {
2043 f.set_parameters(parameters)?;
2044 }
2045 if let Some(cf) = &mut r.data.content_filter {
2046 cf.expression_parameters = parameters.to_vec();
2047 }
2048 let data = r.data.clone();
2049 let events = inner.sedp_add_reader(data);
2050 apply_sedp_events(inner, events, now);
2051 }
2052 }
2053 self.flush();
2054 Ok(())
2055 }
2056
2057 pub(crate) fn remove_writer(&self, guid: &Guid) {
2066 {
2067 let mut g = self.lock_any();
2068 let deleted = g.deleted;
2069 if let Some(w) = g.writers.get_mut(guid)
2070 && !deleted
2071 && !w.orphan
2072 && w.qos.durability >= DurabilityKind::Transient
2073 {
2074 w.orphan(Instant::now());
2075 return;
2076 }
2077 }
2078 let handles: Vec<InstanceHandle> = {
2079 let g = self.lock_any();
2080 match g.writers.get(guid) {
2081 Some(w) if !g.deleted => w.instances.keys().copied().collect(),
2082 _ => Vec::new(),
2083 }
2084 };
2085 for h in handles {
2086 let _ = self.write(
2087 *guid,
2088 h,
2089 WriteOp::Lifecycle {
2090 dispose: self.autodispose_of(guid),
2091 unregister: true,
2092 },
2093 Time::now(),
2094 );
2095 }
2096 {
2097 let mut g = self.lock_any();
2098 let inner = &mut *g;
2099 #[cfg(feature = "security")]
2100 if let Some(sec) = &inner.security {
2101 sec.remove_local_endpoint(guid);
2102 }
2103 if inner.writers.remove(guid).is_none() {
2104 return;
2105 }
2106 for (rg, r) in inner.readers.iter_mut() {
2107 let k = r.writer_removed(guid);
2108 if !k.is_empty() {
2109 inner.pending.push((*rg, k));
2110 }
2111 }
2112 if !inner.deleted {
2113 inner.sedp.remove_writer(guid);
2114 }
2115 }
2116 self.flush();
2117 }
2118
2119 pub(crate) fn register_instance(&self, writer: &Guid, h: InstanceHandle) -> Result<()> {
2121 let mut g = self.lock()?;
2122 let Some(w) = g.writers.get_mut(writer) else {
2123 return Ok(());
2124 };
2125 w.register(h)
2126 }
2127
2128 pub(crate) fn autodispose_of(&self, writer: &Guid) -> bool {
2129 self.lock_any().writers.get(writer).is_some_and(|w| {
2130 w.qos
2131 .writer_data_lifecycle
2132 .autodispose_unregistered_instances
2133 })
2134 }
2135
2136 pub(crate) fn remove_reader(&self, guid: &Guid) {
2137 {
2138 let mut g = self.lock_any();
2139 let inner = &mut *g;
2140 if inner.readers.remove(guid).is_none() {
2141 return;
2142 }
2143 #[cfg(feature = "security")]
2144 if let Some(sec) = &inner.security {
2145 sec.remove_local_endpoint(guid);
2146 }
2147 for (wg, w) in inner.writers.iter_mut() {
2148 if w.remove_match(guid) {
2149 inner.pending.push((*wg, StatusMask::PUBLICATION_MATCHED));
2150 }
2151 }
2152 if !inner.deleted {
2153 inner.sedp.remove_reader(guid);
2154 }
2155 }
2156 self.acknowledged.notify_all();
2157 self.flush();
2158 }
2159
2160 pub(crate) fn write(
2168 &self,
2169 writer: Guid,
2170 h: InstanceHandle,
2171 op: WriteOp,
2172 timestamp: Time,
2173 ) -> Result<SequenceNumber> {
2174 let out;
2175 let (related, directed) = match &op {
2176 WriteOp::Value(_, r, d) => (*r, *d),
2177 WriteOp::Lifecycle { .. } => (None, None),
2178 };
2179 let sn;
2180 {
2181 let mut g = self.lock()?;
2182 let Some(blocking) = g
2183 .writers
2184 .get(&writer)
2185 .map(|w| w.qos.reliability.max_blocking_time)
2186 else {
2187 return Err(Error::AlreadyDeleted);
2188 };
2189 let deadline = Instant::now() + blocking;
2190 loop {
2191 let Some(w) = g.writers.get_mut(&writer) else {
2192 return Err(Error::AlreadyDeleted);
2193 };
2194 if !w.is_full(&h) {
2195 break;
2196 }
2197 let now = Instant::now();
2198 if now >= deadline {
2199 return Err(Error::Timeout);
2200 }
2201 g = match self.acknowledged.wait_timeout(g, deadline - now) {
2202 Ok((g, _)) => g,
2203 Err(e) => e.into_inner().0,
2204 };
2205 if g.deleted {
2206 return Err(Error::AlreadyDeleted);
2207 }
2208 }
2209 let inner = &mut *g;
2210 let w = inner.writers.get_mut(&writer).expect("checked above");
2211 let change;
2212 let key_payload = matches!(op, WriteOp::Lifecycle { .. })
2215 && w.matched.iter().any(|r| {
2216 inner
2217 .spdp
2218 .participant(&r.prefix)
2219 .is_some_and(|p| p.vendor_id == OPENDDS)
2220 });
2221 #[cfg(feature = "shm")]
2222 let by_reference = matches!(&op, WriteOp::Value(p, ..) if p.is_loaned())
2223 && self.by_reference(inner, &writer);
2224 #[cfg(not(feature = "shm"))]
2225 let by_reference = false;
2226 let w = inner.writers.get_mut(&writer).expect("checked above");
2227 (sn, change) = w.add(h, op, timestamp, key_payload, by_reference)?;
2228 let now = Instant::now();
2229 out = w.rtps.poll(now);
2230 w.trim();
2231 inner.local_writer_asserted(writer, now);
2232 let w = inner.writers.get_mut(&writer).expect("checked above");
2233 let matched: Vec<Guid> = w.matched.iter().copied().collect();
2234 for r in matched {
2235 if r.prefix != self.prefix || directed.is_some_and(|d| d != r) {
2236 continue;
2237 }
2238 if let Some(st) = inner.readers.get_mut(&r) {
2239 let c = Incoming {
2240 writer,
2241 sequence_number: sn,
2242 source_timestamp: Some(timestamp),
2243 related_sample_identity: related,
2244 instance: h,
2245 change: change.clone(),
2246 };
2247 let k = st.accept(c);
2248 inner.changed(r, k);
2249 }
2250 }
2251 }
2252 self.flush();
2253 let mut last_err = None;
2257 let mut sent = false;
2258 for o in &out {
2259 let (ok, err) = self.send(&o.bytes, &o.locators);
2260 sent |= ok;
2261 if err.is_some() {
2262 last_err = err;
2263 }
2264 }
2265 match last_err {
2266 Some(e) if !sent => Err(e.into()),
2267 _ => Ok(sn),
2268 }
2269 }
2270
2271 #[cfg(feature = "shm")]
2276 fn by_reference(&self, inner: &Inner, writer: &Guid) -> bool {
2277 let (Some(shm), Some(w)) = (&self.shm, inner.writers.get(writer)) else {
2278 return false;
2279 };
2280 #[cfg(feature = "security")]
2281 if self.security.is_some() || self.psk.is_some() {
2282 return false;
2283 }
2284 w.qos.durability == DurabilityKind::Volatile
2285 && w.matched.iter().all(|r| {
2286 r.prefix == self.prefix
2288 || w.rtps
2289 .reader_destination(r)
2290 .is_some_and(|l| shm.reaches(&l))
2291 })
2292 }
2293
2294 #[cfg(feature = "shm")]
2299 pub(crate) fn writer_pool(
2300 &self,
2301 writer: &Guid,
2302 size: usize,
2303 ) -> Result<Option<Arc<rustorb_rtps::shm::Pool>>> {
2304 let Some(shm) = &self.shm else {
2305 return Ok(None);
2306 };
2307 #[cfg(feature = "security")]
2308 if self.security.is_some() || self.psk.is_some() {
2309 return Ok(None);
2310 }
2311 let mut g = self.lock()?;
2312 let w = g.writers.get_mut(writer).ok_or(Error::AlreadyDeleted)?;
2313 if let Some(p) = &w.pool
2314 && p.slot_size() >= size
2315 {
2316 return Ok(Some(p.clone()));
2317 }
2318 let slots = match w.qos.history {
2321 History::KeepLast(d) => 2 * d.max(1) + 2 * LOANS_KEPT,
2322 History::KeepAll => w.qos.resource_limits.max_samples.unwrap_or(32) + 2 * LOANS_KEPT,
2323 }
2324 .min(MAX_POOL_SLOTS);
2325 let pool = shm.create_pool(slots as u32, size)?;
2326 w.pool = Some(pool.clone());
2327 Ok(Some(pool))
2328 }
2329
2330 pub(crate) fn endpoint_data(&self, guid: &Guid) -> Option<EndpointData> {
2332 let g = self.lock_any();
2333 g.writers
2334 .get(guid)
2335 .map(|w| &w.data)
2336 .or_else(|| g.readers.get(guid).map(|r| &r.data))
2337 .or_else(|| g.sedp.remote_writer(guid))
2338 .or_else(|| g.sedp.remote_reader(guid))
2339 .cloned()
2340 }
2341
2342 pub(crate) fn last_sequence_number(&self, writer: &Guid) -> Result<SequenceNumber> {
2345 self.lock_any()
2346 .writers
2347 .get(writer)
2348 .map(|w| w.rtps.last_sn())
2349 .ok_or(Error::AlreadyDeleted)
2350 }
2351
2352 pub(crate) fn is_announced_to(&self, local: &Guid, prefix: &GuidPrefix) -> bool {
2355 self.lock_any().sedp.is_announced_to(local, prefix)
2356 }
2357
2358 pub(crate) fn update_endpoint(
2361 &self,
2362 guid: &Guid,
2363 f: impl FnOnce(&mut EndpointData),
2364 ) -> Result<()> {
2365 {
2366 let mut g = self.lock()?;
2367 let inner = &mut *g;
2368 let events = if let Some(w) = inner.writers.get_mut(guid) {
2369 f(&mut w.data);
2370 let data = w.data.clone();
2371 inner.sedp_add_writer(data)
2372 } else if let Some(r) = inner.readers.get_mut(guid) {
2373 f(&mut r.data);
2374 let data = r.data.clone();
2375 inner.sedp_add_reader(data)
2376 } else {
2377 return Err(Error::AlreadyDeleted);
2378 };
2379 apply_sedp_events(inner, events, Instant::now());
2380 }
2381 self.flush();
2382 Ok(())
2383 }
2384
2385 pub(crate) fn assert_writer_liveliness(&self, writer: &Guid) -> Result<()> {
2390 let out = {
2391 let mut g = self.lock()?;
2392 let inner = &mut *g;
2393 let Some(kind) = inner.writers.get(writer).map(|w| w.qos.liveliness.kind) else {
2394 return Ok(());
2395 };
2396 if kind == LivelinessKind::Automatic {
2397 return Ok(());
2398 }
2399 inner.local_writer_asserted(*writer, Instant::now());
2400 match inner.writers.get_mut(writer) {
2401 Some(w) if kind == LivelinessKind::ManualByTopic => w.rtps.liveliness_heartbeat(),
2402 _ => Vec::new(),
2403 }
2404 };
2405 self.flush();
2406 for o in &out {
2410 let _ = self.send(&o.bytes, &o.locators);
2411 }
2412 Ok(())
2413 }
2414
2415 pub(crate) fn wait_for_acknowledgments(&self, writer: &Guid, timeout: Duration) -> Result<()> {
2418 let deadline = Instant::now() + timeout;
2419 let mut g = self.lock()?;
2420 loop {
2421 match g.writers.get(writer) {
2422 None => return Ok(()),
2423 Some(w) if w.rtps.is_all_acked() => return Ok(()),
2424 Some(_) => {}
2425 }
2426 let now = Instant::now();
2427 if now >= deadline {
2428 return Err(Error::Timeout);
2429 }
2430 g = match self.acknowledged.wait_timeout(g, deadline - now) {
2431 Ok((g, _)) => g,
2432 Err(e) => e.into_inner().0,
2433 };
2434 if g.deleted {
2435 return Err(Error::AlreadyDeleted);
2436 }
2437 }
2438 }
2439}
2440
2441fn apply_sedp_events(inner: &mut Inner, events: Vec<SedpEvent>, now: Instant) {
2445 for e in events {
2446 match e {
2447 SedpEvent::Matched { local, remote } => {
2448 #[cfg(feature = "security")]
2449 if let Some(sec) = &inner.security
2450 && remote.prefix != local.prefix
2451 {
2452 let writer = inner.writers.contains_key(&local);
2453 let data = if writer {
2454 inner.sedp.remote_reader(&remote)
2455 } else {
2456 inner.sedp.remote_writer(&remote)
2457 };
2458 if !data.is_some_and(|d| sec.remote_allowed(d, !writer)) {
2459 continue;
2460 }
2461 sec.matched(local, remote, writer);
2462 }
2463 if let Some(w) = inner.writers.get_mut(&local) {
2464 if w.add_match(remote) {
2465 inner.pending.push((local, StatusMask::PUBLICATION_MATCHED));
2466 }
2467 if let Some(d) = inner.sedp.remote_reader(&remote) {
2468 w.rtps.add_matched_reader(
2469 remote,
2470 MatchedReader {
2471 unicast: d.unicast_locators.clone(),
2472 multicast: d.multicast_locators.clone(),
2473 reliable: d.reliability.kind == ReliabilityKind::Reliable,
2474 history: w.transient_local()
2477 && d.durability >= DurabilityKind::TransientLocal,
2478 },
2479 );
2480 }
2481 } else if let Some(r) = inner.readers.get_mut(&local) {
2482 let mut k = StatusMask::NONE;
2483 if r.add_match(remote) {
2484 k |= StatusMask::SUBSCRIPTION_MATCHED;
2485 }
2486 if let Some(d) = inner.sedp.remote_writer(&remote)
2487 && r.writer_matched(
2488 remote,
2489 d.liveliness.kind,
2490 d.liveliness.lease_duration.to_std(),
2491 now,
2492 )
2493 {
2494 k |= StatusMask::LIVELINESS_CHANGED;
2495 }
2496 if !k.is_empty() {
2497 inner.pending.push((local, k));
2498 }
2499 if let (Some(rtps), Some(d)) =
2500 (r.rtps.as_mut(), inner.sedp.remote_writer(&remote))
2501 {
2502 rtps.add_writer(
2503 remote,
2504 d.unicast_locators.clone(),
2505 d.multicast_locators.clone(),
2506 now,
2507 );
2508 }
2509 }
2510 }
2511 SedpEvent::Unmatched { local, remote } => {
2512 #[cfg(feature = "security")]
2513 if let Some(sec) = &inner.security {
2514 sec.unmatched(local, remote);
2515 }
2516 if let Some(w) = inner.writers.get_mut(&local) {
2517 if w.remove_match(&remote) {
2518 inner.pending.push((local, StatusMask::PUBLICATION_MATCHED));
2519 }
2520 w.rtps.remove_reader(&remote);
2521 w.trim();
2522 } else if let Some(r) = inner.readers.get_mut(&local) {
2523 r.fragments.remove(&remote);
2524 let k = r.writer_removed(&remote);
2525 if !k.is_empty() {
2526 inner.pending.push((local, k));
2527 }
2528 if let Some(rtps) = r.rtps.as_mut() {
2529 rtps.remove_writer(&remote);
2530 }
2531 }
2532 }
2533 SedpEvent::IncompatibleQos {
2534 local, policies, ..
2535 } => {
2536 if let Some(w) = inner.writers.get_mut(&local) {
2537 w.incompatible.add(&policies);
2538 inner
2539 .pending
2540 .push((local, StatusMask::OFFERED_INCOMPATIBLE_QOS));
2541 } else if let Some(r) = inner.readers.get_mut(&local) {
2542 r.incompatible.add(&policies);
2543 inner
2544 .pending
2545 .push((local, StatusMask::REQUESTED_INCOMPATIBLE_QOS));
2546 }
2547 }
2548 SedpEvent::InconsistentTopic { local, .. } => {
2549 let topic = if let Some(w) = inner.writers.get(&local) {
2550 Some(w.data.topic_name.clone())
2551 } else {
2552 inner.readers.get(&local).map(|r| r.data.topic_name.clone())
2553 };
2554 if let Some(topic) = topic {
2555 inner
2556 .inconsistent_topics
2557 .entry(topic.clone())
2558 .or_default()
2559 .add();
2560 inner.pending_topics.push(topic);
2561 }
2562 }
2563 _ => {}
2564 }
2565 }
2566 request_missing_types(inner);
2567}
2568
2569fn request_missing_types(inner: &mut Inner) {
2575 let mut asks: BTreeMap<GuidPrefix, Vec<TypeIdentifier>> = BTreeMap::new();
2576 let mut dependencies: BTreeMap<GuidPrefix, Vec<TypeIdentifier>> = BTreeMap::new();
2577 for (id, remote) in inner.sedp.unresolved_types() {
2578 let registry = inner.sedp.registry();
2579 let info = inner
2580 .sedp
2581 .remote_writer(&remote)
2582 .or_else(|| inner.sedp.remote_reader(&remote))
2583 .and_then(|d| d.type_information.as_ref());
2584 let mut ids = vec![id];
2585 if let Some(info) = info {
2586 ids.extend(registry.missing(info));
2587 let m = &info.minimal;
2588 let listed = i32::try_from(m.dependent_typeids.len()).unwrap_or(i32::MAX);
2589 let root = &m.typeid_with_size.type_id;
2590 if m.dependent_typeid_count > listed
2591 && inner.type_requests.insert((root.clone(), remote.prefix))
2592 {
2593 dependencies
2594 .entry(remote.prefix)
2595 .or_default()
2596 .push(root.clone());
2597 }
2598 }
2599 for id in ids {
2600 let id = id.scc_identifier().unwrap_or(id);
2603 if !registry.knows(&id) && inner.type_requests.insert((id.clone(), remote.prefix)) {
2604 asks.entry(remote.prefix).or_default().push(id);
2605 }
2606 }
2607 }
2608 for (server, type_ids) in asks {
2609 inner
2610 .typelookup
2611 .request(server, TypeLookupCall::GetTypes(GetTypesIn { type_ids }));
2612 }
2613 for (server, type_ids) in dependencies {
2614 inner.typelookup.request(
2615 server,
2616 TypeLookupCall::GetTypeDependencies(GetTypeDependenciesIn {
2617 type_ids,
2618 continuation_point: None,
2619 }),
2620 );
2621 }
2622}
2623
2624fn request_complete_types(inner: &mut Inner, server: GuidPrefix, info: &TypeInformation) {
2629 let c = &info.complete;
2630 let root = &c.typeid_with_size.type_id;
2631 let registry = inner.sedp.registry();
2632 let requests = &mut inner.type_requests;
2633 let type_ids: Vec<TypeIdentifier> = std::iter::once(&c.typeid_with_size)
2634 .chain(&c.dependent_typeids)
2635 .map(|t| {
2636 t.type_id
2637 .scc_identifier()
2638 .unwrap_or_else(|| t.type_id.clone())
2639 })
2640 .filter(|id| !registry.knows(id))
2641 .filter(|id| requests.insert((id.clone(), server)))
2642 .collect();
2643 let listed = i32::try_from(c.dependent_typeids.len()).unwrap_or(i32::MAX);
2644 let dependencies = c.dependent_typeid_count > listed
2645 && inner.dependency_requests.insert((root.clone(), server));
2646 if !type_ids.is_empty() {
2647 inner
2648 .typelookup
2649 .request(server, TypeLookupCall::GetTypes(GetTypesIn { type_ids }));
2650 }
2651 if dependencies {
2652 inner.typelookup.request(
2653 server,
2654 TypeLookupCall::GetTypeDependencies(GetTypeDependenciesIn {
2655 type_ids: vec![root.clone()],
2656 continuation_point: None,
2657 }),
2658 );
2659 }
2660}
2661
2662fn type_lookup_replied(inner: &mut Inner, r: TypeLookupReplied, now: Instant) {
2666 match r.reply.data {
2667 TypeLookupReturn::GetTypes(Ok(out)) => {
2668 let added = inner.sedp.registry_mut().add_pairs(&out.types).unwrap_or(0);
2670 inner.learnt_types += added;
2671 if added > 0 {
2672 let events = inner.sedp.rematch_unresolved();
2673 apply_sedp_events(inner, events, now);
2674 }
2675 }
2676 TypeLookupReturn::GetTypeDependencies(Ok(out)) if r.call.is_some() => {
2677 let registry = inner.sedp.registry();
2678 let type_ids: Vec<TypeIdentifier> = out
2679 .dependent_typeids
2680 .into_iter()
2681 .map(|t| t.type_id.scc_identifier().unwrap_or(t.type_id))
2682 .filter(|id| !registry.knows(id))
2683 .collect();
2684 let type_ids: Vec<TypeIdentifier> = type_ids
2685 .into_iter()
2686 .filter(|id| inner.type_requests.insert((id.clone(), r.server)))
2687 .collect();
2688 if !type_ids.is_empty() {
2689 inner
2690 .typelookup
2691 .request(r.server, TypeLookupCall::GetTypes(GetTypesIn { type_ids }));
2692 }
2693 }
2694 _ => {}
2695 }
2696}
2697
2698pub struct DomainParticipant {
2705 shared: Arc<Shared>,
2706 thread: Option<JoinHandle<()>>,
2707 #[cfg(feature = "security")]
2710 log_thread: Option<JoinHandle<()>>,
2711 #[cfg(feature = "security")]
2714 ocsp_thread: Option<(JoinHandle<()>, std::sync::mpsc::Sender<()>)>,
2715}
2716
2717impl std::fmt::Debug for DomainParticipant {
2718 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2719 f.debug_struct("DomainParticipant")
2720 .field("domain_id", &self.shared.domain_id)
2721 .field("guid_prefix", &self.shared.prefix)
2722 .finish()
2723 }
2724}
2725
2726impl DomainParticipant {
2727 pub fn new(domain_id: u32) -> Result<Self> {
2729 Self::with_config(ParticipantConfig::new(domain_id))
2730 }
2731
2732 pub fn with_config(config: ParticipantConfig) -> Result<Self> {
2734 let domain_id = config.udp.domain_id;
2735 let (transport, incoming) = UdpTransport::open(&config.udp)?;
2736 #[allow(unused_mut)]
2737 let mut prefix = GuidPrefix::generate(VENDOR_ID);
2738 #[cfg(feature = "security")]
2739 let security = match &config.security {
2740 Some(c) => {
2741 let s = Security::new(
2742 c,
2743 domain_id,
2744 prefix,
2745 SedpConfig::default().writer,
2746 SedpConfig::default().reader,
2747 )?;
2748 prefix = s.prefix();
2749 Some(Arc::new(s))
2750 }
2751 None => None,
2752 };
2753 #[cfg(feature = "security")]
2754 let psk_kind = match (&security, &config.psk) {
2755 (Some(s), psk) => {
2756 let k = s.rtps_psk_protection_kind();
2757 if k.is_protected() && psk.is_none() {
2758 return Err(Error::Security(format!(
2759 "the governance asks for rtps_psk_protection_kind {k:?}, and {} is not given",
2760 rustorb_dds_security::psk::SECRET_PASSPHRASE
2761 )));
2762 }
2763 k
2764 }
2765 (None, Some(c)) => c.protection_kind.unwrap_or(ProtectionKind::Encrypt),
2766 (None, None) => ProtectionKind::None,
2767 };
2768 #[cfg(feature = "security")]
2769 let psk = match &config.psk {
2770 Some(c) if psk_kind.is_protected() => Some(Arc::new(
2771 PskProtection::new(c, psk_kind, domain_id, "")
2772 .map_err(|e| Error::Security(format!("PSK: {e}")))?,
2773 )),
2774 _ => None,
2775 };
2776 let mut data = ParticipantData::new(prefix, VENDOR_ID);
2777 data.domain_id = Some(domain_id);
2778 data.available_builtin_endpoints.0 |=
2779 Sedp::BUILTIN_ENDPOINTS | Wlp::BUILTIN_ENDPOINTS | TypeLookup::BUILTIN_ENDPOINTS;
2780 data.metatraffic_unicast_locators = transport.discovery_unicast_locators();
2781 data.metatraffic_multicast_locators = transport.discovery_multicast_locators();
2782 data.default_unicast_locators = transport.user_unicast_locators();
2783 data.default_multicast_locators = transport.user_multicast_locators();
2784 #[cfg(feature = "shm")]
2785 let shm = if config.shared_memory {
2786 rustorb_rtps::shm::ShmTransport::open(
2788 &rustorb_rtps::shm::ShmConfig::default(),
2789 prefix,
2790 transport.injector(),
2791 )
2792 .ok()
2793 } else {
2794 None
2795 };
2796 #[cfg(feature = "shm")]
2797 if let Some(shm) = &shm {
2798 data.metatraffic_unicast_locators
2799 .push(shm.metatraffic_locator());
2800 data.default_unicast_locators.push(shm.user_locator());
2801 }
2802 data.lease_duration = rustorb_rtps::Duration::from_std(config.lease_duration);
2803 data.user_data = config.user_data.clone();
2804 #[cfg(feature = "security")]
2805 if let Some(s) = &security {
2806 s.announce(&mut data);
2807 } else if config.psk.is_some() {
2808 crate::security::announce_psk(&mut data, psk_kind);
2809 }
2810 let mut spdp_config = SpdpConfig::new(domain_id, transport.discovery_multicast_locators());
2811 spdp_config.announce_period = config.announce_period;
2812 let inner = Inner {
2813 spdp: Spdp::new(data, spdp_config),
2814 sedp: Sedp::new(prefix, VENDOR_ID, SedpConfig::default()),
2815 wlp: Wlp::new(
2816 prefix,
2817 VENDOR_ID,
2818 SedpConfig::default().writer,
2819 SedpConfig::default().reader,
2820 ),
2821 wlp_secure: None,
2822 spdp_secure: None,
2823 typelookup: TypeLookup::new(
2824 prefix,
2825 VENDOR_ID,
2826 SedpConfig::default().writer,
2827 SedpConfig::default().reader,
2828 ),
2829 type_requests: HashSet::new(),
2830 dependency_requests: HashSet::new(),
2831 learnt_types: 0,
2832 next_automatic: None,
2833 manual_pending: false,
2834 next_manual: Instant::now(),
2835 persistence_directory: config.effective_persistence_directory(),
2836 writer_config: config.writer,
2837 reader_config: config.reader,
2838 next_entity: 1,
2839 writers: HashMap::new(),
2840 readers: HashMap::new(),
2841 deleted: false,
2842 pending: Vec::new(),
2843 types: HashMap::new(),
2844 dynamic_types: HashMap::new(),
2845 inconsistent_topics: HashMap::new(),
2846 pending_topics: Vec::new(),
2847 topic_listeners: HashMap::new(),
2848 listener: None,
2849 #[cfg(feature = "security")]
2850 security: security.clone(),
2851 };
2852 #[cfg(feature = "security")]
2853 let inner = {
2854 let mut inner = inner;
2855 if let Some(s) = &inner.security {
2856 if s.discovery_protected() {
2857 inner.sedp.enable_secure();
2858 let mut secure = SpdpSecure::new(
2859 prefix,
2860 VENDOR_ID,
2861 SedpConfig::default().writer,
2862 SedpConfig::default().reader,
2863 );
2864 secure.write(inner.spdp.local());
2865 inner.spdp_secure = Some(secure);
2866 }
2867 if s.liveliness_protected() {
2868 inner.wlp_secure = Some(Wlp::new_secure(
2869 prefix,
2870 VENDOR_ID,
2871 SedpConfig::default().writer,
2872 SedpConfig::default().reader,
2873 ));
2874 }
2875 }
2876 inner
2877 };
2878 let shared = Arc::new_cyclic(|this| Shared {
2879 this: this.clone(),
2880 waitsets: Mutex::new(Vec::new()),
2881 transport,
2882 #[cfg(feature = "shm")]
2883 shm,
2884 prefix,
2885 domain_id,
2886 inner: Mutex::new(inner),
2887 data_arrived: Condvar::new(),
2888 acknowledged: Condvar::new(),
2889 stop: AtomicBool::new(false),
2890 drop_one_in: config.drop_one_in.filter(|n| *n > 0),
2891 #[cfg(feature = "security")]
2892 security,
2893 #[cfg(feature = "security")]
2894 psk,
2895 drop_state: AtomicU64::new(
2896 u64::from_le_bytes(prefix.0[4..12].try_into().expect("8 bytes")) | 1,
2897 ),
2898 });
2899 let s = shared.clone();
2900 let thread = std::thread::Builder::new()
2901 .name(format!("rustorb-dds-{domain_id}"))
2902 .spawn(move || run(s, incoming))?;
2903 #[allow(unused_mut)]
2904 let mut participant = DomainParticipant {
2905 shared,
2906 thread: Some(thread),
2907 #[cfg(feature = "security")]
2908 log_thread: None,
2909 #[cfg(feature = "security")]
2910 ocsp_thread: None,
2911 };
2912 #[cfg(feature = "security")]
2913 participant.start_security_log()?;
2914 #[cfg(feature = "security")]
2915 participant.start_ocsp_refresh()?;
2916 Ok(participant)
2917 }
2918
2919 #[cfg(feature = "security")]
2923 fn start_ocsp_refresh(&mut self) -> Result<()> {
2924 let Some(period) = self.shared.security.as_ref().and_then(|s| s.ocsp_refresh()) else {
2925 return Ok(());
2926 };
2927 let (tx, rx) = std::sync::mpsc::channel::<()>();
2928 let shared = self.shared.clone();
2929 let t = std::thread::Builder::new()
2930 .name(format!("rustorb-dds-{}-ocsp", self.shared.domain_id))
2931 .spawn(move || {
2932 while let Err(std::sync::mpsc::RecvTimeoutError::Timeout) = rx.recv_timeout(period)
2933 {
2934 let Some(sec) = shared.security.clone() else {
2935 return;
2936 };
2937 for prefix in sec.check_ocsp() {
2938 let _ = revoke(&shared, &sec, prefix);
2939 }
2940 }
2941 })?;
2942 self.ocsp_thread = Some((t, tx));
2943 Ok(())
2944 }
2945
2946 #[cfg(feature = "security")]
2950 fn start_security_log(&mut self) -> Result<()> {
2951 use crate::security_log::{BuiltinLoggingTypeV2, LOG_TOPIC};
2952 let Some(logger) = self
2953 .shared
2954 .security
2955 .as_ref()
2956 .and_then(|s| s.logger())
2957 .filter(|l| l.options().distribute)
2958 .cloned()
2959 else {
2960 return Ok(());
2961 };
2962 let topic = self.create_topic::<BuiltinLoggingTypeV2>(LOG_TOPIC)?;
2963 let writer = self.create_publisher()?.create_datawriter_with_qos(
2964 &topic,
2965 DataWriterQos {
2966 history: History::KeepLast(64),
2967 ..DataWriterQos::default()
2968 },
2969 )?;
2970 let (tx, rx) = std::sync::mpsc::channel::<BuiltinLoggingTypeV2>();
2971 logger.attach(tx);
2972 self.log_thread = Some(
2973 std::thread::Builder::new()
2974 .name(format!("rustorb-dds-{}-log", self.shared.domain_id))
2975 .spawn(move || {
2976 for m in rx {
2977 let _ = writer.write(&m);
2978 }
2979 })?,
2980 );
2981 Ok(())
2982 }
2983
2984 pub fn domain_id(&self) -> u32 {
2986 self.shared.domain_id
2987 }
2988
2989 pub fn guid(&self) -> Guid {
2991 Guid::new(self.shared.prefix, EntityId::PARTICIPANT)
2992 }
2993
2994 pub fn register_type<T: TopicType + DescribeType>(&self) -> Result<()> {
3005 let objects = TypeObjects::of::<T>()
3006 .map_err(|_| Error::Unsupported("a type that cannot be described"))?;
3007 let ty = DynamicType::new(T::describe_type());
3008 self.add_type(T::TYPE_NAME, objects, ty).map(|_| ())
3009 }
3010
3011 pub fn register_dynamic_type(&self, ty: &DynamicType) -> Result<()> {
3018 let objects = TypeObjects::new(ty.as_type())?;
3019 if !self.add_type(&ty.get_name(), objects, ty.clone())? {
3020 return Err(Error::PreconditionNotMet);
3021 }
3022 Ok(())
3023 }
3024
3025 fn add_type(&self, name: &str, objects: TypeObjects, ty: DynamicType) -> Result<bool> {
3028 {
3029 let mut g = self.shared.lock()?;
3030 let inner = &mut *g;
3031 if let Some(known) = inner.types.get(name) {
3032 return Ok(known.information == objects.information);
3033 }
3034 inner.sedp.registry_mut().add_type(&objects);
3035 inner.types.insert(name.to_owned(), objects);
3036 inner.dynamic_types.insert(name.to_owned(), ty);
3037 let events = inner.sedp.rematch_unresolved();
3038 apply_sedp_events(inner, events, Instant::now());
3039 }
3040 self.shared.flush();
3041 Ok(true)
3042 }
3043
3044 pub fn create_dynamic_topic(&self, name: &str, ty: &DynamicType) -> Result<Topic<DynamicData>> {
3051 self.register_dynamic_type(ty)?;
3052 Ok(Topic::new(
3053 name,
3054 self.shared.clone(),
3055 Arc::new(Dynamic::new(ty)),
3056 ))
3057 }
3058
3059 pub fn discover_topic_type(
3070 &self,
3071 topic_name: &str,
3072 timeout: Duration,
3073 ) -> Result<Option<DynamicType>> {
3074 let deadline = Instant::now() + timeout;
3075 loop {
3076 {
3077 let mut g = self.shared.lock()?;
3078 let inner = &mut *g;
3079 let infos: Vec<(GuidPrefix, TypeInformation)> = inner
3080 .sedp
3081 .remote_writers()
3082 .chain(inner.sedp.remote_readers())
3083 .filter(|d| d.topic_name == topic_name)
3084 .filter_map(|d| Some((d.guid.prefix, d.type_information.clone()?)))
3085 .collect();
3086 for (_, info) in &infos {
3087 let root = &info.complete.typeid_with_size.type_id;
3088 if let Ok(ty) = DynamicTypeBuilderFactory::create_type_w_type_identifier(
3089 root,
3090 inner.sedp.registry(),
3091 ) {
3092 return Ok(Some(ty));
3093 }
3094 }
3095 for (server, info) in &infos {
3096 request_complete_types(inner, *server, info);
3097 }
3098 }
3099 self.shared.flush();
3100 if Instant::now() >= deadline {
3101 return Ok(None);
3102 }
3103 std::thread::sleep(Duration::from_millis(20));
3104 }
3105 }
3106
3107 pub fn learnt_types(&self) -> usize {
3112 self.shared.lock_any().learnt_types
3113 }
3114
3115 pub fn create_topic<T: TopicType + 'static>(&self, name: &str) -> Result<Topic<T>> {
3117 Ok(Topic::new(
3118 name,
3119 self.shared.clone(),
3120 Arc::new(Typed::<T>::new()),
3121 ))
3122 }
3123
3124 pub fn create_contentfilteredtopic<T>(
3136 &self,
3137 name: &str,
3138 related: &Topic<T>,
3139 filter_expression: &str,
3140 expression_parameters: &[String],
3141 ) -> Result<ContentFilteredTopic<T>> {
3142 let ty = self
3143 .shared
3144 .dynamic_type(related.type_name())?
3145 .ok_or(Error::PreconditionNotMet)?;
3146 let filter = ContentFilter::new(&ty, filter_expression, expression_parameters)?;
3147 Ok(ContentFilteredTopic::new(name, related, filter))
3148 }
3149
3150 pub fn create_publisher(&self) -> Result<Publisher> {
3152 self.create_publisher_with_qos(PublisherQos::default())
3153 }
3154
3155 pub fn create_publisher_with_qos(&self, qos: PublisherQos) -> Result<Publisher> {
3157 Ok(Publisher::new(
3158 self.shared.clone(),
3159 PublisherEntity::new(qos),
3160 ))
3161 }
3162
3163 pub fn create_subscriber(&self) -> Result<Subscriber> {
3165 self.create_subscriber_with_qos(SubscriberQos::default())
3166 }
3167
3168 pub fn create_subscriber_with_qos(&self, qos: SubscriberQos) -> Result<Subscriber> {
3170 Ok(Subscriber::from_entity(
3171 self.shared.clone(),
3172 SubscriberEntity::new(qos),
3173 ))
3174 }
3175
3176 pub fn set_listener(
3182 &self,
3183 listener: impl DomainParticipantListener + 'static,
3184 mask: StatusMask,
3185 ) {
3186 self.shared.lock_any().listener = Some((Arc::new(listener), mask));
3187 }
3188
3189 pub fn clear_listener(&self) {
3191 self.shared.lock_any().listener = None;
3192 }
3193
3194 pub fn assert_liveliness(&self) -> Result<()> {
3198 self.shared.lock()?.participant_asserted(Instant::now());
3199 self.shared.flush();
3200 Ok(())
3201 }
3202
3203 pub fn discovered_participants(&self) -> Vec<GuidPrefix> {
3205 let g = self.shared.lock_any();
3206 let mut v: Vec<GuidPrefix> = g.spdp.participants().map(|p| p.guid_prefix).collect();
3207 v.sort();
3208 v
3209 }
3210
3211 #[cfg(feature = "security")]
3220 pub fn revoke_participant(&self, prefix: GuidPrefix) -> Result<bool> {
3221 let sec = self
3222 .shared
3223 .security
3224 .clone()
3225 .ok_or(Error::PreconditionNotMet)?;
3226 revoke(&self.shared, &sec, prefix)
3227 }
3228
3229 #[cfg(feature = "security")]
3240 pub fn revise_keys(&self) -> Result<i32> {
3241 let sec = self
3242 .shared
3243 .security
3244 .as_ref()
3245 .ok_or(Error::PreconditionNotMet)?;
3246 Ok(sec.revise_keys(Instant::now()))
3247 }
3248}
3249
3250#[cfg(feature = "security")]
3252fn revoke(shared: &Shared, sec: &Security, prefix: GuidPrefix) -> Result<bool> {
3253 let now = Instant::now();
3254 if !sec.revoke_participant(&prefix, now) {
3255 return Ok(false);
3256 }
3257 {
3258 let mut g = shared.lock()?;
3259 participant_event(
3260 &mut g,
3261 ParticipantEvent::Removed(prefix, rustorb_rtps::spdp::RemovalReason::Disposed),
3262 now,
3263 );
3264 }
3265 shared.flush();
3266 Ok(true)
3267}
3268
3269impl Drop for DomainParticipant {
3270 fn drop(&mut self) {
3271 #[cfg(feature = "security")]
3272 if let Some((t, stop)) = self.ocsp_thread.take() {
3273 drop(stop);
3274 let _ = t.join();
3275 }
3276 #[cfg(feature = "security")]
3279 if let Some(t) = self.log_thread.take() {
3280 if let Some(l) = self.shared.security.as_ref().and_then(|s| s.logger()) {
3281 l.close();
3282 }
3283 let _ = t.join();
3284 }
3285 let disposed = {
3289 let mut g = self.shared.lock_any();
3290 g.spdp_secure.as_mut().map(SpdpSecure::dispose)
3291 };
3292 if let Some(sn) = disposed {
3293 let deadline = Instant::now() + SECURE_DISPOSE_WAIT;
3294 while Instant::now() < deadline
3295 && !self
3296 .shared
3297 .lock_any()
3298 .spdp_secure
3299 .as_ref()
3300 .is_none_or(|s| s.is_acked_by_all(sn))
3301 {
3302 std::thread::sleep(Duration::from_millis(5));
3303 }
3304 }
3305 self.shared.stop.store(true, Ordering::Relaxed);
3306 if let Some(t) = self.thread.take() {
3307 let _ = t.join();
3308 }
3309 let mut g = self.shared.lock_any();
3310 g.deleted = true;
3311 for w in g.writers.values_mut() {
3315 w.store = None;
3316 }
3317 let (bytes, to) = g.spdp.dispose();
3320 let to = to.to_vec();
3321 drop(g);
3322 let _ = self.shared.send(&bytes, &to);
3323 self.shared.data_arrived.notify_all();
3324 self.shared.acknowledged.notify_all();
3325 self.shared.wake_waitsets();
3326 }
3327}
3328
3329const SECURE_DISPOSE_WAIT: Duration = Duration::from_millis(300);
3332
3333const MAX_WAIT: Duration = Duration::from_millis(50);
3335
3336fn run(shared: Arc<Shared>, incoming: UdpIncoming) {
3337 while !shared.stop.load(Ordering::Relaxed) {
3338 let wait = {
3339 let g = shared.lock_any();
3340 let manual = g.manual_pending.then_some(g.next_manual);
3341 let next = [
3342 g.spdp.next_deadline(),
3343 g.sedp.next_deadline(),
3344 g.wlp.next_deadline(),
3345 g.wlp_secure.as_ref().and_then(Wlp::next_deadline),
3346 g.spdp_secure.as_ref().and_then(SpdpSecure::next_deadline),
3347 g.typelookup.next_deadline(),
3348 g.next_automatic,
3349 manual,
3350 #[cfg(feature = "security")]
3351 g.security.as_ref().and_then(|s| s.next_deadline()),
3352 ]
3353 .into_iter()
3354 .chain(g.writers.values().map(|w| w.rtps.next_deadline()))
3355 .chain(
3356 g.readers
3357 .values()
3358 .map(|r| r.rtps.as_ref().and_then(|r| r.next_deadline())),
3359 )
3360 .flatten()
3361 .min();
3362 next.map_or(MAX_WAIT, |t| {
3363 t.saturating_duration_since(Instant::now()).min(MAX_WAIT)
3364 })
3365 };
3366 let mut datagrams = Vec::new();
3367 if let Some(d) = incoming.recv_timeout(wait) {
3368 datagrams.push(d);
3369 while let Some(d) = incoming.try_recv() {
3370 datagrams.push(d);
3371 }
3372 }
3373 step(&shared, datagrams);
3374 }
3375}
3376
3377fn step(shared: &Shared, datagrams: Vec<Datagram>) {
3379 let now = Instant::now();
3380 let mut out: Vec<(Vec<u8>, Vec<Locator>)> = Vec::new();
3381 {
3382 let mut g = shared.lock_any();
3383 let inner = &mut *g;
3384 let mut acked = false;
3385 for d in datagrams {
3386 #[cfg(feature = "security")]
3390 let d = match &shared.psk {
3391 Some(psk) => match rustorb_dds_security::crypto::message_prefix_flags(&d.data) {
3392 Some(f) if f & rustorb_dds_security::crypto::prefix_flag::PSK != 0 => {
3393 match psk.decode(&d.data) {
3394 Ok(b) => Datagram { data: b, ..d },
3395 Err(_) => continue,
3396 }
3397 }
3398 Some(_) if inner.security.is_some() => d,
3399 _ => continue,
3400 },
3401 None => d,
3402 };
3403 #[cfg(feature = "security")]
3404 let d = match &inner.security {
3405 Some(sec) => match sec.decode(&d.data) {
3406 Some(b) => {
3407 let b = b.into_owned();
3408 if matches!(
3409 d.channel,
3410 Channel::DiscoveryMulticast | Channel::DiscoveryUnicast
3411 ) {
3412 sec.handle_discovery(&b, now);
3413 }
3414 Datagram { data: b, ..d }
3415 }
3416 None => continue,
3417 },
3418 None => d,
3419 };
3420 match d.channel {
3421 Channel::DiscoveryMulticast | Channel::DiscoveryUnicast => {
3422 for e in inner.spdp.handle_message(&d.data, now) {
3423 participant_event(inner, e, now);
3424 }
3425 let events = inner.sedp.handle_message(&d.data, now);
3426 apply_sedp_events(inner, events, now);
3427 for a in inner.wlp.handle_message(&d.data, now) {
3428 inner.remote_participant_asserted(a.participant, a.kind, now);
3429 }
3430 if let Some(w) = inner.wlp_secure.as_mut() {
3431 for a in w.handle_message(&d.data, now) {
3432 inner.remote_participant_asserted(a.participant, a.kind, now);
3433 }
3434 }
3435 if let Some(s) = inner.spdp_secure.as_mut() {
3436 for e in s.handle_message(&d.data, now) {
3437 if let Some(e) = inner.spdp.handle_secure(e, now) {
3438 participant_event(inner, e, now);
3439 }
3440 }
3441 }
3442 let replies =
3443 inner
3444 .typelookup
3445 .handle_message(&d.data, now, inner.sedp.registry());
3446 for r in replies {
3447 type_lookup_replied(inner, r, now);
3448 }
3449 }
3450 Channel::UserMulticast | Channel::UserUnicast => {
3451 if shared.should_drop() {
3452 continue;
3453 }
3454 acked |= user_traffic(shared.prefix, inner, &d.data, now);
3455 }
3456 }
3457 }
3458 for e in inner.spdp.remove_expired(now) {
3459 participant_event(inner, e, now);
3460 }
3461 inner.check_timers(now);
3462 if let Some((bytes, to)) = inner.spdp.poll_announce(now) {
3463 out.push((bytes, to.to_vec()));
3464 }
3465 for o in inner.sedp.poll(now) {
3466 out.push((o.bytes, o.locators));
3467 }
3468 for o in inner.wlp.poll(now) {
3469 out.push((o.bytes, o.locators));
3470 }
3471 if let Some(w) = inner.wlp_secure.as_mut() {
3472 for o in w.poll(now) {
3473 out.push((o.bytes, o.locators));
3474 }
3475 }
3476 if let Some(s) = inner.spdp_secure.as_mut() {
3477 for o in s.poll(now) {
3478 out.push((o.bytes, o.locators));
3479 }
3480 }
3481 for o in inner.typelookup.poll(now) {
3482 out.push((o.bytes, o.locators));
3483 }
3484 #[cfg(feature = "security")]
3485 if let Some(sec) = inner.security.clone() {
3486 let (o, events) = sec.poll(now);
3487 out.extend(o.into_iter().map(|o| (o.bytes, o.locators)));
3488 for e in events {
3489 match e {
3490 PeerEvent::Ready(p) => participant_ready(inner, &p, now),
3491 }
3492 }
3493 }
3494 for w in inner.writers.values_mut() {
3495 for o in w.rtps.poll(now) {
3496 out.push((o.bytes, o.locators));
3497 }
3498 w.trim();
3499 }
3500 for r in inner.readers.values_mut() {
3501 if let Some(rtps) = r.rtps.as_mut() {
3502 for o in rtps.poll(now) {
3503 out.push((o.bytes, o.locators));
3504 }
3505 }
3506 }
3507 if acked {
3508 shared.acknowledged.notify_all();
3509 }
3510 }
3511 for (bytes, to) in out {
3512 let _ = shared.send(&bytes, &to);
3515 }
3516 shared.flush();
3517}
3518
3519fn participant_event(inner: &mut Inner, e: ParticipantEvent, now: Instant) {
3520 match e {
3521 ParticipantEvent::Discovered(p) | ParticipantEvent::Updated(p) => {
3522 #[cfg(feature = "security")]
3523 if let Some(sec) = &inner.security
3524 && !sec.participant_discovered(&p, now)
3525 {
3526 return;
3527 }
3528 participant_ready(inner, &p, now);
3529 }
3530 ParticipantEvent::Removed(prefix, _) => {
3531 #[cfg(feature = "security")]
3532 if let Some(sec) = &inner.security {
3533 sec.participant_removed(&prefix);
3534 }
3535 inner.wlp.remove_participant(&prefix);
3536 if let Some(w) = inner.wlp_secure.as_mut() {
3537 w.remove_participant(&prefix);
3538 }
3539 if let Some(s) = inner.spdp_secure.as_mut() {
3540 s.remove_participant(&prefix);
3541 }
3542 inner.typelookup.remove_participant(&prefix);
3543 inner.type_requests.retain(|(_, p)| *p != prefix);
3544 let events = inner.sedp.remove_participant(&prefix);
3545 apply_sedp_events(inner, events, now);
3546 }
3547 }
3548}
3549
3550fn participant_ready(inner: &mut Inner, p: &ParticipantData, now: Instant) {
3553 inner.sedp.add_participant(p, now);
3554 inner.wlp.add_participant(p, now);
3555 if let Some(w) = inner.wlp_secure.as_mut() {
3556 w.add_participant(p, now);
3557 }
3558 if let Some(s) = inner.spdp_secure.as_mut() {
3559 s.add_participant(p, now);
3560 }
3561 inner.typelookup.add_participant(p, now);
3562}
3563
3564fn user_traffic(local: GuidPrefix, inner: &mut Inner, bytes: &[u8], now: Instant) -> bool {
3568 let mut acked = false;
3569 let Some((_, received)) = receive(bytes, local) else {
3570 return false;
3571 };
3572 for r in received {
3573 let src = r.source_prefix;
3574 match r.submessage {
3575 Submessage::AckNack(a) => {
3576 if let Some(w) = inner.writers.get_mut(&Guid::new(local, a.writer_id)) {
3577 w.rtps.handle_acknack(Guid::new(src, a.reader_id), &a, now);
3578 w.trim();
3579 acked = true;
3580 }
3581 }
3582 Submessage::Data(d) => {
3583 let writer = Guid::new(src, d.writer_id);
3584 inner.remote_writer_asserted(&writer, now);
3585 for_readers(inner, d.reader_id, |st| match st.rtps.as_mut() {
3586 Some(rtps) => rtps.handle_data(writer, &d, r.timestamp),
3587 None => vec![Change {
3588 writer,
3589 sequence_number: d.writer_sn,
3590 inline_qos: d.inline_qos.clone(),
3591 payload: d.serialized_payload.clone(),
3592 timestamp: r.timestamp,
3593 }],
3594 });
3595 }
3596 Submessage::DataFrag(d) => {
3597 let writer = Guid::new(src, d.writer_id);
3598 inner.remote_writer_asserted(&writer, now);
3599 for_readers(inner, d.reader_id, |st| match st.rtps.as_mut() {
3600 Some(rtps) => rtps.handle_data_frag(writer, &d, r.timestamp),
3601 None if st.matched.contains(&writer) => {
3604 let limits = st.reassembly;
3605 st.fragments
3606 .entry(writer)
3607 .or_insert_with(|| Reassembler::new(limits, Keep::Highest))
3608 .add(writer, &d, r.timestamp)
3609 .into_iter()
3610 .collect()
3611 }
3612 None => Vec::new(),
3613 });
3614 }
3615 Submessage::HeartbeatFrag(h) => {
3616 let writer = Guid::new(src, h.writer_id);
3617 for_readers(inner, h.reader_id, |st| {
3618 if let Some(rtps) = st.rtps.as_mut() {
3619 rtps.handle_heartbeat_frag(writer, &h, now);
3620 }
3621 Vec::new()
3622 });
3623 }
3624 Submessage::NackFrag(n) => {
3625 if let Some(w) = inner.writers.get_mut(&Guid::new(local, n.writer_id)) {
3626 w.rtps.handle_nackfrag(Guid::new(src, n.reader_id), &n, now);
3627 }
3628 }
3629 Submessage::Gap(gap) => {
3630 let writer = Guid::new(src, gap.writer_id);
3631 for_readers(inner, gap.reader_id, |st| match st.rtps.as_mut() {
3632 Some(rtps) => rtps.handle_gap(writer, &gap),
3633 None => Vec::new(),
3634 });
3635 }
3636 Submessage::Heartbeat(h) => {
3637 let writer = Guid::new(src, h.writer_id);
3638 if h.liveliness_flag {
3639 inner.remote_writer_asserted(&writer, now);
3641 }
3642 for_readers(inner, h.reader_id, |st| match st.rtps.as_mut() {
3643 Some(rtps) => rtps.handle_heartbeat(writer, &h, now),
3644 None => Vec::new(),
3645 });
3646 }
3647 _ => {}
3648 }
3649 }
3650 acked
3651}
3652
3653fn for_readers(
3657 inner: &mut Inner,
3658 reader_id: EntityId,
3659 mut f: impl FnMut(&mut ReaderState) -> Vec<Change>,
3660) {
3661 for (rg, st) in inner.readers.iter_mut() {
3662 if reader_id != EntityId::UNKNOWN && reader_id != rg.entity_id {
3663 continue;
3664 }
3665 for c in f(st) {
3666 let Some(c) = st.incoming(c) else {
3667 continue;
3668 };
3669 let k = st.accept(c);
3670 if !k.is_empty() {
3671 inner.pending.push((*rg, k));
3672 }
3673 }
3674 }
3675}
3676
3677#[cfg(test)]
3678mod padding_tests {
3679 use super::drop_missing_padding;
3680
3681 #[test]
3682 fn padding_counted_but_not_sent_is_dropped() {
3683 let mut p = vec![0, 1, 0, 2, 1, 0, 0, 0, 14, 0, 0, 0];
3685 p.extend_from_slice(b"Hello, world!\0");
3686 drop_missing_padding(&mut p);
3687 assert_eq!(p[3], 0);
3688 let mut q = vec![0, 1, 0, 2, 1, 0, 0, 0, 14, 0, 0, 0];
3690 q.extend_from_slice(b"Hello, world!\0\0\0");
3691 drop_missing_padding(&mut q);
3692 assert_eq!(q[3], 2);
3693 }
3694}
3695
3696#[cfg(test)]
3697mod property_tests {
3698 use super::*;
3699
3700 #[test]
3701 fn properties_without_dds_sec_are_ignored() {
3702 let mut c = ParticipantConfig::new(0);
3703 c.set_properties([("some.vendor.thing", "1")]).unwrap();
3704 #[cfg(feature = "security")]
3705 assert!(c.security.is_none());
3706 }
3707
3708 #[cfg(not(feature = "security"))]
3709 #[test]
3710 fn dds_sec_properties_need_the_feature() {
3711 let mut c = ParticipantConfig::new(0);
3712 let e = c
3713 .set_properties([("dds.sec.auth.identity_ca", "file:ca.pem")])
3714 .unwrap_err();
3715 assert!(matches!(e, Error::Unsupported(_)));
3716 }
3717
3718 #[cfg(feature = "security")]
3719 #[test]
3720 fn dds_sec_properties_make_the_security_config() {
3721 let mut c = ParticipantConfig::new(0);
3722 let e = c
3723 .set_properties([("dds.sec.auth.identity_ca", "file:ca.pem")])
3724 .unwrap_err();
3725 assert!(e.to_string().contains("dds.sec.access.permissions"), "{e}");
3726 let props: Vec<(&str, String)> = SecurityConfig::PROPERTIES
3727 .iter()
3728 .map(|n| (*n, format!("file:{n}")))
3729 .collect();
3730 c.set_properties(props.iter().map(|(n, v)| (*n, v.as_str())))
3731 .unwrap();
3732 let s = c.security.unwrap();
3733 assert_eq!(s.identity_ca, "file:dds.sec.auth.identity_ca");
3734 assert_eq!(s.permissions, "file:dds.sec.access.permissions");
3735 }
3736}