Skip to main content

rustorb_rtps/
qos.rs

1//! The QoS policies that endpoint discovery reads and matches on.
2//!
3//! The policies and their default values come from the DDS 1.4
4//! specification (2.2.3 and the IDL in 2.3.3). How they are written in a
5//! parameter list comes from DDSI-RTPS 2.5, 9.6.3 (Tables 9.18 and 9.19).
6//!
7//! RELIABILITY, DURABILITY, DEADLINE, LIVELINESS and PARTITION are
8//! modelled (rustorb-dds#6, rustorb-dds#19). Other policies sent by remote
9//! endpoints are skipped.
10
11use crate::error::DecodeError;
12use crate::parameter::Parameter;
13use crate::pl::{PlBuilder, PlValues, pid};
14use crate::types::Duration;
15
16/// `ReliabilityQosPolicyKind`. On the wire it is `ReliabilityKind_t`:
17/// `BEST_EFFORT = 1`, `RELIABLE = 2` (DDSI-RTPS 2.5, 9.3.2 and Table 9.18
18/// note 3), not the DDS enum ordinal.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub enum ReliabilityKind {
21    /// `BEST_EFFORT_RELIABILITY_QOS`.
22    BestEffort,
23    /// `RELIABLE_RELIABILITY_QOS`.
24    Reliable,
25}
26
27/// `ReliabilityQosPolicy`.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29pub struct Reliability {
30    /// The kind.
31    pub kind: ReliabilityKind,
32    /// How long `write` may block when there is no room.
33    pub max_blocking_time: Duration,
34}
35
36impl Reliability {
37    /// The default `max_blocking_time`: 100 ms (DDS 1.4, 2.2.3).
38    pub fn default_max_blocking_time() -> Duration {
39        Duration::from_std(std::time::Duration::from_millis(100))
40    }
41
42    /// The default for DataWriters: RELIABLE (DDS 1.4, 2.2.3).
43    pub fn writer_default() -> Self {
44        Reliability {
45            kind: ReliabilityKind::Reliable,
46            max_blocking_time: Self::default_max_blocking_time(),
47        }
48    }
49
50    /// The default for DataReaders and Topics: BEST_EFFORT (DDS 1.4,
51    /// 2.2.3).
52    pub fn reader_default() -> Self {
53        Reliability {
54            kind: ReliabilityKind::BestEffort,
55            max_blocking_time: Self::default_max_blocking_time(),
56        }
57    }
58
59    /// Reads `PID_RELIABILITY`: `{ long kind; Duration_t max_blocking_time; }`.
60    ///
61    /// Some senders write only the kind; the blocking time then takes its
62    /// default. An unknown kind is an error.
63    pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
64        let bad = DecodeError::InvalidParameterValue(p.id);
65        let kind = match v.u32(p)? {
66            1 => ReliabilityKind::BestEffort,
67            2 => ReliabilityKind::Reliable,
68            _ => return Err(bad),
69        };
70        let max_blocking_time = if p.value.len() >= 12 {
71            let rest = Parameter::new(p.id, p.value[4..12].to_vec());
72            v.duration(&rest)?
73        } else {
74            Self::default_max_blocking_time()
75        };
76        Ok(Reliability {
77            kind,
78            max_blocking_time,
79        })
80    }
81
82    /// Writes `PID_RELIABILITY`.
83    pub fn to_parameter(&self, b: &PlBuilder) -> Parameter {
84        let kind: u32 = match self.kind {
85            ReliabilityKind::BestEffort => 1,
86            ReliabilityKind::Reliable => 2,
87        };
88        let mut value = b.u32(pid::RELIABILITY, kind).value;
89        value.extend(b.duration(pid::RELIABILITY, self.max_blocking_time).value);
90        Parameter::new(pid::RELIABILITY, value)
91    }
92}
93
94/// `DurabilityQosPolicyKind`, in the order of the DDS enum, which is also
95/// the order used to compare an offered and a requested kind (DDS 1.4,
96/// 2.2.3.4).
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
98pub enum DurabilityKind {
99    /// `VOLATILE_DURABILITY_QOS`, the default.
100    #[default]
101    Volatile,
102    /// `TRANSIENT_LOCAL_DURABILITY_QOS`.
103    TransientLocal,
104    /// `TRANSIENT_DURABILITY_QOS`.
105    Transient,
106    /// `PERSISTENT_DURABILITY_QOS`.
107    Persistent,
108}
109
110impl DurabilityKind {
111    /// Reads `PID_DURABILITY`: `{ DurabilityQosPolicyKind kind; }`, the
112    /// enum being a 32-bit ordinal.
113    pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
114        Ok(match v.u32(p)? {
115            0 => DurabilityKind::Volatile,
116            1 => DurabilityKind::TransientLocal,
117            2 => DurabilityKind::Transient,
118            3 => DurabilityKind::Persistent,
119            _ => return Err(DecodeError::InvalidParameterValue(p.id)),
120        })
121    }
122
123    /// Writes `PID_DURABILITY`.
124    pub fn to_parameter(self, b: &PlBuilder) -> Parameter {
125        b.u32(pid::DURABILITY, self as u32)
126    }
127}
128
129/// `DurabilityServiceQosPolicy` (DDS 1.4, 2.2.3.5): the HISTORY and
130/// RESOURCE_LIMITS of the service that keeps the samples of a TRANSIENT
131/// or PERSISTENT writer, and when it drops a disposed instance. The
132/// counts are `long`s, `-1` being `LENGTH_UNLIMITED`.
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134pub struct DurabilityService {
135    /// `service_cleanup_delay`.
136    pub service_cleanup_delay: Duration,
137    /// `history_kind`: 0 is KEEP_LAST, 1 KEEP_ALL.
138    pub history_kind: u32,
139    /// `history_depth`.
140    pub history_depth: i32,
141    /// `max_samples`.
142    pub max_samples: i32,
143    /// `max_instances`.
144    pub max_instances: i32,
145    /// `max_samples_per_instance`.
146    pub max_samples_per_instance: i32,
147}
148
149impl Default for DurabilityService {
150    /// No cleanup delay, KEEP_LAST 1, no limits (DDS 1.4, 2.2.3).
151    fn default() -> Self {
152        DurabilityService {
153            service_cleanup_delay: Duration::ZERO,
154            history_kind: 0,
155            history_depth: 1,
156            max_samples: -1,
157            max_instances: -1,
158            max_samples_per_instance: -1,
159        }
160    }
161}
162
163impl DurabilityService {
164    /// Reads `PID_DURABILITY_SERVICE`: `{ Duration_t
165    /// service_cleanup_delay; HistoryQosPolicyKind history_kind; long
166    /// history_depth, max_samples, max_instances,
167    /// max_samples_per_instance; }`.
168    pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
169        if p.value.len() < 28 {
170            return Err(DecodeError::InvalidParameterValue(p.id));
171        }
172        let at = |i: usize| v.u32(&Parameter::new(p.id, p.value[i..i + 4].to_vec()));
173        Ok(DurabilityService {
174            service_cleanup_delay: v.duration(&Parameter::new(p.id, p.value[..8].to_vec()))?,
175            history_kind: at(8)?,
176            history_depth: at(12)? as i32,
177            max_samples: at(16)? as i32,
178            max_instances: at(20)? as i32,
179            max_samples_per_instance: at(24)? as i32,
180        })
181    }
182
183    /// Writes `PID_DURABILITY_SERVICE`.
184    pub fn to_parameter(&self, b: &PlBuilder) -> Parameter {
185        let id = pid::DURABILITY_SERVICE;
186        let mut value = b.duration(id, self.service_cleanup_delay).value;
187        for n in [
188            self.history_kind,
189            self.history_depth as u32,
190            self.max_samples as u32,
191            self.max_instances as u32,
192            self.max_samples_per_instance as u32,
193        ] {
194            value.extend(b.u32(id, n).value);
195        }
196        Parameter::new(id, value)
197    }
198}
199
200/// `LivelinessQosPolicyKind`, in the order of the DDS enum, which is also
201/// the order used to compare an offered and a requested kind (DDS 1.4,
202/// 2.2.3.11).
203#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
204pub enum LivelinessKind {
205    /// `AUTOMATIC_LIVELINESS_QOS`, the default: the service asserts the
206    /// liveliness of the writers of a participant that is running.
207    #[default]
208    Automatic,
209    /// `MANUAL_BY_PARTICIPANT_LIVELINESS_QOS`: the application asserts
210    /// it for all the writers of a participant.
211    ManualByParticipant,
212    /// `MANUAL_BY_TOPIC_LIVELINESS_QOS`: the application asserts it for
213    /// each writer.
214    ManualByTopic,
215}
216
217/// `LivelinessQosPolicy` (DDS 1.4, 2.2.3.11).
218#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219pub struct Liveliness {
220    /// The kind.
221    pub kind: LivelinessKind,
222    /// How long an entity is alive without asserting it.
223    pub lease_duration: Duration,
224}
225
226impl Default for Liveliness {
227    /// AUTOMATIC, with an infinite lease (DDS 1.4, 2.2.3).
228    fn default() -> Self {
229        Liveliness {
230            kind: LivelinessKind::Automatic,
231            lease_duration: Duration::INFINITE,
232        }
233    }
234}
235
236impl Liveliness {
237    /// Reads `PID_LIVELINESS`: `{ LivelinessQosPolicyKind kind;
238    /// Duration_t lease_duration; }`, the enum being a 32-bit ordinal.
239    pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
240        let kind = match v.u32(p)? {
241            0 => LivelinessKind::Automatic,
242            1 => LivelinessKind::ManualByParticipant,
243            2 => LivelinessKind::ManualByTopic,
244            _ => return Err(DecodeError::InvalidParameterValue(p.id)),
245        };
246        let lease_duration = if p.value.len() >= 12 {
247            v.duration(&Parameter::new(p.id, p.value[4..12].to_vec()))?
248        } else {
249            Duration::INFINITE
250        };
251        Ok(Liveliness {
252            kind,
253            lease_duration,
254        })
255    }
256
257    /// Writes `PID_LIVELINESS`.
258    pub fn to_parameter(&self, b: &PlBuilder) -> Parameter {
259        let mut value = b.u32(pid::LIVELINESS, self.kind as u32).value;
260        value.extend(b.duration(pid::LIVELINESS, self.lease_duration).value);
261        Parameter::new(pid::LIVELINESS, value)
262    }
263}
264
265/// `QosPolicyId_t` (DDS 1.4, 2.3.3): which policy made a writer and a
266/// reader incompatible.
267#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
268pub struct QosPolicyId(pub u32);
269
270impl QosPolicyId {
271    /// `DURABILITY_QOS_POLICY_ID`.
272    pub const DURABILITY: QosPolicyId = QosPolicyId(2);
273    /// `DEADLINE_QOS_POLICY_ID`.
274    pub const DEADLINE: QosPolicyId = QosPolicyId(4);
275    /// `LIVELINESS_QOS_POLICY_ID`.
276    pub const LIVELINESS: QosPolicyId = QosPolicyId(8);
277    /// `RELIABILITY_QOS_POLICY_ID`.
278    pub const RELIABILITY: QosPolicyId = QosPolicyId(11);
279}
280
281/// The policies an offering writer and a requesting reader set.
282#[derive(Clone, Copy, Debug, PartialEq, Eq)]
283pub struct RxO {
284    /// RELIABILITY kind.
285    pub reliability: ReliabilityKind,
286    /// DURABILITY kind.
287    pub durability: DurabilityKind,
288    /// DEADLINE period.
289    pub deadline: Duration,
290    /// LIVELINESS.
291    pub liveliness: Liveliness,
292}
293
294/// The policies for which what a writer offers does not satisfy what a
295/// reader requests (the "requested/offered" rules of DDS 1.4, 2.2.3):
296/// RELIABILITY and DURABILITY kinds, offered >= requested; DEADLINE,
297/// offered period <= requested; LIVELINESS, offered kind >= requested and
298/// offered lease <= requested. Empty when they are compatible.
299pub fn incompatible_policies(offered: &RxO, requested: &RxO) -> Vec<QosPolicyId> {
300    let mut out = Vec::new();
301    if offered.durability < requested.durability {
302        out.push(QosPolicyId::DURABILITY);
303    }
304    if offered.deadline > requested.deadline {
305        out.push(QosPolicyId::DEADLINE);
306    }
307    if offered.liveliness.kind < requested.liveliness.kind
308        || offered.liveliness.lease_duration > requested.liveliness.lease_duration
309    {
310        out.push(QosPolicyId::LIVELINESS);
311    }
312    if offered.reliability < requested.reliability {
313        out.push(QosPolicyId::RELIABILITY);
314    }
315    out
316}
317
318/// Whether two PARTITION lists share a partition (DDS 1.4, 2.2.3.13). An
319/// empty list means the default partition, `""`.
320///
321/// A name may hold the POSIX fnmatch wildcards `*`, `?` and `[...]`; it
322/// then matches the names of the other side that fit it. Two names that
323/// both hold wildcards never match each other, even when equal.
324pub fn partitions_match(a: &[String], b: &[String]) -> bool {
325    let default = [String::new()];
326    let a = if a.is_empty() { &default[..] } else { a };
327    let b = if b.is_empty() { &default[..] } else { b };
328    a.iter()
329        .any(|x| b.iter().any(|y| partition_names_match(x, y)))
330}
331
332fn partition_names_match(a: &str, b: &str) -> bool {
333    match (has_wildcard(a), has_wildcard(b)) {
334        (false, false) => a == b,
335        (true, false) => fnmatch(a.as_bytes(), b.as_bytes()),
336        (false, true) => fnmatch(b.as_bytes(), a.as_bytes()),
337        (true, true) => false,
338    }
339}
340
341fn has_wildcard(s: &str) -> bool {
342    s.bytes().any(|c| matches!(c, b'*' | b'?' | b'['))
343}
344
345/// fnmatch without flags (POSIX.2 B.6): `*` matches any string, `?` any
346/// character, `[...]` a set (with ranges and `!` for negation), `\`
347/// quotes the next character. Works on octets.
348fn fnmatch(pattern: &[u8], name: &[u8]) -> bool {
349    match pattern.first() {
350        None => name.is_empty(),
351        Some(b'*') => {
352            // Any number of characters, then the rest of the pattern.
353            (0..=name.len()).any(|i| fnmatch(&pattern[1..], &name[i..]))
354        }
355        Some(b'?') => !name.is_empty() && fnmatch(&pattern[1..], &name[1..]),
356        Some(b'[') => {
357            let Some((&c, rest)) = name.split_first() else {
358                return false;
359            };
360            match bracket(&pattern[1..], c) {
361                Some((matched, after)) => matched && fnmatch(after, rest),
362                // No closing bracket: `[` is an ordinary character.
363                None => c == b'[' && fnmatch(&pattern[1..], rest),
364            }
365        }
366        Some(b'\\') if pattern.len() > 1 => {
367            name.first() == Some(&pattern[1]) && fnmatch(&pattern[2..], &name[1..])
368        }
369        Some(&p) => name.first() == Some(&p) && fnmatch(&pattern[1..], &name[1..]),
370    }
371}
372
373/// Matches `c` against a bracket expression whose text starts at `p`
374/// (after the `[`): whether it matched, and the pattern after the `]`.
375/// `None` when there is no closing `]`.
376fn bracket(p: &[u8], c: u8) -> Option<(bool, &[u8])> {
377    let (negate, mut i) = match p.first() {
378        Some(b'!') => (true, 1),
379        _ => (false, 0),
380    };
381    let mut matched = false;
382    let mut first = true;
383    loop {
384        let lo = *p.get(i)?;
385        if lo == b']' && !first {
386            return Some((matched != negate, &p[i + 1..]));
387        }
388        first = false;
389        if p.get(i + 1) == Some(&b'-') && p.get(i + 2).is_some_and(|h| *h != b']') {
390            let hi = p[i + 2];
391            matched |= lo <= c && c <= hi;
392            i += 3;
393        } else {
394            matched |= lo == c;
395            i += 1;
396        }
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use crate::wire::Endianness;
404
405    #[test]
406    fn reliability_wire() {
407        for e in [Endianness::Big, Endianness::Little] {
408            let b = PlBuilder::new(e);
409            let v = PlValues::new(e);
410            for r in [Reliability::writer_default(), Reliability::reader_default()] {
411                let p = r.to_parameter(&b);
412                assert_eq!(p.id, pid::RELIABILITY);
413                assert_eq!(p.value.len(), 12);
414                assert_eq!(Reliability::from_parameter(&v, &p).unwrap(), r);
415            }
416        }
417        let v = PlValues::new(Endianness::Little);
418        // RELIABLE is 2 on the wire, not the DDS ordinal 1.
419        let p = Parameter::new(pid::RELIABILITY, [2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]);
420        let r = Reliability::from_parameter(&v, &p).unwrap();
421        assert_eq!(r.kind, ReliabilityKind::Reliable);
422        assert_eq!(r.max_blocking_time, Duration::from_secs(1));
423        // Kind only.
424        let p = Parameter::new(pid::RELIABILITY, [1, 0, 0, 0]);
425        assert_eq!(
426            Reliability::from_parameter(&v, &p).unwrap(),
427            Reliability::reader_default()
428        );
429        let p = Parameter::new(pid::RELIABILITY, [0, 0, 0, 0]);
430        assert!(Reliability::from_parameter(&v, &p).is_err());
431    }
432
433    #[test]
434    fn durability_wire() {
435        let b = PlBuilder::new(Endianness::Big);
436        let v = PlValues::new(Endianness::Big);
437        for k in [
438            DurabilityKind::Volatile,
439            DurabilityKind::TransientLocal,
440            DurabilityKind::Transient,
441            DurabilityKind::Persistent,
442        ] {
443            assert_eq!(
444                DurabilityKind::from_parameter(&v, &k.to_parameter(&b)).unwrap(),
445                k
446            );
447        }
448        assert_eq!(
449            DurabilityKind::TransientLocal.to_parameter(&b).value,
450            [0, 0, 0, 1]
451        );
452        let p = Parameter::new(pid::DURABILITY, [0, 0, 0, 4]);
453        assert!(DurabilityKind::from_parameter(&v, &p).is_err());
454    }
455
456    #[test]
457    fn liveliness_wire() {
458        for e in [Endianness::Big, Endianness::Little] {
459            let b = PlBuilder::new(e);
460            let v = PlValues::new(e);
461            for l in [
462                Liveliness::default(),
463                Liveliness {
464                    kind: LivelinessKind::ManualByTopic,
465                    lease_duration: Duration::from_secs(3),
466                },
467            ] {
468                let p = l.to_parameter(&b);
469                assert_eq!(p.value.len(), 12);
470                assert_eq!(Liveliness::from_parameter(&v, &p).unwrap(), l);
471            }
472        }
473        let v = PlValues::new(Endianness::Little);
474        let p = Parameter::new(pid::LIVELINESS, [1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]);
475        assert_eq!(
476            Liveliness::from_parameter(&v, &p).unwrap(),
477            Liveliness {
478                kind: LivelinessKind::ManualByParticipant,
479                lease_duration: Duration::from_secs(2),
480            }
481        );
482        let p = Parameter::new(pid::LIVELINESS, [3, 0, 0, 0]);
483        assert!(Liveliness::from_parameter(&v, &p).is_err());
484    }
485
486    #[test]
487    fn matching_rules() {
488        use DurabilityKind::*;
489        use ReliabilityKind::*;
490        let rxo = |reliability, durability| RxO {
491            reliability,
492            durability,
493            deadline: Duration::INFINITE,
494            liveliness: Liveliness::default(),
495        };
496        let none: Vec<QosPolicyId> = Vec::new();
497        assert_eq!(
498            incompatible_policies(&rxo(Reliable, Volatile), &rxo(BestEffort, Volatile)),
499            none
500        );
501        assert_eq!(
502            incompatible_policies(&rxo(Reliable, TransientLocal), &rxo(Reliable, Volatile)),
503            none
504        );
505        assert_eq!(
506            incompatible_policies(&rxo(BestEffort, Volatile), &rxo(Reliable, TransientLocal)),
507            [QosPolicyId::DURABILITY, QosPolicyId::RELIABILITY]
508        );
509        // DEADLINE: the writer must promise at least as often.
510        let mut w = rxo(Reliable, Volatile);
511        let mut r = rxo(Reliable, Volatile);
512        r.deadline = Duration::from_secs(1);
513        assert_eq!(incompatible_policies(&w, &r), [QosPolicyId::DEADLINE]);
514        w.deadline = Duration::from_secs(1);
515        assert_eq!(incompatible_policies(&w, &r), none);
516        // LIVELINESS: kind and lease.
517        r.liveliness = Liveliness {
518            kind: LivelinessKind::ManualByParticipant,
519            lease_duration: Duration::from_secs(5),
520        };
521        assert_eq!(incompatible_policies(&w, &r), [QosPolicyId::LIVELINESS]);
522        w.liveliness = Liveliness {
523            kind: LivelinessKind::ManualByTopic,
524            lease_duration: Duration::from_secs(10),
525        };
526        assert_eq!(incompatible_policies(&w, &r), [QosPolicyId::LIVELINESS]);
527        w.liveliness.lease_duration = Duration::from_secs(5);
528        assert_eq!(incompatible_policies(&w, &r), none);
529    }
530
531    #[test]
532    fn partitions() {
533        let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
534        assert!(partitions_match(&[], &[]));
535        assert!(partitions_match(&[], &s(&[""])));
536        assert!(!partitions_match(&[], &s(&["a"])));
537        assert!(partitions_match(&s(&["a", "b"]), &s(&["b"])));
538        // Wildcards on either side, not on both.
539        assert!(partitions_match(&s(&["sensors/*"]), &s(&["sensors/front"])));
540        assert!(partitions_match(&s(&["sensors/front"]), &s(&["sensors/*"])));
541        assert!(!partitions_match(&s(&["sensors/*"]), &s(&["sensors/*"])));
542        assert!(!partitions_match(&s(&["sensors/*"]), &s(&["robot/1"])));
543        assert!(partitions_match(&s(&["*"]), &[]));
544    }
545
546    #[test]
547    fn fnmatch_rules() {
548        let m = |p: &str, n: &str| fnmatch(p.as_bytes(), n.as_bytes());
549        assert!(m("*", ""));
550        assert!(m("a*c", "abbbc"));
551        assert!(!m("a*c", "abbbd"));
552        assert!(m("a?c", "abc"));
553        assert!(!m("a?c", "ac"));
554        assert!(m("[abc]x", "bx"));
555        assert!(!m("[abc]x", "dx"));
556        assert!(m("[a-c]x", "bx"));
557        assert!(m("[!a-c]x", "dx"));
558        assert!(!m("[!a-c]x", "bx"));
559        assert!(m("[]]", "]"));
560        assert!(m("[a-]", "-"));
561        assert!(m("\\*", "*"));
562        assert!(!m("\\*", "a"));
563        // No closing bracket: an ordinary `[`.
564        assert!(m("[ab", "[ab"));
565    }
566}