diff --git a/src/dds/no_key/datareader.rs b/src/dds/no_key/datareader.rs index 31688953..9cc84844 100644 --- a/src/dds/no_key/datareader.rs +++ b/src/dds/no_key/datareader.rs @@ -13,7 +13,7 @@ use crate::{ qos::{HasQoSPolicy, QosPolicies}, readcondition::ReadCondition, result::ReadResult, - statusevents::DataReaderStatus, + statusevents::{DataReaderStatus, SubscriptionMatchedStatus}, with_key::{ datareader as datareader_with_key, datasample::{DataSample as WithKeyDataSample, Sample}, @@ -422,6 +422,43 @@ where } */ + /// Reads the SUBSCRIPTION_MATCHED status of this DataReader: how many + /// DataWriters it is matched with now, and how many matches there have been + /// since it was created. + /// + /// The counts are those of the RTPS Reader itself. They do not come from the + /// status event stream, so they are right also when nothing reads that + /// stream and it has dropped events. Each `count_change()` is the change + /// since the previous call on this DataReader. + /// + /// See DDS Spec 1.4 Section 2.2.4.1 Communication Status. + /// + /// # Examples + /// + /// ``` + /// # use serde::{Serialize, Deserialize}; + /// # use rustdds::*; + /// # use rustdds::no_key::DataReader; + /// # use rustdds::serialization::CDRDeserializerAdapter; + /// # + /// let domain_participant = DomainParticipant::new(0).unwrap(); + /// let qos = QosPolicyBuilder::new().build(); + /// let subscriber = domain_participant.create_subscriber(&qos).unwrap(); + /// + /// #[derive(Serialize, Deserialize)] + /// struct SomeType {} + /// + /// // NoKey is important + /// let topic = domain_participant.create_topic("some_topic".to_string(), "SomeType".to_string(), &qos, TopicKind::NoKey).unwrap(); + /// let data_reader = subscriber.create_datareader_no_key::>(&topic, None).unwrap(); + /// + /// let matched = data_reader.get_subscription_matched_status(); + /// println!("{} writers now, {} ever", matched.current.count(), matched.total.count()); + /// ``` + pub fn get_subscription_matched_status(&self) -> SubscriptionMatchedStatus { + self.keyed_datareader.get_subscription_matched_status() + } + /// An async stream for reading the (bare) data samples pub fn async_bare_sample_stream(self) -> BareDataReaderStream { BareDataReaderStream { diff --git a/src/dds/no_key/datawriter.rs b/src/dds/no_key/datawriter.rs index c9869b86..cad7ef75 100644 --- a/src/dds/no_key/datawriter.rs +++ b/src/dds/no_key/datawriter.rs @@ -9,7 +9,7 @@ use crate::{ pubsub::Publisher, qos::{HasQoSPolicy, QosPolicies}, result::{unwrap_no_key_write_error, WriteResult}, - statusevents::{DataWriterStatus, StatusReceiverStream}, + statusevents::{DataWriterStatus, PublicationMatchedStatus, StatusReceiverStream}, topic::Topic, with_key::datawriter as datawriter_with_key, }, @@ -221,12 +221,27 @@ where self.keyed_datawriter.get_offered_incompatible_qos_status() } - /// Unimplemented. Do not use. + */ + + /// Reads the PUBLICATION_MATCHED status of this DataWriter: how many + /// DataReaders it is matched with now, and how many matches there have been + /// since it was created. + /// + /// The counts are those of the RTPS Writer itself. They do not come from the + /// status event stream, so they are right also when nothing reads that + /// stream and it has dropped events. Each `count_change()` is the change + /// since the previous call on this DataWriter. + /// + /// The call is cheap enough to make before every write, for example to skip + /// producing a sample that nobody would receive. Skipping is right only for + /// a DataWriter with volatile durability, which keeps nothing for readers + /// that match later, and automatic liveliness, which no write has to assert. + /// + /// See DDS Spec 1.4 Section 2.2.4.1 Communication Status. /// /// # Examples /// - // TODO: enable run when implemented - /// ```no_run + /// ``` /// # use serde::{Serialize, Deserialize}; /// # use rustdds::*; /// # use rustdds::no_key::DataWriter; @@ -236,21 +251,21 @@ where /// let qos = QosPolicyBuilder::new().build(); /// let publisher = domain_participant.create_publisher(&qos).unwrap(); /// - /// # #[derive(Serialize, Deserialize)] - /// # struct SomeType {} - /// # + /// #[derive(Serialize, Deserialize, Debug)] + /// struct SomeType { a: i32 } + /// /// // NoKey is important /// let topic = domain_participant.create_topic("some_topic".to_string(), "SomeType".to_string(), &qos, TopicKind::NoKey).unwrap(); - /// let data_writer = publisher.create_datawriter_no_key::>(topic, None).unwrap(); + /// let data_writer = publisher.create_datawriter_no_key::>(&topic, None).unwrap(); /// - /// if let Ok(status) = data_writer.get_publication_matched_status() { - /// // Do something + /// if data_writer.get_publication_matched_status().current.count() > 0 { + /// data_writer.write(SomeType { a: 1 }, None).unwrap(); /// } /// ``` - pub fn get_publication_matched_status(&self) -> Result { + pub fn get_publication_matched_status(&self) -> PublicationMatchedStatus { self.keyed_datawriter.get_publication_matched_status() } - */ + /// Topic this DataWriter is connected to. /// /// # Examples diff --git a/src/dds/no_key/simpledatareader.rs b/src/dds/no_key/simpledatareader.rs index fc28a05e..12c4174d 100644 --- a/src/dds/no_key/simpledatareader.rs +++ b/src/dds/no_key/simpledatareader.rs @@ -87,6 +87,22 @@ where self.keyed_simpledatareader.guid() } + /// Reads the SUBSCRIPTION_MATCHED status of this DataReader: how many + /// DataWriters it is matched with now, and how many matches there have been + /// since it was created. + /// + /// The counts are those of the RTPS Reader itself. They do not come from the + /// status event stream, so they are right also when nothing reads that + /// stream and it has dropped events. Each `count_change()` is the change + /// since the previous call on this DataReader. + /// + /// See DDS Spec 1.4 Section 2.2.4.1 Communication Status. + pub fn get_subscription_matched_status(&self) -> SubscriptionMatchedStatus { + self + .keyed_simpledatareader + .get_subscription_matched_status() + } + pub fn as_async_stream( &self, ) -> impl FusedStream>> + '_ diff --git a/src/dds/pubsub.rs b/src/dds/pubsub.rs index 1433d9e4..7f263c88 100644 --- a/src/dds/pubsub.rs +++ b/src/dds/pubsub.rs @@ -21,7 +21,7 @@ use crate::{ participant::*, qos::*, result::{CreateError, CreateResult, WaitResult}, - statusevents::{sync_status_channel, DataReaderStatus}, + statusevents::{sync_status_channel, DataReaderStatus, MatchedCounts}, topic::*, with_key, with_key::{ @@ -481,6 +481,8 @@ impl InnerPublisher { { // Status reports back from Writer to DataWriter. let (status_sender, status_receiver) = sync_status_channel(4)?; + // The Writer's matched-reader counts, for `get_publication_matched_status`. + let matched_counts = Arc::new(MatchedCounts::default()); // DDS Spec 2.2.2.4.1.5 create_datawriter: // If no QoS is specified, we should take the Publisher default @@ -618,6 +620,7 @@ impl InnerPublisher { doorbell.clone(), self.discovery_command.clone(), status_receiver, + Arc::clone(&matched_counts), )?; // Construct security info if needed @@ -700,6 +703,7 @@ impl InnerPublisher { like_stateless: writer_like_stateless, qos_policies: writer_qos, status_sender, + matched_counts, security_plugins: self.security_plugins_handle.clone(), }; @@ -1129,6 +1133,8 @@ impl InnerSubscriber { let (send, rec) = crate::mio_source::notification_channel(4); // status change channel from Reader to DataReader let (status_sender, status_receiver) = sync_status_channel::(4)?; + // The Reader's matched-writer counts, for `get_subscription_matched_status`. + let matched_counts = Arc::new(MatchedCounts::default()); // reader command channel from Datareader to Reader. // Capacity 0 is a rendezvous, matching the previous mio-extras channel: the @@ -1232,6 +1238,7 @@ impl InnerSubscriber { guid: reader_guid, notification_sender: send, status_sender, + matched_counts: Arc::clone(&matched_counts), topic_name: topic.name(), topic_cache_handle: topic_cache_handle.clone(), like_stateless: reader_like_stateless, @@ -1314,6 +1321,7 @@ impl InnerSubscriber { topic_cache_handle, self.discovery_command.clone(), status_receiver, + matched_counts, reader_command_sender, data_reader_waker, poll_event_source, diff --git a/src/dds/statusevents.rs b/src/dds/statusevents.rs index 40859d8f..bab8823c 100644 --- a/src/dds/statusevents.rs +++ b/src/dds/statusevents.rs @@ -592,6 +592,99 @@ impl CountWithChange { // } } +/// The PUBLICATION_MATCHED status of a DataWriter: how many DataReaders it is +/// matched with, that is, sends its samples to. +/// +/// Returned by `DataWriter::get_publication_matched_status`. Each +/// `count_change()` is the change since the status was last read from the same +/// DataWriter. +/// +/// See the tables of Section 2.2.4.1 in DDS Specification v1.4. Its +/// `last_subscription_handle` is not included: the +/// [`DataWriterStatus::PublicationMatched`] status event names the reader. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PublicationMatchedStatus { + /// How many matches with a DataReader there have been since the DataWriter + /// was created. This never decreases. + pub total: CountWithChange, + /// How many DataReaders the DataWriter is matched with now. + pub current: CountWithChange, +} + +/// The SUBSCRIPTION_MATCHED status of a DataReader: how many DataWriters it is +/// matched with, that is, receives samples from. +/// +/// Returned by `DataReader::get_subscription_matched_status`. Each +/// `count_change()` is the change since the status was last read from the same +/// DataReader. +/// +/// See the tables of Section 2.2.4.1 in DDS Specification v1.4. Its +/// `last_publication_handle` is not included: the +/// [`DataReaderStatus::SubscriptionMatched`] status event names the writer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SubscriptionMatchedStatus { + /// How many matches with a DataWriter there have been since the DataReader + /// was created. This never decreases. + pub total: CountWithChange, + /// How many DataWriters the DataReader is matched with now. + pub current: CountWithChange, +} + +/// How many remote endpoints a DataWriter or DataReader is matched with: the +/// counts of the PUBLICATION_MATCHED and SUBSCRIPTION_MATCHED statuses. +/// +/// The RTPS Writer / Reader stores them whenever its set of matched endpoints +/// changes, and the DataWriter / DataReader reads them through a +/// [`MatchedCountsView`]. Unlike a status event, they are not queued, so they +/// are right also when nobody drains the status channel. +#[derive(Debug, Default)] +pub(crate) struct MatchedCounts { + // (total, current). One lock for the two, so that a read always gets a pair + // that was stored together. + counts: Mutex<(i32, i32)>, +} + +impl MatchedCounts { + /// `total`: how many matches there have been ever. `current`: how many + /// endpoints are matched now. + pub(crate) fn set(&self, total: i32, current: i32) { + *self.counts.lock().unwrap() = (total, current); + } +} + +/// The DataWriter's / DataReader's end of [`MatchedCounts`]. It remembers the +/// counts it returned last, to tell how much they have changed since. +#[derive(Debug)] +pub(crate) struct MatchedCountsView { + counts: Arc, + // (total, current) as `read` returned them last. + seen: Mutex<(i32, i32)>, +} + +impl MatchedCountsView { + pub(crate) fn new(counts: Arc) -> Self { + Self { + counts, + seen: Mutex::new((0, 0)), + } + } + + /// The total and the current count, each with its change since the previous + /// call. + pub(crate) fn read(&self) -> (CountWithChange, CountWithChange) { + // `seen` stays locked while the counts are read, so that concurrent reads + // take turns: the one that gets the newer counts is also the one that + // remembers them last. + let mut seen = self.seen.lock().unwrap(); + let (total, current) = *self.counts.counts.lock().unwrap(); + let (seen_total, seen_current) = std::mem::replace(&mut *seen, (total, current)); + ( + CountWithChange::new(total, total - seen_total), + CountWithChange::new(current, current - seen_current), + ) + } +} + // sample rejection reasons #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SampleRejectedStatusKind { @@ -608,3 +701,124 @@ pub struct QosPolicyCount { count: i32, } */ + +#[cfg(test)] +mod tests { + use super::*; + + // Total and current count, each with its change, as a matched-status getter + // returns them. + fn status(total: (i32, i32), current: (i32, i32)) -> (CountWithChange, CountWithChange) { + ( + CountWithChange::new(total.0, total.1), + CountWithChange::new(current.0, current.1), + ) + } + + // What the DataWriter / DataReader reads is what the RTPS endpoint stored + // last, and the first read counts the change from "nothing matched". + #[test] + fn matched_counts_view_reads_the_counts_stored_last() { + let counts = Arc::new(MatchedCounts::default()); + let view = MatchedCountsView::new(Arc::clone(&counts)); + assert_eq!(view.read(), status((0, 0), (0, 0))); + + counts.set(1, 1); + counts.set(2, 2); + assert_eq!(view.read(), status((2, 2), (2, 2))); + } + + // A change is reported once: a second read with nothing new in between + // shows the same counts and no change. + #[test] + fn matched_counts_view_reports_a_change_once() { + let counts = Arc::new(MatchedCounts::default()); + let view = MatchedCountsView::new(Arc::clone(&counts)); + counts.set(1, 1); + assert_eq!(view.read(), status((1, 1), (1, 1))); + assert_eq!(view.read(), status((1, 0), (1, 0))); + } + + // Changes between two reads add up: a new match and the loss of an old one + // leave the current count where it was, while the total went up. A loss + // alone is a negative change of the current count only. + #[test] + fn matched_counts_view_nets_the_changes_between_reads() { + let counts = Arc::new(MatchedCounts::default()); + let view = MatchedCountsView::new(Arc::clone(&counts)); + counts.set(1, 1); + view.read(); + + counts.set(2, 2); // a second match + counts.set(2, 1); // the first one is lost + assert_eq!(view.read(), status((2, 1), (1, 0))); + + counts.set(2, 0); // the second one is lost too + assert_eq!(view.read(), status((2, 0), (0, -1))); + } + + // How many matches the two tests below store while other threads read. + const STORED_WHILE_READING: i32 = 200_000; + + // The two counts are read as one snapshot. Every pair stored here has two + // equal counts, so a read that mixed two pairs would return different ones. + #[test] + fn matched_counts_are_read_as_one_snapshot() { + let counts = Arc::new(MatchedCounts::default()); + let view = MatchedCountsView::new(Arc::clone(&counts)); + + std::thread::scope(|scope| { + scope.spawn(|| (1..=STORED_WHILE_READING).for_each(|n| counts.set(n, n))); + loop { + let (total, current) = view.read(); + assert_eq!( + total.count(), + current.count(), + "the two counts are from different snapshots" + ); + if total.count() == STORED_WHILE_READING { + break; + } + } + }); + } + + // Several threads may read the status of one endpoint. The total only + // grows, so no read may report that it went down, and the changes that all + // the reads report add up to the matches there were. + #[test] + fn concurrent_reads_report_each_match_once() { + let counts = Arc::new(MatchedCounts::default()); + let view = MatchedCountsView::new(Arc::clone(&counts)); + + let reported: i32 = std::thread::scope(|scope| { + scope.spawn(|| (1..=STORED_WHILE_READING).for_each(|n| counts.set(n, n))); + let readers: Vec<_> = (0..2) + .map(|_| { + scope.spawn(|| { + let mut reported = 0; + loop { + let (total, _current) = view.read(); + assert!( + total.count_change() >= 0, + "the total went down by {}", + -total.count_change() + ); + reported += total.count_change(); + if total.count() == STORED_WHILE_READING { + break reported; + } + } + }) + }) + .collect(); + readers + .into_iter() + .map(|reader| reader.join().expect("a reading thread failed")) + .sum() + }); + + let (total, _current) = view.read(); + assert_eq!(reported + total.count_change(), STORED_WHILE_READING); + } +} diff --git a/src/dds/with_key/datareader.rs b/src/dds/with_key/datareader.rs index 8d736dc9..62b0a12b 100644 --- a/src/dds/with_key/datareader.rs +++ b/src/dds/with_key/datareader.rs @@ -732,6 +732,50 @@ where vec![].into_iter() } + /// Reads the SUBSCRIPTION_MATCHED status of this DataReader: how many + /// DataWriters it is matched with now, and how many matches there have been + /// since it was created. + /// + /// The counts are those of the RTPS Reader itself. They do not come from the + /// status event stream, so they are right also when nothing reads that + /// stream and it has dropped events. Each `count_change()` is the change + /// since the previous call on this DataReader. + /// + /// See DDS Spec 1.4 Section 2.2.4.1 Communication Status. + /// + /// # Examples + /// + /// ``` + /// # use serde::{Serialize, Deserialize}; + /// # use rustdds::*; + /// # use rustdds::with_key::DataReader; + /// # use rustdds::serialization::CDRDeserializerAdapter; + /// # + /// let domain_participant = DomainParticipant::new(0).unwrap(); + /// let qos = QosPolicyBuilder::new().build(); + /// let subscriber = domain_participant.create_subscriber(&qos).unwrap(); + /// + /// #[derive(Serialize, Deserialize, Debug)] + /// struct SomeType { a: i32 } + /// impl Keyed for SomeType { + /// type K = i32; + /// + /// fn key(&self) -> Self::K { + /// self.a + /// } + /// } + /// + /// // WithKey is important + /// let topic = domain_participant.create_topic("some_topic".to_string(), "SomeType".to_string(), &qos, TopicKind::WithKey).unwrap(); + /// let data_reader = subscriber.create_datareader::>(&topic, None).unwrap(); + /// + /// let matched = data_reader.get_subscription_matched_status(); + /// println!("{} writers now, {} ever", matched.current.count(), matched.total.count()); + /// ``` + pub fn get_subscription_matched_status(&self) -> SubscriptionMatchedStatus { + self.simple_data_reader.get_subscription_matched_status() + } + /// An async stream for reading the (bare) data samples. /// The resulting Stream can be used to get another stream of status events. pub fn async_bare_sample_stream(self) -> BareDataReaderStream { @@ -1247,6 +1291,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: topic.name(), topic_cache_handle: topic_cache, like_stateless: false, @@ -1432,6 +1477,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: topic.name(), topic_cache_handle: topic_cache, like_stateless: false, diff --git a/src/dds/with_key/datawriter.rs b/src/dds/with_key/datawriter.rs index 0849b3fe..c5ebbc6f 100644 --- a/src/dds/with_key/datawriter.rs +++ b/src/dds/with_key/datawriter.rs @@ -1,6 +1,7 @@ use std::{ marker::PhantomData, pin::Pin, + sync::Arc, task::{Context, Poll}, time::{Duration, Instant}, }; @@ -212,6 +213,8 @@ pub struct DataWriter = CDRSerializerAdapter< doorbell: Doorbell, discovery_command: WakeSender, status_receiver: StatusChannelReceiver, + /// How many readers the RTPS Writer is matched with. + matched: MatchedCountsView, } impl Drop for DataWriter @@ -253,6 +256,7 @@ where doorbell: Doorbell, discovery_command: WakeSender, status_receiver: StatusChannelReceiver, + matched_counts: Arc, ) -> CreateResult { if let Some(lv) = qos.liveliness { match lv { @@ -275,6 +279,7 @@ where doorbell, discovery_command, status_receiver, + matched: MatchedCountsView::new(matched_counts), }) } @@ -605,12 +610,27 @@ where todo!() } - /// Unimplemented. Do not use. + */ + + /// Reads the PUBLICATION_MATCHED status of this DataWriter: how many + /// DataReaders it is matched with now, and how many matches there have been + /// since it was created. + /// + /// The counts are those of the RTPS Writer itself. They do not come from the + /// status event stream, so they are right also when nothing reads that + /// stream and it has dropped events. Each `count_change()` is the change + /// since the previous call on this DataWriter. + /// + /// The call is cheap enough to make before every write, for example to skip + /// producing a sample that nobody would receive. Skipping is right only for + /// a DataWriter with volatile durability, which keeps nothing for readers + /// that match later, and automatic liveliness, which no write has to assert. + /// + /// See DDS Spec 1.4 Section 2.2.4.1 Communication Status. /// /// # Examples /// - /// ```no_run - // TODO: enable when functional + /// ``` /// # use serde::{Serialize, Deserialize}; /// # use rustdds::*; /// # use rustdds::with_key::DataWriter; @@ -632,20 +652,17 @@ where /// /// // WithKey is important /// let topic = domain_participant.create_topic("some_topic".to_string(), "SomeType".to_string(), &qos, TopicKind::WithKey).unwrap(); - /// let data_writer = publisher.create_datawriter::>(topic, None).unwrap(); - /// - /// // Liveliness lost status has changed + /// let data_writer = publisher.create_datawriter::>(&topic, None).unwrap(); /// - /// if let Ok(pms) = data_writer.get_publication_matched_status() { - /// // do something + /// if data_writer.get_publication_matched_status().current.count() > 0 { + /// data_writer.write(SomeType { a: 1 }, None).unwrap(); /// } /// ``` - pub fn get_publication_matched_status(&self) -> Result { - todo!() + pub fn get_publication_matched_status(&self) -> PublicationMatchedStatus { + let (total, current) = self.matched.read(); + PublicationMatchedStatus { total, current } } - */ - /// Topic assigned to this DataWriter /// /// # Examples diff --git a/src/dds/with_key/simpledatareader.rs b/src/dds/with_key/simpledatareader.rs index 09237b3f..2e0877c3 100644 --- a/src/dds/with_key/simpledatareader.rs +++ b/src/dds/with_key/simpledatareader.rs @@ -105,6 +105,8 @@ pub struct SimpleDataReader = CDRDeserializ discovery_command: WakeSender, status_receiver: StatusChannelReceiver, + /// How many writers the RTPS Reader is matched with. + matched: MatchedCountsView, #[allow(dead_code)] // TODO: This is currently unused, because we do not implement // resetting deadline missed status. Remove attribute when it is supported. @@ -152,6 +154,7 @@ where topic_cache: Arc>, discovery_command: WakeSender, status_receiver: StatusChannelReceiver, + matched_counts: Arc, reader_command: BoundSender, data_reader_waker: Arc>>, event_source: PollEventSource, @@ -190,6 +193,7 @@ where deserializer_type: PhantomData, discovery_command, status_receiver, + matched: MatchedCountsView::new(matched_counts), reader_command, data_reader_waker, event_source, @@ -409,6 +413,21 @@ where &self.my_topic } + /// Reads the SUBSCRIPTION_MATCHED status of this DataReader: how many + /// DataWriters it is matched with now, and how many matches there have been + /// since it was created. + /// + /// The counts are those of the RTPS Reader itself. They do not come from the + /// status event stream, so they are right also when nothing reads that + /// stream and it has dropped events. Each `count_change()` is the change + /// since the previous call on this DataReader. + /// + /// See DDS Spec 1.4 Section 2.2.4.1 Communication Status. + pub fn get_subscription_matched_status(&self) -> SubscriptionMatchedStatus { + let (total, current) = self.matched.read(); + SubscriptionMatchedStatus { total, current } + } + pub fn as_async_stream(&self) -> SimpleDataReaderStream<'_, D, S, DA> where DA: DefaultDecoder, diff --git a/src/discovery/discovery_db.rs b/src/discovery/discovery_db.rs index 7069169c..8a49aea7 100644 --- a/src/discovery/discovery_db.rs +++ b/src/discovery/discovery_db.rs @@ -1105,6 +1105,7 @@ mod tests { guid: GUID::dummy_test_guid(EntityKind::READER_NO_KEY_USER_DEFINED), notification_sender: notification_sender1, status_sender: status_sender1, + matched_counts: Default::default(), topic_name: topic.name(), topic_cache_handle: topic_cache.clone(), like_stateless: false, @@ -1154,6 +1155,7 @@ mod tests { guid: guid2, notification_sender: notification_sender2, status_sender: status_sender2, + matched_counts: Default::default(), topic_name: topic.name(), topic_cache_handle: topic_cache, like_stateless: false, diff --git a/src/lib.rs b/src/lib.rs index bf7386cc..c83a1222 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -218,7 +218,8 @@ pub use dds::{ sampleinfo::{InstanceState, NotAliveGenerationCounts, SampleInfo, SampleState, ViewState}, statusevents::{ DataReaderStatus, DataWriterStatus, DomainParticipantStatusEvent, EndpointDescription, - LostReason, ParticipantDescription, StatusEvented, + LostReason, ParticipantDescription, PublicationMatchedStatus, StatusEvented, + SubscriptionMatchedStatus, }, topic::{Topic, TopicDescription, TopicKind}, typedesc::TypeDesc, diff --git a/src/rtps/dp_event_loop.rs b/src/rtps/dp_event_loop.rs index 715a10a3..eab2dbe2 100644 --- a/src/rtps/dp_event_loop.rs +++ b/src/rtps/dp_event_loop.rs @@ -1401,6 +1401,7 @@ mod tests { guid: new_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_cache_handle: topic_cache.clone(), topic_name: "test".to_string(), like_stateless: false, diff --git a/src/rtps/message_receiver.rs b/src/rtps/message_receiver.rs index 67386bd7..477f8283 100644 --- a/src/rtps/message_receiver.rs +++ b/src/rtps/message_receiver.rs @@ -1230,6 +1230,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: "test".to_string(), topic_cache_handle: topic_cache_handle.clone(), like_stateless: false, diff --git a/src/rtps/reader.rs b/src/rtps/reader.rs index fb0b8022..4824db3b 100644 --- a/src/rtps/reader.rs +++ b/src/rtps/reader.rs @@ -19,7 +19,8 @@ use crate::{ ddsdata::DDSData, qos::{policy, HasQoSPolicy, QosPolicies}, statusevents::{ - CountWithChange, DataReaderStatus, DomainParticipantStatusEvent, StatusChannelSender, + CountWithChange, DataReaderStatus, DomainParticipantStatusEvent, MatchedCounts, + StatusChannelSender, }, with_key::{ datawriter::{WriteOptions, WriteOptionsBuilder}, @@ -74,6 +75,9 @@ pub(crate) struct ReaderIngredients { pub guid: GUID, pub notification_sender: crate::mio_source::NotificationSender, pub status_sender: StatusChannelSender, + /// Where the Reader stores how many writers it is matched with, for the + /// `DataReader` to read. + pub(crate) matched_counts: Arc, pub topic_name: String, pub(crate) topic_cache_handle: Arc>, /* A handle to the topic cache in DDS * cache */ @@ -104,6 +108,8 @@ pub(crate) struct Reader { // Should the instant be sent? notification_sender: crate::mio_source::NotificationSender, status_sender: StatusChannelSender, + // The matched-writer counts, shared with the DataReader. + matched_counts: Arc, udp_sender: Rc, // By default, this reader is a StatefulReader (see RTPS spec section 8.4.12) @@ -183,6 +189,7 @@ impl Reader { Self { notification_sender: i.notification_sender, status_sender: i.status_sender, + matched_counts: i.matched_counts, udp_sender, like_stateless: i.like_stateless, reliability: i @@ -401,6 +408,7 @@ impl Reader { let count_change = self.matched_writer_update(proxy); if count_change > 0 { self.writer_match_count_total += count_change; + self.store_matched_counts(); self.send_status_change(DataReaderStatus::SubscriptionMatched { total: CountWithChange::new(self.writer_match_count_total, count_change), current: CountWithChange::new(self.matched_writers.len() as i32, count_change), @@ -478,6 +486,7 @@ impl Reader { .unregister_remote_writer(&self.my_guid, &writer_guid) .unwrap_or_else(|e| error!("{e}")); } + self.store_matched_counts(); self.send_status_change(DataReaderStatus::SubscriptionMatched { total: CountWithChange::new(self.writer_match_count_total, 0), current: CountWithChange::new(self.matched_writers.len() as i32, -1), @@ -486,6 +495,16 @@ impl Reader { } } + // Stores the matched-writer counts for the DataReader. Called with every + // SubscriptionMatched status event: the event is dropped when the status + // channel is full, the counts are not. + fn store_matched_counts(&self) { + self.matched_counts.set( + self.writer_match_count_total, + self.matched_writers.len() as i32, + ); + } + // Entire remote participant was lost. // Remove all remote writers belonging to it. pub fn participant_lost(&mut self, guid_prefix: GuidPrefix) { @@ -1500,6 +1519,158 @@ mod tests { }; use super::*; + // A Reader that asks for `qos`, and the DataReader's end of its + // matched-writer counts. + struct MatchFixture { + reader: Reader, + matched: crate::dds::statusevents::MatchedCountsView, + // The other ends of the Reader's channels, kept open. + _channels: Vec>, + } + + impl MatchFixture { + fn new(qos: QosPolicies) -> Self { + let dds_cache = Arc::new(RwLock::new(DDSCache::new())); + let topic_name = "matched_counts_test"; + let topic_cache_handle = dds_cache.write().unwrap().add_new_topic( + topic_name.to_string(), + TypeDesc::new("test_type".to_string()), + &qos, + ); + let (notification_sender, notification_receiver) = + crate::mio_source::notification_channel(100); + let (notification_event_source, notification_event_sender) = + mio_source::make_poll_channel().unwrap(); + let (status_sender, status_receiver) = sync_status_channel::(4).unwrap(); + let (participant_status_sender, participant_status_receiver) = + sync_status_channel(16).unwrap(); + let (reader_command_sender, reader_command_receiver) = + wake_channel::(10, &LoopWaker::new()); + let matched_counts = Arc::new(MatchedCounts::default()); + + let reader = Reader::new( + ReaderIngredients { + guid: GUID::dummy_test_guid(EntityKind::READER_NO_KEY_USER_DEFINED), + notification_sender, + status_sender, + matched_counts: Arc::clone(&matched_counts), + topic_name: topic_name.to_string(), + topic_cache_handle, + like_stateless: false, + qos_policy: qos, + data_reader_command_receiver: reader_command_receiver, + data_reader_waker: Arc::new(Mutex::new(None)), + poll_event_sender: notification_event_sender, + security_plugins: None, + discovery_notify: None, + }, + Rc::new(UDPSender::new(0).unwrap()), + new_shared_timer(), + participant_status_sender, + ); + Self { + reader, + matched: crate::dds::statusevents::MatchedCountsView::new(matched_counts), + _channels: vec![ + Box::new(notification_receiver), + Box::new(notification_event_source), + Box::new(status_receiver), + Box::new(participant_status_receiver), + Box::new(reader_command_sender), + ], + } + } + + // The total and the current matched-writer count, as the DataReader reads + // them. + fn matched_counts(&self) -> (i32, i32) { + let (total, current) = self.matched.read(); + (total.count(), current.count()) + } + + // Tells the Reader about a writer of the participant `participant` that + // offers `qos`. + fn discover_writer(&mut self, participant: u8, qos: &QosPolicies) -> GUID { + let guid = GUID::new( + GuidPrefix::new(&[participant; 12]), + EntityId::new([0, 0, 1], EntityKind::WRITER_NO_KEY_USER_DEFINED), + ); + self + .reader + .matched_writer_add(guid, EntityId::UNKNOWN, vec![], vec![], qos); + guid + } + } + + // A writer counts as matched once, however often it is announced again. + #[test] + fn reader_counts_each_matched_writer_once() { + let qos = QosPolicies::qos_none(); + let mut f = MatchFixture::new(qos.clone()); + assert_eq!(f.matched_counts(), (0, 0)); + + let writer_2 = f.discover_writer(2, &qos); + assert_eq!(f.matched_counts(), (1, 1)); + // The same writer again, as after a QoS or locator update, is not a new + // match. + assert_eq!(f.discover_writer(2, &qos), writer_2); + assert_eq!(f.matched_counts(), (1, 1)); + + // A writer of another participant is one. + f.discover_writer(3, &qos); + assert_eq!(f.matched_counts(), (2, 2)); + } + + // A writer that does not offer what the Reader asks for is not matched, so + // it is not counted. + #[test] + fn reader_does_not_count_a_writer_with_incompatible_qos() { + let asks_for_history = QosPolicyBuilder::new() + .durability(policy::Durability::TransientLocal) + .build(); + let mut f = MatchFixture::new(asks_for_history.clone()); + f.discover_writer(2, &asks_for_history); + // This writer offers the default, Volatile durability. + let writer = f.discover_writer(3, &QosPolicies::qos_none()); + assert!(!f.reader.matched_writers.contains_key(&writer)); + assert_eq!(f.matched_counts(), (1, 1)); + } + + // Losing a writer lowers the current count. The total counts the matches + // there have ever been, so it stays. + #[test] + fn reader_lowers_the_current_count_when_a_writer_is_lost() { + let qos = QosPolicies::qos_none(); + let mut f = MatchFixture::new(qos.clone()); + let writer_2 = f.discover_writer(2, &qos); + let writer_3 = f.discover_writer(3, &qos); + + // A writer that was never matched changes nothing. + f.reader + .remove_writer_proxy(GUID::new(GuidPrefix::new(&[4; 12]), writer_3.entity_id)); + assert_eq!(f.matched_counts(), (2, 2)); + + f.reader.remove_writer_proxy(writer_2); + assert_eq!(f.matched_counts(), (2, 1)); + // A lost participant takes its writers with it. + f.reader.participant_lost(writer_3.prefix); + assert_eq!(f.matched_counts(), (2, 0)); + } + + // The counts do not go through the status channel, which keeps a few events + // and drops the rest when nobody reads them. + #[test] + fn reader_counts_more_writers_than_the_status_channel_holds() { + let qos = QosPolicies::qos_none(); + let mut f = MatchFixture::new(qos.clone()); + // The fixture's status channel has room for 4 events, and nothing reads + // it. + for participant in 2..=11 { + f.discover_writer(participant, &qos); + } + assert_eq!(f.matched_counts(), (10, 10)); + } + #[test] fn reader_sends_notification_when_receiving_data() { // 1. Create a reader @@ -1538,6 +1709,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: topic_name.to_string(), topic_cache_handle, like_stateless: false, @@ -1625,6 +1797,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: topic_name.to_string(), topic_cache_handle: topic_cache_handle.clone(), like_stateless: false, @@ -1733,6 +1906,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: topic_name.to_string(), topic_cache_handle, like_stateless: false, @@ -1844,6 +2018,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: topic_name.to_string(), topic_cache_handle, like_stateless: false, @@ -1984,6 +2159,7 @@ mod tests { guid: reader_guid, notification_sender, status_sender, + matched_counts: Default::default(), topic_name: topic_name.to_string(), topic_cache_handle, like_stateless, diff --git a/src/rtps/writer.rs b/src/rtps/writer.rs index 181aba36..0538e374 100644 --- a/src/rtps/writer.rs +++ b/src/rtps/writer.rs @@ -4,7 +4,7 @@ use std::{ collections::{BTreeMap, BTreeSet}, ops::Bound::Included, rc::Rc, - sync::{atomic, mpsc::TrySendError}, + sync::{atomic, mpsc::TrySendError, Arc}, }; #[allow(unused_imports)] @@ -20,7 +20,8 @@ use crate::{ HasQoSPolicy, QosPolicies, }, statusevents::{ - CountWithChange, DataWriterStatus, DomainParticipantStatusEvent, StatusChannelSender, + CountWithChange, DataWriterStatus, DomainParticipantStatusEvent, MatchedCounts, + StatusChannelSender, }, }, messages::submessages::submessages::AckSubmessage, @@ -135,6 +136,9 @@ pub(crate) struct WriterIngredients { pub(crate) like_stateless: bool, // Usually false (see like_stateless attribute of Writer) pub qos_policies: QosPolicies, pub status_sender: StatusChannelSender, + /// Where the Writer stores how many readers it is matched with, for the + /// `DataWriter` to read. + pub(crate) matched_counts: Arc, pub(crate) security_plugins: Option, } @@ -267,6 +271,8 @@ pub(crate) struct Writer { // Used for sending status info about messages sent status_sender: StatusChannelSender, + // The matched-reader counts, shared with the DataWriter. + matched_counts: Arc, // offered_deadline_status: OfferedDeadlineMissedStatus, participant_status_sender: StatusChannelSender, @@ -367,6 +373,7 @@ impl Writer { like_stateless: i.like_stateless, qos_policies: i.qos_policies, status_sender: i.status_sender, + matched_counts: i.matched_counts, participant_status_sender, security_plugins: i.security_plugins, @@ -2015,6 +2022,7 @@ impl Writer { self.refresh_acked_frontier(); if new_reader { self.matched_readers_count_total += 1; + self.store_matched_counts(); self.send_status(DataWriterStatus::PublicationMatched { // total: How many matches have been detected ever? total: CountWithChange::new(self.matched_readers_count_total, 1), @@ -2208,6 +2216,7 @@ impl Writer { // Removing a reader may relax (raise) the writer-wide minimum budget. self.recompute_min_datagram_payload(); // self.matched_readers_count_total -= 1; // this never decreases + self.store_matched_counts(); self.send_status(DataWriterStatus::PublicationMatched { total: CountWithChange::new(self.matched_readers_count_total, 0), current: CountWithChange::new(self.readers.len() as i32, -1), @@ -2232,6 +2241,15 @@ impl Writer { } } + // Stores the matched-reader counts for the DataWriter. Called with every + // PublicationMatched status event: the event is dropped when the status + // channel is full, the counts are not. + fn store_matched_counts(&self) { + self + .matched_counts + .set(self.matched_readers_count_total, self.readers.len() as i32); + } + fn lookup_reader_proxy_mut(&mut self, guid: GUID) -> Option<&mut RtpsReaderProxy> { self.readers.get_mut(&guid) } @@ -2775,7 +2793,7 @@ mod tests { dds::{ ddsdata::DDSData, qos::{policy::Durability, QosPolicyBuilder}, - statusevents::{sync_status_channel, StatusChannelReceiver}, + statusevents::{sync_status_channel, MatchedCountsView, StatusChannelReceiver}, with_key::datawriter::WriteOptions, }, discovery::discovery::Discovery, @@ -2794,6 +2812,8 @@ mod tests { timer: SharedTimer, _status: StatusChannelReceiver, _participant_status: StatusChannelReceiver, + // The DataWriter's end of the Writer's matched-reader counts. + matched: MatchedCountsView, } impl Fixture { @@ -2833,6 +2853,7 @@ mod tests { let (status_sender, status) = sync_status_channel(4).unwrap(); let (participant_status_sender, participant_status) = sync_status_channel(16).unwrap(); let timer = new_shared_timer(); + let matched_counts = Arc::new(MatchedCounts::default()); let mut writer = Writer::new( WriterIngredients { guid, @@ -2841,6 +2862,7 @@ mod tests { like_stateless: false, qos_policies: writer_qos, status_sender, + matched_counts: Arc::clone(&matched_counts), security_plugins: None, }, Rc::new(UDPSender::new(0).unwrap()), @@ -2865,6 +2887,7 @@ mod tests { timer, _status: status, _participant_status: participant_status, + matched: MatchedCountsView::new(matched_counts), } } @@ -2905,6 +2928,26 @@ mod tests { &self.writer.readers[&self.reader_guid] } + // The total and the current matched-reader count, as the DataWriter + // reads them. + fn matched_counts(&self) -> (i32, i32) { + let (total, current) = self.matched.read(); + (total.count(), current.count()) + } + + // Tells the Writer about a reader `entity` of the participant + // `participant` that asks for `qos`. + fn discover_reader(&mut self, participant: u8, qos: &QosPolicies) -> GUID { + let guid = GUID::new( + GuidPrefix::new(&[participant; 12]), + self.reader_guid.entity_id, + ); + self + .writer + .update_reader_proxy(&RtpsReaderProxy::new(guid, qos.clone(), false), qos); + guid + } + fn unsent(&self) -> usize { self.reader_proxy().unsent_changes_count() } @@ -3150,5 +3193,75 @@ mod tests { assert_eq!(f.writer.last_sent, SequenceNumber::new(5)); assert!(!f.writer.process_pending()); } + + // A reader counts as matched once, however often it is announced again. + #[test] + fn writer_counts_each_matched_reader_once() { + // The fixture's Writer is matched with a reader of participant 2. + let mut f = Fixture::user(3, 8, None); + let qos = f.writer.qos_policies.clone(); + assert_eq!(f.matched_counts(), (1, 1)); + + // The same reader again, as after a QoS or locator update, + assert_eq!(f.discover_reader(2, &qos), f.reader_guid); + // and the repair path, which takes the proxy out of the map and puts it + // back, are not new matches. + f.ack_nack(1..=3, 1); + assert_eq!(f.matched_counts(), (1, 1)); + + // A reader of another participant is one. + f.discover_reader(3, &qos); + assert_eq!(f.matched_counts(), (2, 2)); + } + + // A reader the Writer cannot serve is not matched, so it is not counted. + #[test] + fn writer_does_not_count_a_reader_with_incompatible_qos() { + // The fixture's Writer is matched with a reader of participant 2. + let mut f = Fixture::user(0, 8, None); + // The Writer offers TransientLocal durability. This reader asks for more. + let asks_too_much = QosPolicyBuilder::new() + .durability(Durability::Persistent) + .build(); + let reader = f.discover_reader(3, &asks_too_much); + assert!(!f.writer.readers.contains_key(&reader)); + assert_eq!(f.matched_counts(), (1, 1)); + } + + // Losing a reader lowers the current count. The total counts the matches + // there have ever been, so it stays. + #[test] + fn writer_lowers_the_current_count_when_a_reader_is_lost() { + // The fixture's Writer is matched with a reader of participant 2. + let mut f = Fixture::user(0, 8, None); + let qos = f.writer.qos_policies.clone(); + let reader_3 = f.discover_reader(3, &qos); + + // A reader that was never matched changes nothing. + f.writer + .reader_lost(GUID::new(GuidPrefix::new(&[4; 12]), reader_3.entity_id)); + assert_eq!(f.matched_counts(), (2, 2)); + + f.writer.reader_lost(f.reader_guid); + assert_eq!(f.matched_counts(), (2, 1)); + // A lost participant takes its readers with it. + f.writer.participant_lost(reader_3.prefix); + assert_eq!(f.matched_counts(), (2, 0)); + } + + // The counts do not go through the status channel, which keeps a few + // events and drops the rest when nobody reads them. + #[test] + fn writer_counts_more_readers_than_the_status_channel_holds() { + // The fixture's Writer is matched with a reader of participant 2. + let mut f = Fixture::user(0, 8, None); + let qos = f.writer.qos_policies.clone(); + // The fixture's status channel has room for 4 events, and nothing reads + // it. + for participant in 3..=11 { + f.discover_reader(participant, &qos); + } + assert_eq!(f.matched_counts(), (10, 10)); + } } } diff --git a/tests/matched_status_test.rs b/tests/matched_status_test.rs new file mode 100644 index 00000000..6cbcf18a --- /dev/null +++ b/tests/matched_status_test.rs @@ -0,0 +1,116 @@ +//! `DataWriter::get_publication_matched_status` and +//! `DataReader::get_subscription_matched_status` between two participants. +use std::time::{Duration, Instant}; + +use rustdds::{policy, DomainParticipant, QosPolicyBuilder, TopicKind}; +use serde::{Deserialize, Serialize}; + +mod common; + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +struct Ping { + seq: u32, +} + +const TIMEOUT: Duration = Duration::from_secs(10); + +/// Calls `poll` until it returns a value, for at most [`TIMEOUT`]. +fn wait_for(mut poll: impl FnMut() -> Option) -> Option { + let deadline = Instant::now() + TIMEOUT; + loop { + if let Some(value) = poll() { + return Some(value); + } + if Instant::now() >= deadline { + return None; + } + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn matched_status_follows_the_remote_endpoint() { + let domain_id = common::test_domain_id(49); + let qos = QosPolicyBuilder::new() + .reliability(policy::Reliability::Reliable { + max_blocking_time: rustdds::Duration::from_secs(1), + }) + .build(); + let topic_name = "matched_status_test_topic".to_string(); + + // Participant A has the writer. + let participant_a = DomainParticipant::new(domain_id).unwrap(); + let topic_a = participant_a + .create_topic( + topic_name.clone(), + "Ping".to_string(), + &qos, + TopicKind::NoKey, + ) + .unwrap(); + let publisher = participant_a.create_publisher(&qos).unwrap(); + let writer = publisher + .create_datawriter_no_key_cdr::(&topic_a, None) + .unwrap(); + + let unmatched = writer.get_publication_matched_status(); + assert_eq!( + (unmatched.total.count(), unmatched.current.count()), + (0, 0), + "matched before there is a reader" + ); + + // Participant B has the reader. + let participant_b = DomainParticipant::new(domain_id).unwrap(); + let topic_b = participant_b + .create_topic(topic_name, "Ping".to_string(), &qos, TopicKind::NoKey) + .unwrap(); + let subscriber = participant_b.create_subscriber(&qos).unwrap(); + let reader = subscriber + .create_datareader_no_key_cdr::(&topic_b, None) + .unwrap(); + + // Each side reports the other one, with the change since its last read. + // Nothing here reads the status events. + let on_writer = wait_for(|| { + let status = writer.get_publication_matched_status(); + (status.current.count() > 0).then_some(status) + }) + .expect("the writer never reported a matched reader"); + assert_eq!( + (on_writer.total.count(), on_writer.total.count_change()), + (1, 1) + ); + assert_eq!( + (on_writer.current.count(), on_writer.current.count_change()), + (1, 1) + ); + + let on_reader = wait_for(|| { + let status = reader.get_subscription_matched_status(); + (status.current.count() > 0).then_some(status) + }) + .expect("the reader never reported a matched writer"); + assert_eq!( + (on_reader.total.count(), on_reader.total.count_change()), + (1, 1) + ); + assert_eq!( + (on_reader.current.count(), on_reader.current.count_change()), + (1, 1) + ); + + // The reader goes away: the writer is matched with nobody, and has matched + // one reader ever. + drop(reader); + let after_loss = wait_for(|| { + let status = writer.get_publication_matched_status(); + (status.current.count() == 0).then_some(status) + }) + .expect("the writer never reported the reader as lost"); + assert_eq!(after_loss.current.count_change(), -1); + assert_eq!( + (after_loss.total.count(), after_loss.total.count_change()), + (1, 0) + ); +}