rustorb-dds-ros2 0.4.0

The ROS 2 conventions on DDS for rustorb-dds: names, interface types from .msg/.srv, RIHS01 type hashes, node discovery
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! ROS 2 names and their DDS names.
//!
//! ROS 2 (Jazzy, `rmw_fastrtps_cpp` and `rmw_cyclonedds_cpp`), seen from
//! outside, puts on DDS:
//!
//! - a topic `/ns/name` as the DDS topic `rt/ns/name`;
//! - a service `/ns/name` as the request topic `rq/ns/nameRequest` and
//!   the reply topic `rr/ns/nameReply`;
//! - a message type `pkg/msg/Name` as the DDS type
//!   `pkg::msg::dds_::Name_`, and the request and response of a service
//!   type `pkg/srv/Name` as `pkg::srv::dds_::Name_Request_` and
//!   `pkg::srv::dds_::Name_Response_`.
//!
//! The rules on the names themselves are those of the ROS 2 design
//! article "Topic and Service name mapping to DDS" and of the ROS 2
//! documentation on names: a name is tokens of `[A-Za-z0-9_]` that do not
//! start with a digit, separated by `/`; no empty token, no `__`, no
//! trailing `/`. A fully qualified name starts with `/`.

use std::fmt;

use crate::{Error, Result};

/// The prefix of the DDS topic of a ROS 2 topic.
pub const TOPIC_PREFIX: &str = "rt";
/// The prefix of the DDS topic of the requests of a ROS 2 service.
pub const REQUEST_PREFIX: &str = "rq";
/// The prefix of the DDS topic of the replies of a ROS 2 service.
pub const REPLY_PREFIX: &str = "rr";
/// The suffix of the DDS topic of the requests of a ROS 2 service.
pub const REQUEST_SUFFIX: &str = "Request";
/// The suffix of the DDS topic of the replies of a ROS 2 service.
pub const REPLY_SUFFIX: &str = "Reply";

/// The kind of an interface: a message, a service or an action.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum InterfaceKind {
    /// `msg`.
    Message,
    /// `srv`.
    Service,
    /// `action`.
    Action,
}

impl InterfaceKind {
    /// `msg`, `srv` or `action`.
    pub fn as_str(self) -> &'static str {
        match self {
            InterfaceKind::Message => "msg",
            InterfaceKind::Service => "srv",
            InterfaceKind::Action => "action",
        }
    }

    fn parse(s: &str) -> Option<InterfaceKind> {
        match s {
            "msg" => Some(InterfaceKind::Message),
            "srv" => Some(InterfaceKind::Service),
            "action" => Some(InterfaceKind::Action),
            _ => None,
        }
    }
}

/// The name of an interface type: `pkg/msg/Name`, `pkg/srv/Name`, or a
/// part of a service such as `pkg/srv/Name_Request`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TypeName {
    /// The package.
    pub package: String,
    /// `msg`, `srv` or `action`.
    pub kind: InterfaceKind,
    /// The name in the package.
    pub name: String,
}

impl TypeName {
    /// `package/kind/name`, its parts checked.
    pub fn new(package: &str, kind: InterfaceKind, name: &str) -> Result<TypeName> {
        validate_package_name(package)?;
        validate_type_base_name(name)?;
        Ok(TypeName {
            package: package.to_string(),
            kind,
            name: name.to_string(),
        })
    }

    /// A message type `package/msg/name`.
    pub fn message(package: &str, name: &str) -> Result<TypeName> {
        TypeName::new(package, InterfaceKind::Message, name)
    }

    /// Parses `pkg/msg/Name`, `pkg/srv/Name` or `pkg/action/Name`; `pkg/Name`
    /// is the message `pkg/msg/Name`.
    pub fn parse(s: &str) -> Result<TypeName> {
        let parts: Vec<&str> = s.split('/').collect();
        match parts.as_slice() {
            [p, n] => TypeName::new(p, InterfaceKind::Message, n),
            [p, k, n] => match InterfaceKind::parse(k) {
                Some(kind) => TypeName::new(p, kind, n),
                None => Err(Error::Name(format!(
                    "{s:?}: the kind must be msg, srv or action"
                ))),
            },
            _ => Err(Error::Name(format!(
                "{s:?} is not a type name pkg/msg/Name"
            ))),
        }
    }

    /// The name with a suffix: `pkg/srv/Name` and `_Request` is
    /// `pkg/srv/Name_Request`.
    pub fn with_suffix(&self, suffix: &str) -> TypeName {
        TypeName {
            package: self.package.clone(),
            kind: self.kind,
            name: format!("{}{suffix}", self.name),
        }
    }

    /// The DDS type name: `pkg::msg::dds_::Name_`.
    pub fn dds_name(&self) -> String {
        format!(
            "{}::{}::dds_::{}_",
            self.package,
            self.kind.as_str(),
            self.name
        )
    }

    /// The type of a DDS type name `pkg::msg::dds_::Name_`, if it is one
    /// that ROS 2 makes.
    pub fn from_dds_name(dds: &str) -> Option<TypeName> {
        let parts: Vec<&str> = dds.split("::").collect();
        match parts.as_slice() {
            [p, k, "dds_", n] => {
                let kind = InterfaceKind::parse(k)?;
                let n = n.strip_suffix('_')?;
                TypeName::new(p, kind, n).ok()
            }
            _ => None,
        }
    }
}

impl fmt::Display for TypeName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}/{}", self.package, self.kind.as_str(), self.name)
    }
}

fn is_name_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

/// Checks the tokens of a name (between the `/`).
fn validate_tokens(what: &str, name: &str, body: &str) -> Result<()> {
    if body.is_empty() {
        return Ok(());
    }
    if body.ends_with('/') {
        return Err(Error::Name(format!("{what} {name:?} ends with '/'")));
    }
    for token in body.split('/') {
        if token.is_empty() {
            return Err(Error::Name(format!("{what} {name:?} has an empty token")));
        }
        if let Some(c) = token.chars().find(|c| !is_name_char(*c)) {
            return Err(Error::Name(format!(
                "{what} {name:?} has the character {c:?}"
            )));
        }
        if token.starts_with(|c: char| c.is_ascii_digit()) {
            return Err(Error::Name(format!(
                "{what} {name:?} has a token that starts with a digit"
            )));
        }
    }
    if name.contains("__") {
        return Err(Error::Name(format!("{what} {name:?} has '__'")));
    }
    Ok(())
}

/// Checks a fully qualified topic or service name: `/` or `/a/b`.
pub fn validate_full_topic_name(name: &str) -> Result<()> {
    let Some(body) = name.strip_prefix('/') else {
        return Err(Error::Name(format!(
            "topic name {name:?} is not fully qualified (does not start with '/')"
        )));
    };
    if body.is_empty() {
        return Err(Error::Name("topic name \"/\" is empty".to_string()));
    }
    validate_tokens("topic name", name, body)
}

/// Checks a node name: `[A-Za-z_][A-Za-z0-9_]*`, without `__`.
pub fn validate_node_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(Error::Name("the node name is empty".to_string()));
    }
    if name.contains('/') {
        return Err(Error::Name(format!("node name {name:?} has '/'")));
    }
    validate_tokens("node name", name, name)
}

/// Checks a namespace: `/` or `/a/b`.
pub fn validate_namespace(namespace: &str) -> Result<()> {
    let Some(body) = namespace.strip_prefix('/') else {
        return Err(Error::Name(format!(
            "namespace {namespace:?} does not start with '/'"
        )));
    };
    validate_tokens("namespace", namespace, body)
}

/// Checks a package name: `[a-z][a-z0-9_]*`, without `__` and not
/// ending with `_`.
pub fn validate_package_name(name: &str) -> Result<()> {
    let ok = name.starts_with(|c: char| c.is_ascii_lowercase())
        && name
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
        && !name.contains("__")
        && !name.ends_with('_');
    if ok {
        Ok(())
    } else {
        Err(Error::Name(format!(
            "package name {name:?} is not [a-z][a-z0-9_]* (without '__', not ending in '_')"
        )))
    }
}

/// Checks the base name of a type: `[A-Z][A-Za-z0-9_]*`.
pub fn validate_type_base_name(name: &str) -> Result<()> {
    let ok = name.starts_with(|c: char| c.is_ascii_uppercase()) && name.chars().all(is_name_char);
    if ok {
        Ok(())
    } else {
        Err(Error::Name(format!(
            "type name {name:?} is not [A-Z][A-Za-z0-9_]*"
        )))
    }
}

/// The fully qualified name of node `name` in `namespace`: `/ns/name`.
pub fn node_full_name(namespace: &str, name: &str) -> String {
    if namespace == "/" {
        format!("/{name}")
    } else {
        format!("{namespace}/{name}")
    }
}

/// Expands a topic or service name for node `node_name` in
/// `namespace`: a name that starts with `/` is kept, `~` and `~/x` are
/// the node's own (`/ns/node`, `/ns/node/x`), and the others are in the
/// namespace (`x` is `/ns/x`). The result is checked.
pub fn expand_topic_name(name: &str, node_name: &str, namespace: &str) -> Result<String> {
    validate_namespace(namespace)?;
    validate_node_name(node_name)?;
    let full = if name.starts_with('/') {
        name.to_string()
    } else if name == "~" {
        node_full_name(namespace, node_name)
    } else if let Some(rest) = name.strip_prefix("~/") {
        format!("{}/{rest}", node_full_name(namespace, node_name))
    } else if namespace == "/" {
        format!("/{name}")
    } else {
        format!("{namespace}/{name}")
    };
    if full.contains('{') || full.contains('~') {
        return Err(Error::Name(format!(
            "topic name {name:?}: substitutions are not supported"
        )));
    }
    validate_full_topic_name(&full)?;
    Ok(full)
}

/// The DDS topic of a ROS 2 topic: `/chatter` is `rt/chatter`.
pub fn topic_to_dds(full_name: &str) -> Result<String> {
    validate_full_topic_name(full_name)?;
    Ok(format!("{TOPIC_PREFIX}{full_name}"))
}

/// The DDS topics of the requests and of the replies of a ROS 2
/// service: `/add_two_ints` is `rq/add_two_intsRequest` and
/// `rr/add_two_intsReply`.
pub fn service_to_dds(full_name: &str) -> Result<(String, String)> {
    validate_full_topic_name(full_name)?;
    Ok((
        format!("{REQUEST_PREFIX}{full_name}{REQUEST_SUFFIX}"),
        format!("{REPLY_PREFIX}{full_name}{REPLY_SUFFIX}"),
    ))
}

/// What a DDS topic is in ROS 2.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DdsTopic {
    /// The ROS 2 topic of this name (`rt/`).
    Topic(String),
    /// The requests of the ROS 2 service of this name (`rq/`).
    Request(String),
    /// The replies of the ROS 2 service of this name (`rr/`).
    Reply(String),
}

/// The ROS 2 topic or service of a DDS topic, if ROS 2 made it.
pub fn topic_from_dds(dds: &str) -> Option<DdsTopic> {
    let ros = |prefix: &str, suffix: &str| -> Option<String> {
        let rest = dds.strip_prefix(prefix)?.strip_suffix(suffix)?;
        rest.starts_with('/')
            .then(|| rest.to_string())
            .filter(|n| validate_full_topic_name(n).is_ok())
    };
    if let Some(n) = ros(TOPIC_PREFIX, "") {
        Some(DdsTopic::Topic(n))
    } else if let Some(n) = ros(REQUEST_PREFIX, REQUEST_SUFFIX) {
        Some(DdsTopic::Request(n))
    } else {
        ros(REPLY_PREFIX, REPLY_SUFFIX).map(DdsTopic::Reply)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn type_names() {
        let t = TypeName::parse("std_msgs/msg/String").unwrap();
        assert_eq!(t.dds_name(), "std_msgs::msg::dds_::String_");
        assert_eq!(t.to_string(), "std_msgs/msg/String");
        assert_eq!(TypeName::parse("std_msgs/String").unwrap(), t);
        assert_eq!(
            TypeName::from_dds_name("std_msgs::msg::dds_::String_"),
            Some(t)
        );
        let s = TypeName::parse("example_interfaces/srv/AddTwoInts").unwrap();
        assert_eq!(
            s.with_suffix("_Request").dds_name(),
            "example_interfaces::srv::dds_::AddTwoInts_Request_"
        );
        assert!(TypeName::parse("Std/msg/String").is_err());
        assert!(TypeName::parse("std_msgs/msg/string").is_err());
        assert!(TypeName::parse("std_msgs/foo/String").is_err());
        assert_eq!(TypeName::from_dds_name("HelloWorld"), None);
    }

    #[test]
    fn topics() {
        assert_eq!(topic_to_dds("/chatter").unwrap(), "rt/chatter");
        assert_eq!(
            service_to_dds("/add_two_ints").unwrap(),
            (
                "rq/add_two_intsRequest".to_string(),
                "rr/add_two_intsReply".to_string()
            )
        );
        assert!(topic_to_dds("chatter").is_err());
        assert!(topic_to_dds("/a//b").is_err());
        assert!(topic_to_dds("/a/").is_err());
        assert!(topic_to_dds("/a/1b").is_err());
        assert!(topic_to_dds("/a__b").is_err());
        assert!(topic_to_dds("/a-b").is_err());
        assert_eq!(
            topic_from_dds("rt/ns/chatter"),
            Some(DdsTopic::Topic("/ns/chatter".into()))
        );
        assert_eq!(
            topic_from_dds("rq/add_two_intsRequest"),
            Some(DdsTopic::Request("/add_two_ints".into()))
        );
        assert_eq!(
            topic_from_dds("rr/add_two_intsReply"),
            Some(DdsTopic::Reply("/add_two_ints".into()))
        );
        assert_eq!(topic_from_dds("ros_discovery_info"), None);
    }

    #[test]
    fn expansion() {
        assert_eq!(
            expand_topic_name("chatter", "talker", "/").unwrap(),
            "/chatter"
        );
        assert_eq!(
            expand_topic_name("chatter", "talker", "/robot").unwrap(),
            "/robot/chatter"
        );
        assert_eq!(expand_topic_name("/x", "talker", "/robot").unwrap(), "/x");
        assert_eq!(
            expand_topic_name("~/state", "talker", "/robot").unwrap(),
            "/robot/talker/state"
        );
        assert_eq!(expand_topic_name("~", "talker", "/").unwrap(), "/talker");
        assert!(expand_topic_name("{node}/x", "talker", "/").is_err());
        assert!(expand_topic_name("x", "1talker", "/").is_err());
        assert!(expand_topic_name("x", "talker", "robot").is_err());
        assert!(validate_namespace("/").is_ok());
        assert!(validate_namespace("/a/b").is_ok());
        assert!(validate_namespace("/a/").is_err());
    }
}