Skip to main content

rustorb_dds/
topic.rs

1//! `Topic`.
2
3use std::sync::{Arc, Mutex};
4
5use rustorb_rtps::Guid;
6use rustorb_rtps::sedp::ContentFilterProperty;
7use rustorb_xtypes::dynamic::ContentFilter;
8use rustorb_xtypes::dynamic::filter::DDSSQL;
9
10use crate::error::Result;
11use crate::listener::TopicListener;
12use crate::participant::Shared;
13use crate::status::{InconsistentTopicStatus, StatusMask};
14use crate::typed::SampleType;
15
16/// A DDS topic (DDS 1.4, 2.2.2.3.2): a name and the type of its samples,
17/// which are of Rust type `T`: a [`TopicType`](crate::TopicType) the
18/// program was built with, or [`DynamicData`](crate::DynamicData) of a
19/// type known at run time
20/// ([`DomainParticipant::create_dynamic_topic`](crate::DomainParticipant::create_dynamic_topic)).
21/// Writers and readers match by topic name and type name, or by type
22/// assignability for registered types.
23pub struct Topic<T> {
24    name: String,
25    pub(crate) shared: Arc<Shared>,
26    pub(crate) samples: Arc<dyn SampleType<T>>,
27}
28
29impl<T> Topic<T> {
30    pub(crate) fn new(name: &str, shared: Arc<Shared>, samples: Arc<dyn SampleType<T>>) -> Self {
31        Topic {
32            name: name.to_owned(),
33            shared,
34            samples,
35        }
36    }
37
38    /// The topic name.
39    pub fn name(&self) -> &str {
40        &self.name
41    }
42
43    /// The INCONSISTENT_TOPIC status (DDS 1.4, 2.2.4.1): the writers and
44    /// readers of this topic found in other participants whose types are
45    /// not consistent with those of the local ones. Reading it resets
46    /// `total_count_change`.
47    pub fn inconsistent_topic_status(&self) -> InconsistentTopicStatus {
48        let mut g = self.shared.lock_any();
49        g.inconsistent_topics
50            .get_mut(&self.name)
51            .map(|s| s.take())
52            .unwrap_or_default()
53    }
54
55    /// Sets the listener of the topic (`set_listener`), replacing any
56    /// earlier one: it is called for INCONSISTENT_TOPIC when `mask` has
57    /// it. The topics of one name in a participant share their listener.
58    pub fn set_listener(&self, listener: impl TopicListener + 'static, mask: StatusMask) {
59        self.shared
60            .lock_any()
61            .topic_listeners
62            .insert(self.name.clone(), (Arc::new(listener), mask));
63    }
64
65    /// Removes the listener of the topic.
66    pub fn clear_listener(&self) {
67        self.shared.lock_any().topic_listeners.remove(&self.name);
68    }
69
70    /// The type name: `T::TYPE_NAME` for a [`TopicType`](crate::TopicType),
71    /// the name of the DynamicType otherwise.
72    pub fn type_name(&self) -> &str {
73        self.samples.type_name()
74    }
75}
76
77impl<T> Clone for Topic<T> {
78    fn clone(&self) -> Self {
79        Topic {
80            name: self.name.clone(),
81            shared: self.shared.clone(),
82            samples: self.samples.clone(),
83        }
84    }
85}
86
87impl<T> std::fmt::Debug for Topic<T> {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_struct("Topic")
90            .field("name", &self.name)
91            .field("type_name", &self.type_name())
92            .finish()
93    }
94}
95
96/// A topic whose readers get only the samples of its related topic that
97/// pass a filter (DDS 1.4, 2.2.2.3.3): a filter expression (DDS 1.4,
98/// Annex B, see [`ContentFilter`]) with parameters, which can change.
99///
100/// Made by
101/// [`DomainParticipant::create_contentfilteredtopic`](crate::DomainParticipant::create_contentfilteredtopic).
102/// Its readers announce the filter (DDSI-RTPS 2.5, 8.7.3.1), so that
103/// remote writers that can filter do, and filter the samples they get
104/// themselves.
105pub struct ContentFilteredTopic<T> {
106    name: String,
107    related: Topic<T>,
108    state: Arc<Mutex<FilterState>>,
109}
110
111/// What the readers of a content filtered topic share.
112struct FilterState {
113    filter: ContentFilter,
114    readers: Vec<Guid>,
115}
116
117impl<T> ContentFilteredTopic<T> {
118    pub(crate) fn new(name: &str, related: &Topic<T>, filter: ContentFilter) -> Self {
119        ContentFilteredTopic {
120            name: name.to_owned(),
121            related: related.clone(),
122            state: Arc::new(Mutex::new(FilterState {
123                filter,
124                readers: Vec::new(),
125            })),
126        }
127    }
128
129    fn state(&self) -> std::sync::MutexGuard<'_, FilterState> {
130        self.state.lock().unwrap_or_else(|e| e.into_inner())
131    }
132
133    /// The name of the content filtered topic.
134    pub fn name(&self) -> &str {
135        &self.name
136    }
137
138    /// The type name, that of the related topic.
139    pub fn type_name(&self) -> &str {
140        self.related.type_name()
141    }
142
143    /// The related topic (`get_related_topic`).
144    pub fn related_topic(&self) -> &Topic<T> {
145        &self.related
146    }
147
148    /// The filter expression.
149    pub fn filter_expression(&self) -> String {
150        self.state().filter.expression().to_owned()
151    }
152
153    /// The expression parameters: those of the last successful
154    /// [`set_expression_parameters`](Self::set_expression_parameters),
155    /// or those it was made with.
156    pub fn expression_parameters(&self) -> Vec<String> {
157        self.state().filter.parameters().to_vec()
158    }
159
160    /// Changes the expression parameters: the readers filter with them
161    /// from now on, and announce them. Fails with
162    /// [`Error::Dynamic`](crate::Error::Dynamic) when there are
163    /// fewer than the expression uses.
164    pub fn set_expression_parameters(&self, parameters: &[String]) -> Result<()> {
165        let mut st = self.state();
166        st.filter.set_parameters(parameters)?;
167        st.readers
168            .retain(|g| self.related.shared.lock_any().readers.contains_key(g));
169        self.related
170            .shared
171            .set_filter_parameters(&st.readers, parameters)
172    }
173
174    /// The filter and the property that announces it, for a new reader.
175    pub(crate) fn reader_filter(&self) -> (ContentFilter, ContentFilterProperty) {
176        let st = self.state();
177        let property = ContentFilterProperty {
178            content_filtered_topic_name: self.name.clone(),
179            related_topic_name: self.related.name().to_owned(),
180            filter_class_name: DDSSQL.to_owned(),
181            filter_expression: st.filter.expression().to_owned(),
182            expression_parameters: st.filter.parameters().to_vec(),
183        };
184        (st.filter.clone(), property)
185    }
186
187    /// Notes a reader of the topic, whose parameters change with it.
188    pub(crate) fn add_reader(&self, guid: Guid) {
189        self.state().readers.push(guid);
190    }
191}
192
193impl<T> std::fmt::Debug for ContentFilteredTopic<T> {
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        f.debug_struct("ContentFilteredTopic")
196            .field("name", &self.name)
197            .field("related_topic", &self.related.name())
198            .field("filter_expression", &self.filter_expression())
199            .field("expression_parameters", &self.expression_parameters())
200            .finish()
201    }
202}
203
204/// What readers can be created for (`TopicDescription`, DDS 1.4,
205/// 2.2.2.3.1): a [`Topic`] or a [`ContentFilteredTopic`].
206pub trait TopicDescription<T>: sealed::Description<T> {
207    /// The name.
208    fn get_name(&self) -> &str;
209    /// The type name.
210    fn get_type_name(&self) -> &str;
211}
212
213pub(crate) mod sealed {
214    use super::*;
215
216    /// The topic and the filter of a reader.
217    pub trait Description<T> {
218        #[doc(hidden)]
219        fn topic(&self) -> &Topic<T>;
220        #[doc(hidden)]
221        fn content_filter(&self) -> Option<&ContentFilteredTopic<T>> {
222            None
223        }
224    }
225}
226
227impl<T> sealed::Description<T> for Topic<T> {
228    fn topic(&self) -> &Topic<T> {
229        self
230    }
231}
232
233impl<T> TopicDescription<T> for Topic<T> {
234    fn get_name(&self) -> &str {
235        self.name()
236    }
237    fn get_type_name(&self) -> &str {
238        self.type_name()
239    }
240}
241
242impl<T> sealed::Description<T> for ContentFilteredTopic<T> {
243    fn topic(&self) -> &Topic<T> {
244        &self.related
245    }
246    fn content_filter(&self) -> Option<&ContentFilteredTopic<T>> {
247        Some(self)
248    }
249}
250
251impl<T> TopicDescription<T> for ContentFilteredTopic<T> {
252    fn get_name(&self) -> &str {
253        self.name()
254    }
255    fn get_type_name(&self) -> &str {
256        self.type_name()
257    }
258}