Skip to main content

rustorb_dds/
condition.rs

1//! Conditions and WaitSets (DDS 1.4, 2.2.2.1.6 to 2.2.2.1.9 and
2//! 2.2.4.4): a thread waits on a WaitSet until one of the conditions
3//! attached to it is true, without an async runtime.
4
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Condvar, Mutex, Weak};
7use std::time::{Duration, Instant};
8
9use rustorb_rtps::Guid;
10
11use crate::error::{Error, Result};
12use crate::instance::StateFilter;
13use crate::participant::Shared;
14use crate::status::StatusMask;
15
16/// What a WaitSet sleeps on: woken when one of its conditions may have
17/// changed.
18#[derive(Debug, Default)]
19pub(crate) struct Waker {
20    /// Counts the wakes, so that a wake between the check of the
21    /// conditions and the wait is not missed.
22    generation: Mutex<u64>,
23    cv: Condvar,
24}
25
26impl Waker {
27    pub(crate) fn wake(&self) {
28        *self.generation.lock().unwrap_or_else(|e| e.into_inner()) += 1;
29        self.cv.notify_all();
30    }
31
32    fn generation(&self) -> u64 {
33        *self.generation.lock().unwrap_or_else(|e| e.into_inner())
34    }
35
36    /// Waits until a wake after `generation`, or `deadline`.
37    fn wait(&self, generation: u64, deadline: Option<Instant>) {
38        let mut g = self.generation.lock().unwrap_or_else(|e| e.into_inner());
39        while *g == generation {
40            match deadline {
41                None => g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner()),
42                Some(d) => {
43                    let now = Instant::now();
44                    if now >= d {
45                        return;
46                    }
47                    g = match self.cv.wait_timeout(g, d - now) {
48                        Ok((g, _)) => g,
49                        Err(e) => e.into_inner().0,
50                    };
51                }
52            }
53        }
54    }
55}
56
57/// Adds `waker` to `list` unless it is there, dropping the WaitSets gone.
58fn register(list: &Mutex<Vec<Weak<Waker>>>, waker: &Arc<Waker>) {
59    let mut l = list.lock().unwrap_or_else(|e| e.into_inner());
60    l.retain(|w| w.strong_count() > 0);
61    if !l.iter().any(|w| w.as_ptr() == Arc::as_ptr(waker)) {
62        l.push(Arc::downgrade(waker));
63    }
64}
65
66#[derive(Debug, Default)]
67struct GuardState {
68    trigger: Mutex<bool>,
69    waitsets: Mutex<Vec<Weak<Waker>>>,
70}
71
72/// A condition whose trigger value the application sets (DDS 1.4,
73/// 2.2.2.1.8): to wake a thread waiting on a WaitSet.
74///
75/// Clones are the same condition.
76#[derive(Clone, Debug, Default)]
77pub struct GuardCondition {
78    state: Arc<GuardState>,
79}
80
81impl GuardCondition {
82    /// A new condition, not triggered.
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    /// Sets the trigger value (`set_trigger_value`), waking the WaitSets
88    /// it is attached to.
89    pub fn set_trigger_value(&self, value: bool) {
90        *self.state.trigger.lock().unwrap_or_else(|e| e.into_inner()) = value;
91        let l = self
92            .state
93            .waitsets
94            .lock()
95            .unwrap_or_else(|e| e.into_inner());
96        for w in l.iter().filter_map(Weak::upgrade) {
97            w.wake();
98        }
99    }
100
101    /// The trigger value (`get_trigger_value`).
102    pub fn trigger_value(&self) -> bool {
103        *self.state.trigger.lock().unwrap_or_else(|e| e.into_inner())
104    }
105}
106
107/// The condition of an entity's communication statuses (DDS 1.4,
108/// 2.2.2.1.9): true when one of its enabled statuses has changed since it
109/// was last read (`get_status_changes() & get_enabled_statuses()`).
110///
111/// A status is read with its `*_status` getter; DATA_AVAILABLE by
112/// reading or taking samples. A status given to a listener is read too.
113/// Every StatusCondition of an entity is the same condition.
114#[derive(Clone)]
115pub struct StatusCondition {
116    shared: Arc<Shared>,
117    entity: Guid,
118}
119
120impl std::fmt::Debug for StatusCondition {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        f.debug_struct("StatusCondition")
123            .field("entity", &self.entity)
124            .finish()
125    }
126}
127
128impl PartialEq for StatusCondition {
129    fn eq(&self, other: &Self) -> bool {
130        Arc::ptr_eq(&self.shared, &other.shared) && self.entity == other.entity
131    }
132}
133
134impl StatusCondition {
135    pub(crate) fn new(shared: Arc<Shared>, entity: Guid) -> Self {
136        StatusCondition { shared, entity }
137    }
138
139    /// The GUID of its entity (`get_entity`).
140    pub fn entity(&self) -> Guid {
141        self.entity
142    }
143
144    /// Sets the statuses the condition is triggered by
145    /// (`set_enabled_statuses`). All are, at first.
146    pub fn set_enabled_statuses(&self, mask: StatusMask) {
147        {
148            let mut g = self.shared.lock_any();
149            if let Some(w) = g.writers.get_mut(&self.entity) {
150                w.enabled = mask;
151            } else if let Some(r) = g.readers.get_mut(&self.entity) {
152                r.enabled = mask;
153            }
154        }
155        self.shared.wake_waitsets();
156    }
157
158    /// The statuses the condition is triggered by
159    /// (`get_enabled_statuses`).
160    pub fn enabled_statuses(&self) -> StatusMask {
161        let g = self.shared.lock_any();
162        if let Some(w) = g.writers.get(&self.entity) {
163            w.enabled
164        } else if let Some(r) = g.readers.get(&self.entity) {
165            r.enabled
166        } else {
167            StatusMask::NONE
168        }
169    }
170
171    /// The trigger value (`get_trigger_value`).
172    pub fn trigger_value(&self) -> bool {
173        let g = self.shared.lock_any();
174        if let Some(w) = g.writers.get(&self.entity) {
175            w.changes.intersects(w.enabled)
176        } else if let Some(r) = g.readers.get(&self.entity) {
177            r.changes.intersects(r.enabled)
178        } else {
179            false
180        }
181    }
182}
183
184/// A condition on the samples of a reader (DDS 1.4, 2.2.2.5.8): true
185/// while the reader has a sample whose states pass its filter. Made with
186/// `DataReader::create_readcondition`; reading or taking with
187/// `DataReader::read_w_condition` or `take_w_condition` selects the same
188/// samples.
189///
190/// Clones are the same condition.
191#[derive(Clone)]
192pub struct ReadCondition {
193    shared: Arc<Shared>,
194    reader: Guid,
195    filter: StateFilter,
196    /// Its identity.
197    id: Arc<()>,
198}
199
200impl std::fmt::Debug for ReadCondition {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        f.debug_struct("ReadCondition")
203            .field("reader", &self.reader)
204            .field("filter", &self.filter)
205            .finish()
206    }
207}
208
209impl PartialEq for ReadCondition {
210    fn eq(&self, other: &Self) -> bool {
211        Arc::ptr_eq(&self.id, &other.id)
212    }
213}
214
215impl ReadCondition {
216    pub(crate) fn new(shared: Arc<Shared>, reader: Guid, filter: StateFilter) -> Self {
217        ReadCondition {
218            shared,
219            reader,
220            filter,
221            id: Arc::new(()),
222        }
223    }
224
225    /// The GUID of its reader (`get_datareader`).
226    pub fn reader(&self) -> Guid {
227        self.reader
228    }
229
230    /// The states of the samples it is true for (`get_sample_state_mask`,
231    /// `get_view_state_mask` and `get_instance_state_mask`).
232    pub fn filter(&self) -> StateFilter {
233        self.filter
234    }
235
236    /// The trigger value (`get_trigger_value`).
237    pub fn trigger_value(&self) -> bool {
238        let g = self.shared.lock_any();
239        g.readers
240            .get(&self.reader)
241            .is_some_and(|r| r.samples.has_matching(self.filter))
242    }
243}
244
245/// A condition to attach to a [`WaitSet`] (DDS 1.4 `Condition`,
246/// 2.2.2.1.6).
247#[derive(Clone, Debug, PartialEq)]
248pub enum Condition {
249    /// A [`GuardCondition`].
250    Guard(GuardCondition),
251    /// A [`StatusCondition`].
252    Status(StatusCondition),
253    /// A [`ReadCondition`].
254    Read(ReadCondition),
255}
256
257impl PartialEq for GuardCondition {
258    fn eq(&self, other: &Self) -> bool {
259        Arc::ptr_eq(&self.state, &other.state)
260    }
261}
262
263impl Condition {
264    /// The trigger value (`get_trigger_value`).
265    pub fn trigger_value(&self) -> bool {
266        match self {
267            Condition::Guard(c) => c.trigger_value(),
268            Condition::Status(c) => c.trigger_value(),
269            Condition::Read(c) => c.trigger_value(),
270        }
271    }
272
273    /// Has the WaitSet of `waker` woken when the condition may change.
274    fn register(&self, waker: &Arc<Waker>) {
275        match self {
276            Condition::Guard(c) => register(&c.state.waitsets, waker),
277            Condition::Status(c) => register(&c.shared.waitsets, waker),
278            Condition::Read(c) => register(&c.shared.waitsets, waker),
279        }
280    }
281}
282
283macro_rules! from_condition {
284    ($t:ident, $v:ident) => {
285        impl From<$t> for Condition {
286            fn from(c: $t) -> Condition {
287                Condition::$v(c)
288            }
289        }
290
291        impl From<&$t> for Condition {
292            fn from(c: &$t) -> Condition {
293                Condition::$v(c.clone())
294            }
295        }
296
297        impl PartialEq<$t> for Condition {
298            fn eq(&self, other: &$t) -> bool {
299                matches!(self, Condition::$v(c) if c == other)
300            }
301        }
302    };
303}
304
305from_condition!(GuardCondition, Guard);
306from_condition!(StatusCondition, Status);
307from_condition!(ReadCondition, Read);
308
309/// A set of conditions a thread waits on (DDS 1.4, 2.2.2.1.7): `wait`
310/// returns when one of them is true.
311///
312/// One thread at a time may wait on a WaitSet. It works with plain
313/// threads; no async runtime is needed.
314///
315/// ```no_run
316/// # fn f(reader: &rustorb_dds::DataReader<impl rustorb_typesupport::TopicType>)
317/// #     -> rustorb_dds::Result<()> {
318/// use std::time::Duration;
319/// use rustorb_dds::{GuardCondition, StatusMask, WaitSet};
320///
321/// let status = reader.status_condition();
322/// status.set_enabled_statuses(StatusMask::DATA_AVAILABLE);
323/// let stop = GuardCondition::new();
324/// let waitset = WaitSet::new();
325/// waitset.attach_condition(&status)?;
326/// waitset.attach_condition(&stop)?;
327/// loop {
328///     let active = waitset.wait(Duration::from_secs(10))?;
329///     if active.iter().any(|c| *c == stop) {
330///         break;
331///     }
332///     for s in reader.take() {
333///         println!("{:?}", s.info);
334///     }
335/// }
336/// # Ok(())
337/// # }
338/// ```
339#[derive(Debug, Default)]
340pub struct WaitSet {
341    waker: Arc<Waker>,
342    conditions: Mutex<Vec<Condition>>,
343    waiting: AtomicBool,
344}
345
346/// Clears the waiting flag of a WaitSet when its `wait` returns.
347struct Waiting<'a>(&'a AtomicBool);
348
349impl Drop for Waiting<'_> {
350    fn drop(&mut self) {
351        self.0.store(false, Ordering::Release);
352    }
353}
354
355impl WaitSet {
356    /// An empty WaitSet.
357    pub fn new() -> Self {
358        Self::default()
359    }
360
361    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Condition>> {
362        self.conditions.lock().unwrap_or_else(|e| e.into_inner())
363    }
364
365    /// Attaches a condition (`attach_condition`); attaching one already
366    /// attached does nothing. A thread waiting on the WaitSet checks it
367    /// at once.
368    pub fn attach_condition(&self, condition: impl Into<Condition>) -> Result<()> {
369        let c = condition.into();
370        {
371            let mut l = self.lock();
372            if l.contains(&c) {
373                return Ok(());
374            }
375            c.register(&self.waker);
376            l.push(c);
377        }
378        self.waker.wake();
379        Ok(())
380    }
381
382    /// Detaches a condition (`detach_condition`). Fails with
383    /// [`Error::PreconditionNotMet`] if it is not attached.
384    pub fn detach_condition(&self, condition: impl Into<Condition>) -> Result<()> {
385        let c = condition.into();
386        let mut l = self.lock();
387        let Some(i) = l.iter().position(|x| *x == c) else {
388            return Err(Error::PreconditionNotMet);
389        };
390        l.remove(i);
391        Ok(())
392    }
393
394    /// The conditions attached (`get_conditions`).
395    pub fn conditions(&self) -> Vec<Condition> {
396        self.lock().clone()
397    }
398
399    /// Waits until at least one attached condition is true, and returns
400    /// those that are (`wait`). Returns at once if one is true already.
401    ///
402    /// Fails with [`Error::Timeout`] if `timeout` passes first, and with
403    /// [`Error::PreconditionNotMet`] if another thread is waiting on the
404    /// WaitSet. A `timeout` of [`Duration::MAX`] waits for ever.
405    pub fn wait(&self, timeout: Duration) -> Result<Vec<Condition>> {
406        if self.waiting.swap(true, Ordering::AcqRel) {
407            return Err(Error::PreconditionNotMet);
408        }
409        let _waiting = Waiting(&self.waiting);
410        let deadline = Instant::now().checked_add(timeout);
411        loop {
412            // The generation is read before the conditions are checked:
413            // a change after the check wakes the wait below.
414            let generation = self.waker.generation();
415            let active: Vec<Condition> = self
416                .conditions()
417                .into_iter()
418                .filter(Condition::trigger_value)
419                .collect();
420            if !active.is_empty() {
421                return Ok(active);
422            }
423            if deadline.is_some_and(|d| Instant::now() >= d) {
424                return Err(Error::Timeout);
425            }
426            self.waker.wait(generation, deadline);
427        }
428    }
429}