1use std::collections::BTreeSet;
30use std::sync::Arc;
31use std::time::{Duration, Instant};
32
33use astrs_ros2::graph::{EndpointInfo, GraphQuery, NodeInfo};
34use astrs_ros2::names::mangle::TopicKind;
35use astrs_ros2::node::{ContextOptions, NodeOptions, Ros2Context, Ros2Node};
36use astrs_rtps::behavior::MulticastCapability;
37use astrs_rtps::discovery::RosCompat;
38use astrs_rtps::structure::Locator;
39use serde::Serialize;
40
41use crate::error::CliError;
42
43pub const DEFAULT_DOMAIN_ID: u32 = 0;
46
47pub const ENV_DOMAIN_ID: &str = "ROS_DOMAIN_ID";
49
50pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2);
57
58pub const QUIET_PERIOD: Duration = Duration::from_millis(400);
61
62pub const POLL_INTERVAL: Duration = Duration::from_millis(25);
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct ProbeArgs {
68 pub domain_id: u32,
70 pub timeout: Duration,
72 pub include_hidden: bool,
74 pub json: bool,
76}
77
78impl Default for ProbeArgs {
79 fn default() -> Self {
80 Self {
81 domain_id: domain_id_from_env(),
82 timeout: DEFAULT_TIMEOUT,
83 include_hidden: false,
84 json: false,
85 }
86 }
87}
88
89impl ProbeArgs {
90 #[must_use]
97 pub const fn query(&self) -> GraphQuery {
98 let query = GraphQuery::new().remote_only();
99 if self.include_hidden {
100 query.with_hidden()
101 } else {
102 query
103 }
104 }
105}
106
107#[must_use]
114pub fn domain_id_from_env() -> u32 {
115 std::env::var(ENV_DOMAIN_ID)
116 .ok()
117 .and_then(|raw| raw.trim().parse::<u32>().ok())
118 .unwrap_or(DEFAULT_DOMAIN_ID)
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
123pub struct ParticipantSummary {
124 pub guid: String,
126 pub is_astrs: bool,
128 pub nodes: Vec<String>,
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
134pub struct TopicSummary {
135 pub name: String,
137 pub types: Vec<String>,
140 pub publishers: usize,
142 pub subscribers: usize,
144 pub publisher_nodes: Vec<String>,
146 pub subscriber_nodes: Vec<String>,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
152pub struct ProbeReport {
153 pub domain_id: u32,
155 pub listened_ms: u64,
157 pub multicast: String,
159 pub multicast_joined: bool,
161 pub locator: String,
163 pub participants: Vec<ParticipantSummary>,
165 pub nodes: Vec<String>,
167 pub topics: Vec<TopicSummary>,
169 pub services: Vec<TopicSummary>,
171 pub actions: Vec<TopicSummary>,
173 pub unclaimed_endpoints: usize,
176}
177
178impl ProbeReport {
179 #[must_use]
181 pub fn endpoint_count(&self) -> usize {
182 self.topics
183 .iter()
184 .chain(&self.services)
185 .chain(&self.actions)
186 .map(|entry| entry.publishers.saturating_add(entry.subscribers))
187 .sum()
188 }
189
190 #[must_use]
192 pub fn is_empty(&self) -> bool {
193 self.participants.is_empty() && self.topics.is_empty()
194 }
195}
196
197pub fn probe(args: &ProbeArgs) -> Result<ProbeReport, CliError> {
205 let runtime = tokio::runtime::Builder::new_multi_thread()
206 .worker_threads(2)
207 .enable_all()
208 .build()
209 .map_err(|error| CliError::Ros2(format!("no runtime for the probe: {error}")))?;
210 runtime.block_on(probe_async(args))
211}
212
213pub async fn probe_async(args: &ProbeArgs) -> Result<ProbeReport, CliError> {
219 let started = Instant::now();
220 let options = ContextOptions::new(args.domain_id)
221 .with_compat(RosCompat::Jazzy)
226 .with_multicast(true);
227 let context = Ros2Context::new(options)
228 .await
229 .map_err(|error| CliError::Ros2(format!("the probe participant: {error}")))?;
230
231 let node = Ros2Node::new(
236 Arc::clone(&context),
237 format!("astrs_probe_{}", std::process::id()),
238 NodeOptions::default().with_parameter_services(false),
239 )
240 .await
241 .map_err(|error| CliError::Ros2(format!("the probe node: {error}")))?;
242
243 let report = listen(&context, &node, args, started).await;
244
245 if let Err(error) = node.shutdown().await {
248 tracing::debug!(%error, "the probe node was already shut down");
249 }
250 context.shutdown().await;
251
252 report
253}
254
255async fn listen(
257 context: &Arc<Ros2Context>,
258 node: &Ros2Node,
259 args: &ProbeArgs,
260 started: Instant,
261) -> Result<ProbeReport, CliError> {
262 let deadline = started + args.timeout;
263 let graph = node.graph();
264 let mut seen = 0_usize;
265 let mut last_change = Instant::now();
266
267 while Instant::now() < deadline {
268 let count = graph.known_participants().await;
269 if count != seen {
270 seen = count;
271 last_change = Instant::now();
272 } else if seen > 0 && last_change.elapsed() >= QUIET_PERIOD {
273 break;
274 }
275 tokio::time::sleep(POLL_INTERVAL).await;
276 }
277
278 let query = args.query();
279 let nodes = graph.nodes(query).await;
280 let endpoints = graph.endpoints(query).await;
281
282 Ok(ProbeReport {
283 domain_id: args.domain_id,
284 listened_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
285 multicast: describe_multicast(context.multicast()),
286 multicast_joined: context.multicast().is_joined(),
287 locator: describe_locator(context.metatraffic_locator()),
288 participants: summarize_participants(&nodes, graph.known_participants().await),
289 nodes: node_names(&nodes),
290 topics: summarize(&endpoints, TopicKind::Topic),
291 services: summarize(&endpoints, TopicKind::Request),
292 actions: summarize_actions(&endpoints),
293 unclaimed_endpoints: endpoints
294 .iter()
295 .filter(|endpoint| endpoint.is_unclaimed())
296 .count(),
297 })
298}
299
300#[must_use]
302pub fn describe_multicast(capability: &MulticastCapability) -> String {
303 match capability {
304 MulticastCapability::Joined { group } => format!("joined {group}"),
305 MulticastCapability::Disabled => "disabled".to_owned(),
306 MulticastCapability::Refused { group, reason } => {
307 format!("refused {group} ({reason})")
308 }
309 }
310}
311
312#[must_use]
314pub fn describe_locator(locator: Locator) -> String {
315 locator.socket_addr().map_or_else(
316 |_| "unaddressable".to_owned(),
317 |address| address.to_string(),
318 )
319}
320
321fn node_names(nodes: &[NodeInfo]) -> Vec<String> {
323 let mut names: Vec<String> = nodes.iter().map(NodeInfo::fully_qualified).collect();
324 names.sort_unstable();
325 names.dedup();
326 names
327}
328
329fn summarize_participants(nodes: &[NodeInfo], known: usize) -> Vec<ParticipantSummary> {
331 use std::collections::BTreeMap;
332
333 let mut by_participant: BTreeMap<String, ParticipantSummary> = BTreeMap::new();
334 for info in nodes {
335 let guid = info.participant.prefix.to_string();
336 let entry = by_participant
337 .entry(guid.clone())
338 .or_insert_with(|| ParticipantSummary {
339 is_astrs: info.participant.prefix.vendor_id()
340 == astrs_rtps::structure::VendorId::ASTRS,
341 guid,
342 nodes: Vec::new(),
343 });
344 entry.nodes.push(info.fully_qualified());
345 }
346 for entry in by_participant.values_mut() {
347 entry.nodes.sort_unstable();
348 entry.nodes.dedup();
349 }
350
351 let listed = by_participant.len();
356 let mut summaries: Vec<ParticipantSummary> = by_participant.into_values().collect();
357 for index in listed..known {
358 summaries.push(ParticipantSummary {
359 guid: format!("<unannounced #{}>", index.saturating_sub(listed) + 1),
360 is_astrs: false,
361 nodes: Vec::new(),
362 });
363 }
364 summaries
365}
366
367fn summarize(endpoints: &[EndpointInfo], kind: TopicKind) -> Vec<TopicSummary> {
369 use std::collections::BTreeMap;
370
371 let mut grouped: BTreeMap<&str, Grouped> = BTreeMap::new();
372 for endpoint in endpoints {
373 let matches = match kind {
374 TopicKind::Topic => endpoint.kind == TopicKind::Topic,
375 _ => endpoint.kind.is_service(),
378 };
379 if !matches || is_action_endpoint(&endpoint.name) {
380 continue;
381 }
382 grouped
383 .entry(endpoint.name.as_str())
384 .or_default()
385 .absorb(endpoint);
386 }
387 grouped
388 .into_iter()
389 .map(|(name, group)| group.finish(name.to_owned()))
390 .collect()
391}
392
393fn summarize_actions(endpoints: &[EndpointInfo]) -> Vec<TopicSummary> {
395 use std::collections::BTreeMap;
396
397 let mut grouped: BTreeMap<String, Grouped> = BTreeMap::new();
398 for endpoint in endpoints {
399 let Some((action, _)) = astrs_ros2::names::mangle::split_action_name(&endpoint.name) else {
400 continue;
401 };
402 grouped
403 .entry(action.to_owned())
404 .or_default()
405 .absorb(endpoint);
406 }
407 grouped
408 .into_iter()
409 .map(|(name, group)| group.finish(name))
410 .collect()
411}
412
413fn is_action_endpoint(name: &str) -> bool {
415 astrs_ros2::names::mangle::split_action_name(name).is_some()
416}
417
418#[derive(Debug, Default)]
420struct Grouped {
421 types: BTreeSet<String>,
422 publishers: usize,
423 subscribers: usize,
424 publisher_nodes: BTreeSet<String>,
425 subscriber_nodes: BTreeSet<String>,
426}
427
428impl Grouped {
429 fn absorb(&mut self, endpoint: &EndpointInfo) {
430 if !endpoint.type_name.is_empty() {
431 self.types.insert(endpoint.type_name.clone());
432 }
433 let node = if endpoint.is_unclaimed() {
434 "<unclaimed>".to_owned()
435 } else {
436 endpoint.node.clone()
437 };
438 if endpoint.is_publisher {
439 self.publishers = self.publishers.saturating_add(1);
440 self.publisher_nodes.insert(node);
441 } else {
442 self.subscribers = self.subscribers.saturating_add(1);
443 self.subscriber_nodes.insert(node);
444 }
445 }
446
447 fn finish(self, name: String) -> TopicSummary {
448 TopicSummary {
449 name,
450 types: self.types.into_iter().collect(),
451 publishers: self.publishers,
452 subscribers: self.subscribers,
453 publisher_nodes: self.publisher_nodes.into_iter().collect(),
454 subscriber_nodes: self.subscriber_nodes.into_iter().collect(),
455 }
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
462
463 use astrs_rtps::discovery::Gid;
464 use astrs_rtps::structure::{EntityId, EntityKind, Guid, GuidPrefix, VendorId};
465
466 use super::*;
467
468 fn guid(seed: u8) -> Guid {
469 Guid::new(
470 GuidPrefix::vendor_scoped(VendorId::ASTRS, [seed; 10]),
471 EntityId::user_defined(1, EntityKind::USER_WRITER_NO_KEY),
472 )
473 }
474
475 fn endpoint(
476 node: &str,
477 name: &str,
478 type_name: &str,
479 is_publisher: bool,
480 kind: TopicKind,
481 ) -> EndpointInfo {
482 EndpointInfo {
483 node: node.to_owned(),
484 name: name.to_owned(),
485 type_name: type_name.to_owned(),
486 gid: Gid::new(RosCompat::Jazzy, guid(1)),
487 is_publisher,
488 is_local: false,
489 kind,
490 }
491 }
492
493 #[test]
494 fn the_default_timeout_and_domain_are_the_documented_ones() {
495 let args = ProbeArgs {
496 domain_id: 0,
497 ..ProbeArgs::default()
498 };
499 assert_eq!(args.timeout, DEFAULT_TIMEOUT);
500 assert_eq!(args.domain_id, 0);
501 assert!(!args.json);
502 assert!(!args.include_hidden);
503 }
504
505 #[test]
506 fn the_query_excludes_the_probes_own_endpoints() {
507 let args = ProbeArgs::default();
508 assert!(!args.query().include_local);
509 assert!(!args.query().include_hidden);
510
511 let hidden = ProbeArgs {
512 include_hidden: true,
513 ..ProbeArgs::default()
514 };
515 assert!(hidden.query().include_hidden);
516 assert!(!hidden.query().include_local);
517 }
518
519 #[test]
520 fn topics_are_grouped_by_name_with_their_endpoint_counts() {
521 let endpoints = vec![
522 endpoint(
523 "/talker",
524 "/chatter",
525 "std_msgs/msg/String",
526 true,
527 TopicKind::Topic,
528 ),
529 endpoint(
530 "/listener",
531 "/chatter",
532 "std_msgs/msg/String",
533 false,
534 TopicKind::Topic,
535 ),
536 endpoint(
537 "/other",
538 "/chatter",
539 "std_msgs/msg/String",
540 false,
541 TopicKind::Topic,
542 ),
543 endpoint(
544 "/talker",
545 "/scan",
546 "sensor_msgs/msg/LaserScan",
547 true,
548 TopicKind::Topic,
549 ),
550 ];
551 let topics = summarize(&endpoints, TopicKind::Topic);
552 assert_eq!(topics.len(), 2);
553 assert_eq!(topics[0].name, "/chatter", "sorted by name");
554 assert_eq!(topics[0].publishers, 1);
555 assert_eq!(topics[0].subscribers, 2);
556 assert_eq!(topics[0].types, vec!["std_msgs/msg/String"]);
557 assert_eq!(topics[0].publisher_nodes, vec!["/talker"]);
558 assert_eq!(topics[0].subscriber_nodes, vec!["/listener", "/other"]);
559 assert_eq!(topics[1].name, "/scan");
560 }
561
562 #[test]
563 fn two_types_on_one_topic_are_both_reported() {
564 let endpoints = vec![
565 endpoint("/a", "/x", "std_msgs/msg/String", true, TopicKind::Topic),
566 endpoint("/b", "/x", "std_msgs/msg/Int32", false, TopicKind::Topic),
567 ];
568 let topics = summarize(&endpoints, TopicKind::Topic);
569 assert_eq!(
570 topics[0].types,
571 vec!["std_msgs/msg/Int32", "std_msgs/msg/String"],
572 "a type disagreement is shown, not collapsed"
573 );
574 }
575
576 #[test]
577 fn a_services_two_halves_are_one_entry() {
578 let endpoints = vec![
579 endpoint(
580 "/server",
581 "/add_two_ints",
582 "example_interfaces/srv/AddTwoInts_Request",
583 false,
584 TopicKind::Request,
585 ),
586 endpoint(
587 "/server",
588 "/add_two_ints",
589 "example_interfaces/srv/AddTwoInts_Response",
590 true,
591 TopicKind::Reply,
592 ),
593 ];
594 let services = summarize(&endpoints, TopicKind::Request);
595 assert_eq!(services.len(), 1);
596 assert_eq!(services[0].name, "/add_two_ints");
597 assert_eq!(services[0].publishers, 1);
598 assert_eq!(services[0].subscribers, 1);
599 }
600
601 #[test]
602 fn an_actions_endpoints_are_grouped_under_the_action_name() {
603 let endpoints = vec![
604 endpoint(
605 "/server",
606 "/fibonacci/_action/send_goal",
607 "example_interfaces/action/Fibonacci_SendGoal_Request",
608 false,
609 TopicKind::Request,
610 ),
611 endpoint(
612 "/server",
613 "/fibonacci/_action/feedback",
614 "example_interfaces/action/Fibonacci_FeedbackMessage",
615 true,
616 TopicKind::Topic,
617 ),
618 ];
619 let actions = summarize_actions(&endpoints);
620 assert_eq!(actions.len(), 1);
621 assert_eq!(actions[0].name, "/fibonacci");
622 assert_eq!(actions[0].publishers, 1);
623 assert_eq!(actions[0].subscribers, 1);
624
625 assert!(summarize(&endpoints, TopicKind::Topic).is_empty());
627 assert!(summarize(&endpoints, TopicKind::Request).is_empty());
628 }
629
630 #[test]
631 fn an_unclaimed_endpoint_is_labelled_rather_than_dropped() {
632 let endpoints = vec![endpoint(
633 "",
634 "/mystery",
635 "some/msg/Type",
636 true,
637 TopicKind::Topic,
638 )];
639 let topics = summarize(&endpoints, TopicKind::Topic);
640 assert_eq!(topics[0].publisher_nodes, vec!["<unclaimed>"]);
641 }
642
643 #[test]
644 fn participants_are_grouped_and_unannounced_ones_are_counted() {
645 let nodes = vec![
646 NodeInfo {
647 name: "talker".to_owned(),
648 namespace: "/".to_owned(),
649 participant: guid(1),
650 is_local: false,
651 enclave: None,
652 },
653 NodeInfo {
654 name: "listener".to_owned(),
655 namespace: "/".to_owned(),
656 participant: guid(1),
657 is_local: false,
658 enclave: None,
659 },
660 ];
661 let summaries = summarize_participants(&nodes, 3);
662 assert_eq!(summaries.len(), 3, "one announced, two unannounced");
663 assert_eq!(summaries[0].nodes, vec!["/listener", "/talker"]);
664 assert!(
665 summaries[0].is_astrs,
666 "the fixture uses the AstRS vendor id"
667 );
668 assert!(summaries[1].nodes.is_empty());
669 }
670
671 #[test]
672 fn the_multicast_capability_renders_every_outcome() {
673 let group = std::net::Ipv4Addr::new(239, 255, 0, 1);
674 assert_eq!(
675 describe_multicast(&MulticastCapability::Joined { group }),
676 "joined 239.255.0.1"
677 );
678 assert_eq!(
679 describe_multicast(&MulticastCapability::Disabled),
680 "disabled"
681 );
682 }
683
684 #[test]
685 fn an_empty_report_says_so() {
686 let report = ProbeReport {
687 domain_id: 0,
688 listened_ms: 10,
689 multicast: "joined".to_owned(),
690 multicast_joined: true,
691 locator: "127.0.0.1:7400".to_owned(),
692 participants: Vec::new(),
693 nodes: Vec::new(),
694 topics: Vec::new(),
695 services: Vec::new(),
696 actions: Vec::new(),
697 unclaimed_endpoints: 0,
698 };
699 assert!(report.is_empty());
700 assert_eq!(report.endpoint_count(), 0);
701 }
702
703 #[test]
704 fn a_malformed_ros_domain_id_falls_back_rather_than_failing() {
705 assert_eq!(DEFAULT_DOMAIN_ID, 0);
708 assert!(domain_id_from_env() < 233, "a legal ROS domain id");
709 }
710}