1use crate::{
4 ParameterType, ParameterValue, QoSProfile,
5 heapless::{String, Vec},
6};
7use nros_node::timer::TimerClockSource;
13
14#[cfg(feature = "alloc")]
15use crate::{QoSDurabilityPolicy, QoSHistoryPolicy, QoSLivelinessPolicy, QoSReliabilityPolicy};
16#[cfg(feature = "alloc")]
17use alloc::{format, string::String as StdString, vec::Vec as StdVec};
22
23pub const SOURCE_METADATA_SCHEMA_VERSION: u32 = 7;
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum BufferedRow {
103 TypedBound,
105 Unbounded,
107}
108
109impl BufferedRow {
110 pub const fn as_str(self) -> &'static str {
112 match self {
113 Self::TypedBound => "typed_bound",
114 Self::Unbounded => "unbounded",
115 }
116 }
117}
118
119pub const DEFAULT_MAX_METADATA_NODES: usize = 8;
122pub const DEFAULT_MAX_METADATA_ENTITIES: usize = 32;
125pub const DEFAULT_MAX_METADATA_CALLBACKS: usize = 32;
128pub const METADATA_STRING_CAPACITY: usize = 128;
130
131pub type MetadataString = String<METADATA_STRING_CAPACITY>;
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136pub struct NodeSlot(pub usize);
137
138impl NodeSlot {
139 pub const fn new(index: usize) -> Self {
141 Self(index)
142 }
143
144 pub const fn index(self) -> usize {
146 self.0
147 }
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub struct EntitySlot(pub usize);
153
154impl EntitySlot {
155 pub const fn new(index: usize) -> Self {
157 Self(index)
158 }
159
160 pub const fn index(self) -> usize {
162 self.0
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
168pub struct CallbackSlot(pub usize);
169
170impl CallbackSlot {
171 pub const fn new(index: usize) -> Self {
173 Self(index)
174 }
175
176 pub const fn index(self) -> usize {
178 self.0
179 }
180}
181
182#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct SourceLocationMetadata {
185 pub artifact: MetadataString,
186 pub line: Option<u32>,
187 pub column: Option<u32>,
188}
189
190impl SourceLocationMetadata {
191 pub const fn empty() -> Self {
193 Self {
194 artifact: MetadataString::new(),
195 line: None,
196 column: None,
197 }
198 }
199
200 #[track_caller]
202 pub fn caller() -> Result<Self, NodeMetadataError> {
203 let location = core::panic::Location::caller();
204 Ok(Self {
205 artifact: copy_str_keep_tail(location.file())?,
222 line: Some(location.line()),
223 column: Some(location.column()),
224 })
225 }
226}
227
228#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum ParameterDefault {
231 Bool(bool),
232 Integer(i64),
233 Double(MetadataString),
234 String(MetadataString),
235 BoolArray,
236 IntegerArray,
237 DoubleArray,
238 StringArray,
239}
240
241impl ParameterDefault {
242 pub const fn parameter_type(&self) -> ParameterType {
244 match self {
245 Self::Bool(_) => ParameterType::Bool,
246 Self::Integer(_) => ParameterType::Integer,
247 Self::Double(_) => ParameterType::Double,
248 Self::String(_) => ParameterType::String,
249 Self::BoolArray => ParameterType::BoolArray,
250 Self::IntegerArray => ParameterType::IntegerArray,
251 Self::DoubleArray => ParameterType::DoubleArray,
252 Self::StringArray => ParameterType::StringArray,
253 }
254 }
255
256 pub fn from_value(value: &ParameterValue) -> Result<Self, NodeMetadataError> {
264 use core::fmt::Write as _;
265 Ok(match value {
266 ParameterValue::Bool(v) => Self::Bool(*v),
267 ParameterValue::Integer(v) => Self::Integer(*v),
268 ParameterValue::Double(v) => {
269 let mut text = MetadataString::new();
270 write!(text, "{v:?}").map_err(|_| NodeMetadataError::NameTooLong)?;
271 Self::Double(text)
272 }
273 ParameterValue::String(v) => Self::String(copy_str(v.as_str())?),
274 ParameterValue::BoolArray(_) => Self::BoolArray,
275 ParameterValue::IntegerArray(_) => Self::IntegerArray,
276 ParameterValue::DoubleArray(_) => Self::DoubleArray,
277 ParameterValue::StringArray(_) => Self::StringArray,
278 ParameterValue::ByteArray(_) | ParameterValue::NotSet => Self::Integer(0),
279 })
280 }
281
282 pub fn for_type(param_type: ParameterType) -> Result<Self, NodeMetadataError> {
284 Ok(match param_type {
285 ParameterType::Bool => Self::Bool(false),
286 ParameterType::Integer => Self::Integer(0),
287 ParameterType::Double => Self::Double(copy_str("0.0")?),
288 ParameterType::String => Self::String(copy_str("")?),
289 ParameterType::BoolArray => Self::BoolArray,
290 ParameterType::IntegerArray => Self::IntegerArray,
291 ParameterType::DoubleArray => Self::DoubleArray,
292 ParameterType::StringArray => Self::StringArray,
293 ParameterType::ByteArray | ParameterType::NotSet => Self::Integer(0),
294 })
295 }
296}
297
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300pub enum SourceNameKind {
301 Absolute,
303 Private,
305 Relative,
307}
308
309impl SourceNameKind {
310 pub const fn from_source_name(name: &str) -> Self {
312 let bytes = name.as_bytes();
313 if bytes.is_empty() {
314 Self::Relative
315 } else if bytes[0] == b'/' {
316 Self::Absolute
317 } else if bytes[0] == b'~' {
318 Self::Private
319 } else {
320 Self::Relative
321 }
322 }
323}
324
325pub use nros_node::names::{
332 MAX_RESOLVED_NAME_LEN, ResolvedName, expand_name, fully_qualified_name, resolve_name,
333};
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
337pub struct EntityId<'a>(pub &'a str);
338
339impl<'a> EntityId<'a> {
340 pub const fn new(id: &'a str) -> Self {
342 Self(id)
343 }
344
345 pub const fn as_str(self) -> &'a str {
347 self.0
348 }
349}
350
351#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
353pub struct NodeId<'a>(pub &'a str);
354
355impl<'a> NodeId<'a> {
356 pub const fn new(id: &'a str) -> Self {
358 Self(id)
359 }
360
361 pub const fn as_str(self) -> &'a str {
363 self.0
364 }
365}
366
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
369pub struct CallbackId<'a>(pub &'a str);
370
371impl<'a> CallbackId<'a> {
372 pub const fn new(id: &'a str) -> Self {
374 Self(id)
375 }
376
377 pub const fn as_str(self) -> &'a str {
379 self.0
380 }
381}
382
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385pub enum EntityKind {
386 Publisher,
387 Subscription,
388 Timer,
389 ServiceServer,
390 ServiceClient,
391 ActionServer,
392 ActionClient,
393 Parameter,
394}
395
396#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
414pub enum TimerKind {
415 #[default]
417 Wall,
418 Clock,
420 Oneshot,
422 InGroup,
424 GuardCondition,
426}
427
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
430pub enum CallbackEffectKind {
431 Reads,
432 Publishes,
433 Writes,
434}
435
436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
438pub enum NodeMetadataError {
439 Capacity,
441 NameTooLong,
443 UnknownNode,
445 UnknownEntity,
447 DuplicateId,
449}
450
451#[derive(Debug, Clone, PartialEq, Eq)]
453pub struct NodeMetadata {
454 pub slot: NodeSlot,
455 pub id: MetadataString,
456 pub source_default_name: MetadataString,
457 pub name: MetadataString,
458 pub namespace: MetadataString,
459 pub domain_id: u32,
460 pub code_managed: bool,
468}
469
470#[derive(Debug, Clone, PartialEq, Eq)]
472pub struct EntityMetadata {
473 pub slot: Option<EntitySlot>,
474 pub id: MetadataString,
475 pub node_slot: Option<NodeSlot>,
476 pub node_id: MetadataString,
477 pub kind: EntityKind,
478 pub source_name: MetadataString,
479 pub source_name_kind: SourceNameKind,
480 pub type_name: &'static str,
481 pub type_hash: &'static str,
482 pub action_hashes: Option<nros_node::ActionEndpointHashes<'static>>,
487 pub qos: QoSProfile,
488 pub callback_slot: Option<CallbackSlot>,
489 pub callback_id: Option<MetadataString>,
490 pub callback_source: SourceLocationMetadata,
491 pub callback_group: Option<MetadataString>,
492 pub action_cancel_callback_slot: Option<CallbackSlot>,
493 pub action_cancel_callback_id: Option<MetadataString>,
494 pub action_cancel_source: SourceLocationMetadata,
495 pub action_accepted_callback_slot: Option<CallbackSlot>,
496 pub action_accepted_callback_id: Option<MetadataString>,
497 pub action_accepted_source: SourceLocationMetadata,
498 pub period_ms: Option<u64>,
499 pub period_us: Option<u64>,
505 pub timer_clock: TimerClockSource,
516 pub timer_autostart: bool,
524 pub timer_kind: TimerKind,
527 pub parameter_type: Option<ParameterType>,
528 pub parameter_default: Option<ParameterDefault>,
529 pub parameter_read_only: bool,
530 pub parameter_read: bool,
535 pub safety: bool,
543 pub message_info: bool,
549 pub in_place_capable: Option<bool>,
567 pub buffered_row: Option<BufferedRow>,
571 pub rx_bound: Option<usize>,
578 pub source: SourceLocationMetadata,
579}
580
581impl EntityMetadata {
582 pub fn declared_subscription_shape(
603 &self,
604 ) -> nros_node::executor::declared_shape::DeclaredSubscriptionShape {
605 #[cfg(feature = "safety-e2e")]
606 let safety = self.safety;
607 #[cfg(not(feature = "safety-e2e"))]
608 let safety = false;
609 nros_node::executor::declared_shape::DeclaredSubscriptionShape::of_declaration(
610 safety,
611 self.message_info,
612 )
613 }
614}
615
616#[derive(Debug, Clone, PartialEq, Eq)]
618pub struct CallbackEffectMetadata {
619 pub callback_id: MetadataString,
620 pub callback_slot: Option<CallbackSlot>,
621 pub kind: CallbackEffectKind,
622 pub entity_id: MetadataString,
623 pub entity_slot: Option<EntitySlot>,
624}
625
626#[cfg(feature = "alloc")]
628#[derive(Debug, Clone)]
629pub struct SourceMetadataExport<'a> {
630 pub package: &'a str,
631 pub component: &'a str,
632 pub executable: Option<&'a str>,
633 pub exported_symbol: Option<&'a str>,
634 pub package_manifest: &'a str,
635 pub source_artifacts: &'a [&'a str],
636 pub language: &'a str,
643}
644
645#[cfg(feature = "alloc")]
646impl<'a> SourceMetadataExport<'a> {
647 pub const fn new(package: &'a str, component: &'a str) -> Self {
649 Self {
650 package,
651 component,
652 executable: None,
653 exported_symbol: None,
654 package_manifest: "package.xml",
655 source_artifacts: &[],
656 language: "rust",
657 }
658 }
659
660 pub const fn language(mut self, language: &'a str) -> Self {
662 self.language = language;
663 self
664 }
665
666 pub const fn executable(mut self, executable: &'a str) -> Self {
668 self.executable = Some(executable);
669 self
670 }
671
672 pub const fn exported_symbol(mut self, exported_symbol: &'a str) -> Self {
674 self.exported_symbol = Some(exported_symbol);
675 self
676 }
677
678 pub const fn package_manifest(mut self, package_manifest: &'a str) -> Self {
680 self.package_manifest = package_manifest;
681 self
682 }
683
684 pub const fn source_artifacts(mut self, source_artifacts: &'a [&'a str]) -> Self {
686 self.source_artifacts = source_artifacts;
687 self
688 }
689}
690
691pub fn metadata_string(value: &str) -> Result<MetadataString, NodeMetadataError> {
694 copy_str(value)
695}
696
697pub(crate) fn copy_str_keep_tail(value: &str) -> Result<MetadataString, NodeMetadataError> {
706 if value.len() <= METADATA_STRING_CAPACITY {
707 return copy_str(value);
708 }
709 const MARK: &str = "…/";
711 let budget = METADATA_STRING_CAPACITY - MARK.len();
712 let tail = value
713 .char_indices()
714 .find(|(i, _)| value.len() - i <= budget)
715 .map(|(i, _)| &value[i..])
716 .unwrap_or("");
717 let tail = match tail.find('/') {
719 Some(cut) => &tail[cut + 1..],
720 None => tail,
721 };
722 let mut out = MetadataString::new();
723 out.push_str(MARK)
724 .map_err(|_| NodeMetadataError::NameTooLong)?;
725 out.push_str(tail)
726 .map_err(|_| NodeMetadataError::NameTooLong)?;
727 Ok(out)
728}
729
730pub(crate) fn copy_str(value: &str) -> Result<MetadataString, NodeMetadataError> {
731 let mut out = MetadataString::new();
732 out.push_str(value)
733 .map_err(|_| NodeMetadataError::NameTooLong)?;
734 Ok(out)
735}
736
737#[derive(Debug)]
747pub(crate) struct Rows<T, const N: usize> {
748 #[cfg(feature = "alloc")]
749 inner: alloc::vec::Vec<T>,
750 #[cfg(not(feature = "alloc"))]
751 inner: Vec<T, N>,
752}
753
754impl<T, const N: usize> Rows<T, N> {
755 pub(crate) const fn new() -> Self {
756 Self {
757 #[cfg(feature = "alloc")]
758 inner: alloc::vec::Vec::new(),
759 #[cfg(not(feature = "alloc"))]
760 inner: Vec::new(),
761 }
762 }
763
764 pub(crate) fn push(&mut self, value: T) -> Result<(), T> {
767 #[cfg(feature = "alloc")]
768 {
769 self.inner.push(value);
770 Ok(())
771 }
772 #[cfg(not(feature = "alloc"))]
773 {
774 self.inner.push(value)
775 }
776 }
777}
778
779impl<T, const N: usize> core::ops::Deref for Rows<T, N> {
780 type Target = [T];
781 fn deref(&self) -> &[T] {
782 &self.inner
783 }
784}
785
786impl<'a, T, const N: usize> IntoIterator for &'a Rows<T, N> {
787 type Item = &'a T;
788 type IntoIter = core::slice::Iter<'a, T>;
789 fn into_iter(self) -> Self::IntoIter {
790 self.iter()
791 }
792}
793
794impl<T, const N: usize> core::ops::DerefMut for Rows<T, N> {
795 fn deref_mut(&mut self) -> &mut [T] {
796 &mut self.inner
797 }
798}
799
800#[derive(Debug)]
807pub struct MetadataRecorder<
808 const MAX_NODES: usize = DEFAULT_MAX_METADATA_NODES,
809 const MAX_ENTITIES: usize = DEFAULT_MAX_METADATA_ENTITIES,
810 const MAX_CALLBACKS: usize = DEFAULT_MAX_METADATA_CALLBACKS,
811> {
812 nodes: Rows<NodeMetadata, MAX_NODES>,
813 entities: Rows<EntityMetadata, MAX_ENTITIES>,
814 callback_effects: Rows<CallbackEffectMetadata, MAX_CALLBACKS>,
815 description_max_len: Option<usize>,
820 constraints_max_len: Option<usize>,
822 parameter_declarations_watched: Option<bool>,
828}
829
830impl<const MAX_NODES: usize, const MAX_ENTITIES: usize, const MAX_CALLBACKS: usize> Default
831 for MetadataRecorder<MAX_NODES, MAX_ENTITIES, MAX_CALLBACKS>
832{
833 fn default() -> Self {
834 Self::new()
835 }
836}
837
838impl<const MAX_NODES: usize, const MAX_ENTITIES: usize, const MAX_CALLBACKS: usize>
839 MetadataRecorder<MAX_NODES, MAX_ENTITIES, MAX_CALLBACKS>
840{
841 pub const fn new() -> Self {
843 Self {
844 nodes: Rows::new(),
845 entities: Rows::new(),
846 callback_effects: Rows::new(),
847 description_max_len: None,
848 constraints_max_len: None,
849 parameter_declarations_watched: None,
850 }
851 }
852
853 pub fn arm_parameter_declarations(&mut self) {
858 self.parameter_declarations_watched.get_or_insert(true);
859 }
860
861 pub fn break_parameter_declarations(&mut self) {
865 if let Some(watched) = self.parameter_declarations_watched.as_mut() {
866 *watched = false;
867 }
868 }
869
870 pub fn parameter_declarations_watched(&self) -> Option<bool> {
873 self.parameter_declarations_watched
874 }
875
876 pub fn arm_descriptor_text(&mut self) {
880 self.description_max_len.get_or_insert(0);
881 self.constraints_max_len.get_or_insert(0);
882 }
883
884 pub fn observe_descriptor_text(&mut self, constraints: bool, len: usize) {
889 let slot = if constraints {
890 &mut self.constraints_max_len
891 } else {
892 &mut self.description_max_len
893 };
894 if let Some(max) = slot.as_mut() {
895 *max = (*max).max(len);
896 }
897 }
898
899 pub fn description_max_len(&self) -> Option<usize> {
901 self.description_max_len
902 }
903
904 pub fn constraints_max_len(&self) -> Option<usize> {
907 self.constraints_max_len
908 }
909
910 pub fn nodes(&self) -> &[NodeMetadata] {
912 &self.nodes
913 }
914
915 pub fn entities(&self) -> &[EntityMetadata] {
917 &self.entities
918 }
919
920 pub fn callback_effects(&self) -> &[CallbackEffectMetadata] {
922 &self.callback_effects
923 }
924
925 #[must_use]
953 pub fn observe_lifecycle_registration(&mut self, name: &str, namespace: &str) -> bool {
954 let want = namespace.trim_matches('/');
955 for node in self.nodes.iter_mut() {
956 if node.name.as_str() == name && node.namespace.as_str().trim_matches('/') == want {
957 node.code_managed = true;
958 return true;
959 }
960 }
961 false
962 }
963
964 #[must_use]
965 pub fn observe_subscription_registration(
966 &mut self,
967 source_name: &str,
968 type_name: &str,
969 in_place_capable: bool,
970 buffered_row: BufferedRow,
971 ) -> bool {
972 for entity in self.entities.iter_mut() {
973 if entity.kind == EntityKind::Subscription
974 && entity.in_place_capable.is_none()
975 && entity.source_name.as_str() == source_name
976 && entity.type_name == type_name
977 {
978 entity.in_place_capable = Some(in_place_capable);
979 entity.buffered_row = Some(buffered_row);
980 return true;
981 }
982 }
983 false
984 }
985
986 #[cfg(feature = "alloc")]
989 pub fn to_source_metadata_json(
990 &self,
991 export: &SourceMetadataExport<'_>,
992 ) -> Result<StdString, core::fmt::Error> {
993 let mut out = StdString::new();
994 self.write_source_metadata_json(export, &mut out)?;
995 Ok(out)
996 }
997
998 #[cfg(feature = "alloc")]
1001 pub fn write_source_metadata_json(
1002 &self,
1003 export: &SourceMetadataExport<'_>,
1004 out: &mut impl core::fmt::Write,
1005 ) -> core::fmt::Result {
1006 write!(out, "{{")?;
1007 write!(out, "\"version\":{},", SOURCE_METADATA_SCHEMA_VERSION)?;
1008 write_json_field(out, "package", export.package)?;
1009 out.write_char(',')?;
1010 write_json_field(out, "component", export.component)?;
1011 out.write_char(',')?;
1012 write_json_field(out, "language", export.language)?;
1013 out.write_char(',')?;
1014 write_json_opt_field(out, "executable", export.executable)?;
1015 out.write_char(',')?;
1016 write_json_opt_field(out, "exported_symbol", export.exported_symbol)?;
1017 out.write_char(',')?;
1018 self.write_nodes_json(out)?;
1019 out.write_char(',')?;
1020 self.write_callbacks_json(out)?;
1021 out.write_char(',')?;
1022 self.write_parameters_json(out)?;
1023 out.write_char(',')?;
1024 if let Some(len) = self.description_max_len {
1025 write!(out, "\"parameter_description_max_len\":{len},")?;
1026 }
1027 if let Some(len) = self.constraints_max_len {
1028 write!(out, "\"parameter_constraints_max_len\":{len},")?;
1029 }
1030 if let Some(watched) = self.parameter_declarations_watched {
1031 write!(out, "\"parameter_declarations_watched\":{watched},")?;
1032 }
1033 self.write_trace_json(export, out)?;
1034 write!(out, "}}")
1035 }
1036
1037 pub fn push_node(
1047 &mut self,
1048 id: NodeId<'_>,
1049 name: &str,
1050 namespace: &str,
1051 domain_id: u32,
1052 ) -> Result<(), NodeMetadataError> {
1053 if self.has_node(id.as_str()) {
1054 return Err(NodeMetadataError::DuplicateId);
1055 }
1056
1057 self.nodes
1058 .push(NodeMetadata {
1059 slot: NodeSlot::new(self.nodes.len()),
1060 id: copy_str(id.as_str())?,
1061 source_default_name: copy_str(name)?,
1062 name: copy_str(name)?,
1063 namespace: copy_str(namespace)?,
1064 domain_id,
1065 code_managed: false,
1066 })
1067 .map_err(|_| NodeMetadataError::Capacity)
1068 }
1069
1070 pub fn push_entity(&mut self, mut entity: EntityMetadata) -> Result<(), NodeMetadataError> {
1075 if !self.has_node(&entity.node_id) {
1076 return Err(NodeMetadataError::UnknownNode);
1077 }
1078 if self.has_entity(&entity.id) {
1079 return Err(NodeMetadataError::DuplicateId);
1080 }
1081
1082 entity.slot = Some(EntitySlot::new(self.entities.len()));
1083 entity.node_slot = self.node_slot_for_id(&entity.node_id);
1084 let mut current_callbacks = Vec::<MetadataString, 3>::new();
1085 let mut next_callback_slot = self.callback_slot_count();
1086 entity.callback_slot = entity.callback_id.as_ref().map(|callback_id| {
1087 self.callback_slot_for_current_entity(
1088 callback_id.as_str(),
1089 &mut current_callbacks,
1090 &mut next_callback_slot,
1091 )
1092 });
1093 entity.action_cancel_callback_slot =
1094 entity
1095 .action_cancel_callback_id
1096 .as_ref()
1097 .map(|callback_id| {
1098 self.callback_slot_for_current_entity(
1099 callback_id.as_str(),
1100 &mut current_callbacks,
1101 &mut next_callback_slot,
1102 )
1103 });
1104 entity.action_accepted_callback_slot =
1105 entity
1106 .action_accepted_callback_id
1107 .as_ref()
1108 .map(|callback_id| {
1109 self.callback_slot_for_current_entity(
1110 callback_id.as_str(),
1111 &mut current_callbacks,
1112 &mut next_callback_slot,
1113 )
1114 });
1115
1116 self.entities
1117 .push(entity)
1118 .map_err(|_| NodeMetadataError::Capacity)
1119 }
1120
1121 pub(crate) fn push_callback_effect(
1122 &mut self,
1123 callback_id: CallbackId<'_>,
1124 kind: CallbackEffectKind,
1125 entity_id: EntityId<'_>,
1126 ) -> Result<(), NodeMetadataError> {
1127 if !self.has_entity(entity_id.as_str()) {
1128 return Err(NodeMetadataError::UnknownEntity);
1129 }
1130
1131 self.callback_effects
1132 .push(CallbackEffectMetadata {
1133 callback_id: copy_str(callback_id.as_str())?,
1134 callback_slot: self.callback_slot_for_id(callback_id.as_str()),
1135 kind,
1136 entity_id: copy_str(entity_id.as_str())?,
1137 entity_slot: self.entity_slot_for_id(entity_id.as_str()),
1138 })
1139 .map_err(|_| NodeMetadataError::Capacity)
1140 }
1141
1142 pub(crate) fn has_node(&self, id: &str) -> bool {
1143 self.nodes.iter().any(|node| node.id.as_str() == id)
1144 }
1145
1146 pub(crate) fn has_entity(&self, id: &str) -> bool {
1147 self.entities.iter().any(|entity| entity.id.as_str() == id)
1148 }
1149
1150 fn node_slot_for_id(&self, id: &str) -> Option<NodeSlot> {
1151 self.nodes
1152 .iter()
1153 .find(|node| node.id.as_str() == id)
1154 .map(|node| node.slot)
1155 }
1156
1157 fn entity_slot_for_id(&self, id: &str) -> Option<EntitySlot> {
1158 self.entities
1159 .iter()
1160 .find(|entity| entity.id.as_str() == id)
1161 .and_then(|entity| entity.slot)
1162 }
1163
1164 fn callback_slot_for_current_entity(
1165 &self,
1166 id: &str,
1167 current_callbacks: &mut Vec<MetadataString, 3>,
1168 next_callback_slot: &mut usize,
1169 ) -> CallbackSlot {
1170 if let Some(slot) = self.callback_slot_for_id(id) {
1171 return slot;
1172 }
1173 if let Some((index, _)) = current_callbacks
1174 .iter()
1175 .enumerate()
1176 .find(|(_, callback_id)| callback_id.as_str() == id)
1177 {
1178 return CallbackSlot::new(self.callback_slot_count() + index);
1179 }
1180 let slot = CallbackSlot::new(*next_callback_slot);
1181 let _ = current_callbacks
1182 .push(copy_str(id).expect("callback ID already fits metadata string capacity"));
1183 *next_callback_slot += 1;
1184 slot
1185 }
1186
1187 fn callback_slot_for_id(&self, id: &str) -> Option<CallbackSlot> {
1188 let mut seen = Rows::<&str, MAX_CALLBACKS>::new();
1191 for entity in &self.entities {
1192 for callback_id in entity_callback_ids(entity) {
1193 let Some(callback_id) = callback_id else {
1194 continue;
1195 };
1196 let callback_id = callback_id.as_str();
1197 if seen.contains(&callback_id) {
1198 continue;
1199 }
1200 if callback_id == id {
1201 return Some(CallbackSlot::new(seen.len()));
1202 }
1203 let _ = seen.push(callback_id);
1204 }
1205 }
1206 None
1207 }
1208
1209 fn callback_slot_count(&self) -> usize {
1210 let mut seen = Rows::<&str, MAX_CALLBACKS>::new();
1213 for entity in &self.entities {
1214 for callback_id in entity_callback_ids(entity) {
1215 let Some(callback_id) = callback_id else {
1216 continue;
1217 };
1218 let callback_id = callback_id.as_str();
1219 if !seen.contains(&callback_id) {
1220 let _ = seen.push(callback_id);
1221 }
1222 }
1223 }
1224 seen.len()
1225 }
1226
1227 #[cfg(feature = "alloc")]
1228 fn write_nodes_json(&self, out: &mut impl core::fmt::Write) -> core::fmt::Result {
1229 write!(out, "\"nodes\":[")?;
1230 for (index, node) in self.nodes.iter().enumerate() {
1231 if index > 0 {
1232 out.write_char(',')?;
1233 }
1234 write!(out, "{{")?;
1235 write_json_field(out, "id", node.id.as_str())?;
1236 out.write_char(',')?;
1237 write!(out, "\"declaration_slot\":{},", node.slot.index())?;
1238 write_json_field(
1239 out,
1240 "source_default_name",
1241 node.source_default_name.as_str(),
1242 )?;
1243 out.write_char(',')?;
1244 write!(out, "\"unresolved_name\":")?;
1245 write_source_name(
1246 out,
1247 node.name.as_str(),
1248 SourceNameKind::from_source_name(&node.name),
1249 )?;
1250 out.write_char(',')?;
1251 if node.namespace.as_str() == "/" {
1252 write!(out, "\"namespace\":null,")?;
1253 } else {
1254 write_json_field(out, "namespace", node.namespace.as_str())?;
1255 out.write_char(',')?;
1256 }
1257 if node.code_managed {
1261 write!(out, "\"lifecycle\":true,")?;
1262 }
1263 self.write_node_entities(out, node.id.as_str())?;
1264 write!(out, "}}")?;
1265 }
1266 write!(out, "]")
1267 }
1268
1269 #[cfg(feature = "alloc")]
1270 fn write_node_entities(
1271 &self,
1272 out: &mut impl core::fmt::Write,
1273 node_id: &str,
1274 ) -> core::fmt::Result {
1275 self.write_entity_array(out, "publishers", node_id, EntityKind::Publisher)?;
1276 out.write_char(',')?;
1277 self.write_entity_array(out, "subscribers", node_id, EntityKind::Subscription)?;
1278 out.write_char(',')?;
1279 self.write_entity_array(out, "timers", node_id, EntityKind::Timer)?;
1283 out.write_char(',')?;
1284 self.write_entity_array(out, "services", node_id, EntityKind::ServiceServer)?;
1285 out.write_char(',')?;
1286 self.write_entity_array(out, "actions", node_id, EntityKind::ActionServer)?;
1287 out.write_char(',')?;
1294 self.write_entity_array(out, "action_clients", node_id, EntityKind::ActionClient)?;
1295 out.write_char(',')?;
1296 self.write_entity_array(out, "service_clients", node_id, EntityKind::ServiceClient)
1297 }
1298
1299 #[cfg(feature = "alloc")]
1300 fn write_entity_array(
1301 &self,
1302 out: &mut impl core::fmt::Write,
1303 field: &str,
1304 node_id: &str,
1305 kind: EntityKind,
1306 ) -> core::fmt::Result {
1307 write!(out, "\"{}\":[", field)?;
1308 for (index, entity) in self
1309 .entities
1310 .iter()
1311 .filter(|entity| entity.node_id.as_str() == node_id && entity.kind == kind)
1312 .enumerate()
1313 {
1314 if index > 0 {
1315 out.write_char(',')?;
1316 }
1317 match kind {
1318 EntityKind::Publisher => write_publisher_json(out, entity)?,
1319 EntityKind::Subscription => write_subscriber_json(out, entity)?,
1320 EntityKind::Timer => write_timer_json(out, entity)?,
1321 EntityKind::ServiceServer => write_service_json(out, entity)?,
1322 EntityKind::ActionServer => write_action_json(out, entity)?,
1323 EntityKind::ActionClient | EntityKind::ServiceClient => {
1327 write_client_json(out, entity)?
1328 }
1329 _ => {}
1330 }
1331 }
1332 write!(out, "]")
1333 }
1334
1335 #[cfg(feature = "alloc")]
1336 fn write_callbacks_json(&self, out: &mut impl core::fmt::Write) -> core::fmt::Result {
1337 let callbacks = self.source_callbacks();
1338 write!(out, "\"callbacks\":[")?;
1339 for (index, callback) in callbacks.iter().enumerate() {
1340 if index > 0 {
1341 out.write_char(',')?;
1342 }
1343 write!(out, "{{")?;
1344 write_json_field(out, "id", callback.id.as_str())?;
1345 out.write_char(',')?;
1346 if let Some(slot) = callback.slot {
1347 write!(out, "\"declaration_slot\":{},", slot.index())?;
1348 }
1349 write_json_field(out, "kind", callback.kind)?;
1350 out.write_char(',')?;
1351 if let Some(group) = callback.group.as_ref() {
1352 write_json_field(out, "group", group)?;
1353 out.write_char(',')?;
1354 } else {
1355 write!(out, "\"group\":null,")?;
1356 }
1357 write!(out, "\"effects\":[")?;
1358 for (effect_index, effect) in self
1359 .callback_effects
1360 .iter()
1361 .filter(|effect| effect.callback_id.as_str() == callback.id)
1362 .enumerate()
1363 {
1364 if effect_index > 0 {
1365 out.write_char(',')?;
1366 }
1367 write!(out, "{{")?;
1368 write_json_field(out, "kind", effect_json_kind(effect.kind))?;
1369 out.write_char(',')?;
1370 write_json_field(out, "entity", effect.entity_id.as_str())?;
1371 if let Some(entity_slot) = effect.entity_slot {
1372 write!(out, ",\"entity_slot\":{}", entity_slot.index())?;
1373 }
1374 write!(out, "}}")?;
1375 }
1376 write!(out, "],")?;
1377 write_source_location(out, &callback.source)?;
1378 write!(out, "}}")?;
1379 }
1380 write!(out, "]")
1381 }
1382
1383 #[cfg(feature = "alloc")]
1384 fn write_parameters_json(&self, out: &mut impl core::fmt::Write) -> core::fmt::Result {
1385 write!(out, "\"parameters\":[")?;
1386 for (index, entity) in self
1387 .entities
1388 .iter()
1389 .filter(|entity| entity.kind == EntityKind::Parameter)
1390 .enumerate()
1391 {
1392 if index > 0 {
1393 out.write_char(',')?;
1394 }
1395 write!(out, "{{")?;
1396 write_json_field(out, "node", entity.node_id.as_str())?;
1397 out.write_char(',')?;
1398 if let Some(slot) = entity.slot {
1399 write!(out, "\"declaration_slot\":{},", slot.index())?;
1400 }
1401 write_json_field(out, "name", entity.source_name.as_str())?;
1402 out.write_char(',')?;
1403 let parameter_type = entity.parameter_type.unwrap_or_else(|| {
1408 entity
1409 .parameter_default
1410 .as_ref()
1411 .map(ParameterDefault::parameter_type)
1412 .unwrap_or(ParameterType::NotSet)
1413 });
1414 write_json_field(out, "type", parameter_type_json(parameter_type))?;
1415 out.write_char(',')?;
1416 write!(out, "\"default\":")?;
1417 write_parameter_default(out, entity.parameter_default.as_ref())?;
1418 out.write_char(',')?;
1419 write!(out, "\"read_only\":{},", entity.parameter_read_only)?;
1420 if entity.parameter_read {
1421 write!(out, "\"read\":true,")?;
1422 }
1423 write_source_location(out, &entity.source)?;
1424 write!(out, "}}")?;
1425 }
1426 write!(out, "]")
1427 }
1428
1429 #[cfg(feature = "alloc")]
1430 fn write_trace_json(
1431 &self,
1432 export: &SourceMetadataExport<'_>,
1433 out: &mut impl core::fmt::Write,
1434 ) -> core::fmt::Result {
1435 write!(out, "\"trace\":{{")?;
1436 write_json_field(out, "generator", "nros-metadata-rust")?;
1437 out.write_char(',')?;
1438 write_json_field(out, "package_manifest", export.package_manifest)?;
1439 out.write_char(',')?;
1440 write!(out, "\"source_artifacts\":[")?;
1441 for (index, artifact) in export.source_artifacts.iter().enumerate() {
1442 if index > 0 {
1443 out.write_char(',')?;
1444 }
1445 write_json_string(out, artifact)?;
1446 }
1447 write!(out, "]}}")
1448 }
1449
1450 #[cfg(feature = "alloc")]
1451 fn source_callbacks(&self) -> StdVec<SourceCallbackRef> {
1452 let mut callbacks = StdVec::new();
1453 for entity in &self.entities {
1454 let Some(callback_id) = entity.callback_id.as_ref() else {
1455 continue;
1456 };
1457 let kind = match entity.kind {
1458 EntityKind::Subscription => "subscription",
1459 EntityKind::Timer if entity.timer_kind == TimerKind::GuardCondition => {
1460 "guard_condition"
1461 }
1462 EntityKind::Timer => "timer",
1463 EntityKind::ServiceServer => "service",
1464 EntityKind::ActionServer => "action_goal",
1465 _ => continue,
1466 };
1467 if !callbacks
1468 .iter()
1469 .any(|callback: &SourceCallbackRef| callback.id == callback_id.as_str())
1470 {
1471 callbacks.push(SourceCallbackRef {
1472 id: callback_id.as_str().into(),
1473 slot: entity.callback_slot,
1474 kind,
1475 source: entity.callback_source.clone(),
1476 group: entity
1477 .callback_group
1478 .as_ref()
1479 .map(|group| group.as_str().into()),
1480 });
1481 }
1482 if entity.kind == EntityKind::ActionServer {
1483 if let Some(cancel_id) = entity.action_cancel_callback_id.as_ref()
1484 && !callbacks
1485 .iter()
1486 .any(|callback: &SourceCallbackRef| callback.id == cancel_id.as_str())
1487 {
1488 callbacks.push(SourceCallbackRef {
1489 id: cancel_id.as_str().into(),
1490 slot: entity.action_cancel_callback_slot,
1491 kind: "action_cancel",
1492 source: entity.action_cancel_source.clone(),
1493 group: entity
1494 .callback_group
1495 .as_ref()
1496 .map(|group| group.as_str().into()),
1497 });
1498 }
1499 if let Some(accepted_id) = entity.action_accepted_callback_id.as_ref()
1500 && !callbacks
1501 .iter()
1502 .any(|callback: &SourceCallbackRef| callback.id == accepted_id.as_str())
1503 {
1504 callbacks.push(SourceCallbackRef {
1505 id: accepted_id.as_str().into(),
1506 slot: entity.action_accepted_callback_slot,
1507 kind: "action_accepted",
1508 source: entity.action_accepted_source.clone(),
1509 group: entity
1510 .callback_group
1511 .as_ref()
1512 .map(|group| group.as_str().into()),
1513 });
1514 }
1515 }
1516 }
1517 callbacks
1518 }
1519}
1520
1521#[cfg(feature = "alloc")]
1522struct SourceCallbackRef {
1523 id: StdString,
1524 slot: Option<CallbackSlot>,
1525 kind: &'static str,
1526 source: SourceLocationMetadata,
1527 group: Option<StdString>,
1528}
1529
1530pub(crate) fn entity_callback_ids(entity: &EntityMetadata) -> [Option<&MetadataString>; 3] {
1531 [
1532 entity.callback_id.as_ref(),
1533 entity.action_cancel_callback_id.as_ref(),
1534 entity.action_accepted_callback_id.as_ref(),
1535 ]
1536}
1537
1538pub struct EntityMetadataSpec<'a> {
1546 pub id: EntityId<'a>,
1547 pub node_id: NodeId<'a>,
1548 pub kind: EntityKind,
1549 pub source_name: &'a str,
1550 pub type_name: &'static str,
1551 pub type_hash: &'static str,
1552 pub qos: QoSProfile,
1553}
1554
1555pub fn entity_metadata(spec: EntityMetadataSpec<'_>) -> Result<EntityMetadata, NodeMetadataError> {
1558 let EntityMetadataSpec {
1559 id,
1560 node_id,
1561 kind,
1562 source_name,
1563 type_name,
1564 type_hash,
1565 qos,
1566 } = spec;
1567 Ok(EntityMetadata {
1568 slot: None,
1569 id: copy_str(id.as_str())?,
1570 node_slot: None,
1571 node_id: copy_str(node_id.as_str())?,
1572 kind,
1573 source_name: copy_str(source_name)?,
1574 source_name_kind: SourceNameKind::from_source_name(source_name),
1575 type_name,
1576 type_hash,
1577 action_hashes: None,
1578 qos,
1579 callback_slot: None,
1580 callback_id: None,
1581 callback_source: SourceLocationMetadata::empty(),
1582 callback_group: None,
1583 action_cancel_callback_slot: None,
1584 action_cancel_callback_id: None,
1585 action_cancel_source: SourceLocationMetadata::empty(),
1586 action_accepted_callback_slot: None,
1587 action_accepted_callback_id: None,
1588 action_accepted_source: SourceLocationMetadata::empty(),
1589 period_ms: None,
1590 period_us: None,
1591 timer_clock: TimerClockSource::Steady,
1592 timer_autostart: true,
1593 timer_kind: TimerKind::Wall,
1594 parameter_type: None,
1595 parameter_default: None,
1596 parameter_read_only: false,
1597 parameter_read: false,
1598 safety: false,
1599 message_info: false,
1600 in_place_capable: None,
1603 buffered_row: None,
1604 rx_bound: None,
1605 source: SourceLocationMetadata::empty(),
1606 })
1607}
1608
1609#[cfg(feature = "alloc")]
1610fn write_publisher_json(
1611 out: &mut impl core::fmt::Write,
1612 entity: &EntityMetadata,
1613) -> core::fmt::Result {
1614 write!(out, "{{")?;
1615 write_json_field(out, "id", entity.id.as_str())?;
1616 out.write_char(',')?;
1617 if let Some(slot) = entity.slot {
1618 write!(out, "\"declaration_slot\":{},", slot.index())?;
1619 }
1620 write!(out, "\"unresolved_topic\":")?;
1621 write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1622 out.write_char(',')?;
1623 write_interface(out, entity.type_name, "message")?;
1624 out.write_char(',')?;
1625 write_qos(out, entity.qos)?;
1626 write!(out, "}}")
1627}
1628
1629#[cfg(feature = "alloc")]
1630fn write_subscriber_json(
1631 out: &mut impl core::fmt::Write,
1632 entity: &EntityMetadata,
1633) -> core::fmt::Result {
1634 write!(out, "{{")?;
1635 write_json_field(out, "id", entity.id.as_str())?;
1636 out.write_char(',')?;
1637 if let Some(slot) = entity.slot {
1638 write!(out, "\"declaration_slot\":{},", slot.index())?;
1639 }
1640 write!(out, "\"unresolved_topic\":")?;
1641 write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1642 out.write_char(',')?;
1643 write_interface(out, entity.type_name, "message")?;
1644 out.write_char(',')?;
1645 write_qos(out, entity.qos)?;
1646 out.write_char(',')?;
1647 write_json_field(
1648 out,
1649 "callback",
1650 entity
1651 .callback_id
1652 .as_ref()
1653 .map(|id| id.as_str())
1654 .unwrap_or(""),
1655 )?;
1656 if let Some(callback_slot) = entity.callback_slot {
1657 write!(out, ",\"callback_slot\":{}", callback_slot.index())?;
1658 }
1659 if let Some(in_place) = entity.in_place_capable {
1664 write!(out, ",\"in_place\":{in_place}")?;
1665 }
1666 if let Some(row) = entity.buffered_row {
1669 write!(out, ",\"buffered\":\"{}\"", row.as_str())?;
1670 }
1671 write!(out, "}}")
1672}
1673
1674#[cfg(feature = "alloc")]
1675fn write_timer_json(out: &mut impl core::fmt::Write, entity: &EntityMetadata) -> core::fmt::Result {
1676 write!(out, "{{")?;
1677 write_json_field(out, "id", entity.id.as_str())?;
1678 out.write_char(',')?;
1679 if let Some(slot) = entity.slot {
1680 write!(out, "\"declaration_slot\":{},", slot.index())?;
1681 }
1682 write_json_field(out, "kind", timer_kind_json(entity.timer_kind))?;
1686 out.write_char(',')?;
1687 write!(out, "\"period_ms\":{},", entity.period_ms.unwrap_or(0))?;
1688 write!(out, "\"period_us\":{},", entity.period_us.unwrap_or(0))?;
1689 write_json_field(
1690 out,
1691 "callback",
1692 entity
1693 .callback_id
1694 .as_ref()
1695 .map(|id| id.as_str())
1696 .unwrap_or(""),
1697 )?;
1698 if let Some(callback_slot) = entity.callback_slot {
1699 write!(out, ",\"callback_slot\":{}", callback_slot.index())?;
1700 }
1701 write!(out, "}}")
1702}
1703
1704#[cfg(feature = "alloc")]
1705fn write_service_json(
1706 out: &mut impl core::fmt::Write,
1707 entity: &EntityMetadata,
1708) -> core::fmt::Result {
1709 write!(out, "{{")?;
1710 write_json_field(out, "id", entity.id.as_str())?;
1711 out.write_char(',')?;
1712 if let Some(slot) = entity.slot {
1713 write!(out, "\"declaration_slot\":{},", slot.index())?;
1714 }
1715 write!(out, "\"unresolved_name\":")?;
1716 write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1717 out.write_char(',')?;
1718 write_interface(out, entity.type_name, "service")?;
1719 out.write_char(',')?;
1720 write_qos(out, entity.qos)?;
1722 out.write_char(',')?;
1723 write_json_field(
1724 out,
1725 "callback",
1726 entity
1727 .callback_id
1728 .as_ref()
1729 .map(|id| id.as_str())
1730 .unwrap_or(""),
1731 )?;
1732 if let Some(callback_slot) = entity.callback_slot {
1733 write!(out, ",\"callback_slot\":{}", callback_slot.index())?;
1734 }
1735 write!(out, "}}")
1736}
1737
1738#[cfg(feature = "alloc")]
1745fn write_client_json(
1746 out: &mut impl core::fmt::Write,
1747 entity: &EntityMetadata,
1748) -> core::fmt::Result {
1749 let interface_kind = if entity.kind == EntityKind::ActionClient {
1750 "action"
1751 } else {
1752 "service"
1753 };
1754 write!(out, "{{")?;
1755 write_json_field(out, "id", entity.id.as_str())?;
1756 out.write_char(',')?;
1757 if let Some(slot) = entity.slot {
1758 write!(out, "\"declaration_slot\":{},", slot.index())?;
1759 }
1760 write!(out, "\"unresolved_name\":")?;
1761 write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1762 out.write_char(',')?;
1763 write_interface(out, entity.type_name, interface_kind)?;
1764 out.write_char(',')?;
1765 write_qos(out, entity.qos)?;
1767 write!(out, "}}")
1768}
1769
1770#[cfg(feature = "alloc")]
1771fn write_action_json(
1772 out: &mut impl core::fmt::Write,
1773 entity: &EntityMetadata,
1774) -> core::fmt::Result {
1775 let goal_callback = entity
1776 .callback_id
1777 .as_ref()
1778 .map(|id| id.as_str())
1779 .unwrap_or("");
1780 let cancel_callback = entity
1781 .action_cancel_callback_id
1782 .as_ref()
1783 .map(|id| id.as_str())
1784 .unwrap_or(goal_callback);
1785 let accepted_callback = entity
1786 .action_accepted_callback_id
1787 .as_ref()
1788 .map(|id| id.as_str())
1789 .unwrap_or(goal_callback);
1790 write!(out, "{{")?;
1791 write_json_field(out, "id", entity.id.as_str())?;
1792 out.write_char(',')?;
1793 if let Some(slot) = entity.slot {
1794 write!(out, "\"declaration_slot\":{},", slot.index())?;
1795 }
1796 write!(out, "\"unresolved_name\":")?;
1797 write_source_name(out, entity.source_name.as_str(), entity.source_name_kind)?;
1798 out.write_char(',')?;
1799 write_interface(out, entity.type_name, "action")?;
1800 out.write_char(',')?;
1801 write_qos(out, entity.qos)?;
1803 out.write_char(',')?;
1804 write_json_field(out, "goal_callback", goal_callback)?;
1805 if let Some(callback_slot) = entity.callback_slot {
1806 write!(out, ",\"goal_callback_slot\":{}", callback_slot.index())?;
1807 }
1808 out.write_char(',')?;
1809 write_json_field(out, "cancel_callback", cancel_callback)?;
1810 if let Some(callback_slot) = entity.action_cancel_callback_slot {
1811 write!(out, ",\"cancel_callback_slot\":{}", callback_slot.index())?;
1812 }
1813 out.write_char(',')?;
1814 write_json_field(out, "accepted_callback", accepted_callback)?;
1815 if let Some(callback_slot) = entity.action_accepted_callback_slot {
1816 write!(out, ",\"accepted_callback_slot\":{}", callback_slot.index())?;
1817 }
1818 write!(out, "}}")
1819}
1820
1821#[cfg(feature = "alloc")]
1822fn write_source_name(
1823 out: &mut impl core::fmt::Write,
1824 value: &str,
1825 kind: SourceNameKind,
1826) -> core::fmt::Result {
1827 write!(out, "{{")?;
1828 write_json_field(out, "value", value)?;
1829 out.write_char(',')?;
1830 write_json_field(out, "kind", source_name_kind_json(kind))?;
1831 write!(out, "}}")
1832}
1833
1834#[cfg(feature = "alloc")]
1835fn write_interface(
1836 out: &mut impl core::fmt::Write,
1837 type_name: &str,
1838 fallback_kind: &'static str,
1839) -> core::fmt::Result {
1840 let interface = parse_interface(type_name, fallback_kind);
1841 write!(out, "\"interface\":{{")?;
1842 write_json_field(out, "package", &interface.package)?;
1843 out.write_char(',')?;
1844 write_json_field(out, "name", &interface.name)?;
1845 out.write_char(',')?;
1846 write_json_field(out, "kind", interface.kind)?;
1847 write!(out, "}}")
1848}
1849
1850#[cfg(feature = "alloc")]
1851fn write_qos(out: &mut impl core::fmt::Write, qos: QoSProfile) -> core::fmt::Result {
1852 write!(out, "\"qos\":{{")?;
1853 write_json_field(out, "reliability", reliability_json(qos.reliability))?;
1854 out.write_char(',')?;
1855 write_json_field(out, "durability", durability_json(qos.durability))?;
1856 out.write_char(',')?;
1857 write_json_field(out, "history", history_json(qos.history))?;
1858 out.write_char(',')?;
1859 write!(out, "\"depth\":{},", qos.depth)?;
1860 write_optional_ms(out, "deadline_ms", qos.deadline_ms)?;
1861 out.write_char(',')?;
1862 write_optional_ms(out, "lifespan_ms", qos.lifespan_ms)?;
1863 out.write_char(',')?;
1864 write_json_field(out, "liveliness", liveliness_json(qos.liveliness_kind))?;
1865 out.write_char(',')?;
1866 write_optional_ms(out, "liveliness_lease_duration_ms", qos.liveliness_lease_ms)?;
1867 write!(out, ",\"extensions\":{{}}}}")
1868}
1869
1870#[cfg(feature = "alloc")]
1871fn write_source_location(
1872 out: &mut impl core::fmt::Write,
1873 source: &SourceLocationMetadata,
1874) -> core::fmt::Result {
1875 write!(out, "\"source\":{{")?;
1876 write_json_field(out, "artifact", source.artifact.as_str())?;
1877 out.write_char(',')?;
1878 write!(out, "\"line\":")?;
1879 write_optional_u32(out, source.line)?;
1880 out.write_char(',')?;
1881 write!(out, "\"column\":")?;
1882 write_optional_u32(out, source.column)?;
1883 write!(out, "}}")
1884}
1885
1886#[cfg(feature = "alloc")]
1887fn write_parameter_default(
1888 out: &mut impl core::fmt::Write,
1889 default: Option<&ParameterDefault>,
1890) -> core::fmt::Result {
1891 match default {
1892 Some(ParameterDefault::Bool(value)) => write!(out, "{}", value),
1893 Some(ParameterDefault::Integer(value)) => write!(out, "{}", value),
1894 Some(ParameterDefault::Double(value)) => {
1899 let text = value.as_str();
1900 if text.parse::<f64>().is_ok_and(f64::is_finite) {
1901 write!(out, "{}", text)
1902 } else {
1903 write_json_string(out, text)
1904 }
1905 }
1906 Some(ParameterDefault::String(value)) => write_json_string(out, value.as_str()),
1907 Some(ParameterDefault::BoolArray)
1908 | Some(ParameterDefault::IntegerArray)
1909 | Some(ParameterDefault::DoubleArray)
1910 | Some(ParameterDefault::StringArray)
1911 | None => write!(out, "[]"),
1912 }
1913}
1914
1915#[cfg(feature = "alloc")]
1916fn write_json_field(out: &mut impl core::fmt::Write, name: &str, value: &str) -> core::fmt::Result {
1917 write_json_string(out, name)?;
1918 out.write_char(':')?;
1919 write_json_string(out, value)
1920}
1921
1922#[cfg(feature = "alloc")]
1923fn write_json_opt_field(
1924 out: &mut impl core::fmt::Write,
1925 name: &str,
1926 value: Option<&str>,
1927) -> core::fmt::Result {
1928 write_json_string(out, name)?;
1929 out.write_char(':')?;
1930 if let Some(value) = value {
1931 write_json_string(out, value)
1932 } else {
1933 write!(out, "null")
1934 }
1935}
1936
1937#[cfg(feature = "alloc")]
1938fn write_json_string(out: &mut impl core::fmt::Write, value: &str) -> core::fmt::Result {
1939 out.write_char('"')?;
1940 for ch in value.chars() {
1941 match ch {
1942 '"' => write!(out, "\\\"")?,
1943 '\\' => write!(out, "\\\\")?,
1944 '\n' => write!(out, "\\n")?,
1945 '\r' => write!(out, "\\r")?,
1946 '\t' => write!(out, "\\t")?,
1947 ch if ch.is_control() => write!(out, "\\u{:04x}", ch as u32)?,
1948 ch => out.write_char(ch)?,
1949 }
1950 }
1951 out.write_char('"')
1952}
1953
1954#[cfg(feature = "alloc")]
1955fn write_optional_ms(out: &mut impl core::fmt::Write, name: &str, value: u32) -> core::fmt::Result {
1956 write_json_string(out, name)?;
1957 out.write_char(':')?;
1958 if value == 0 {
1959 write!(out, "null")
1960 } else {
1961 write!(out, "{}", value)
1962 }
1963}
1964
1965#[cfg(feature = "alloc")]
1966fn write_optional_u32(out: &mut impl core::fmt::Write, value: Option<u32>) -> core::fmt::Result {
1967 if let Some(value) = value {
1968 write!(out, "{}", value)
1969 } else {
1970 write!(out, "null")
1971 }
1972}
1973
1974#[cfg(feature = "alloc")]
1975fn source_name_kind_json(kind: SourceNameKind) -> &'static str {
1976 match kind {
1977 SourceNameKind::Absolute => "absolute",
1978 SourceNameKind::Relative => "relative",
1979 SourceNameKind::Private => "private",
1980 }
1981}
1982
1983#[cfg(feature = "alloc")]
1984fn timer_kind_json(kind: TimerKind) -> &'static str {
1985 match kind {
1986 TimerKind::Wall => "wall",
1987 TimerKind::Clock => "clock",
1988 TimerKind::Oneshot => "oneshot",
1989 TimerKind::InGroup => "in_group",
1990 TimerKind::GuardCondition => "guard_condition",
1991 }
1992}
1993
1994#[cfg(feature = "alloc")]
1998fn parameter_type_json(value: ParameterType) -> &'static str {
1999 match value {
2000 ParameterType::NotSet => "not_set",
2001 ParameterType::Bool => "bool",
2002 ParameterType::Integer => "integer",
2003 ParameterType::Double => "double",
2004 ParameterType::String => "string",
2005 ParameterType::ByteArray => "byte_array",
2006 ParameterType::BoolArray => "bool_array",
2007 ParameterType::IntegerArray => "integer_array",
2008 ParameterType::DoubleArray => "double_array",
2009 ParameterType::StringArray => "string_array",
2010 }
2011}
2012
2013#[cfg(feature = "alloc")]
2014fn effect_json_kind(kind: CallbackEffectKind) -> &'static str {
2015 match kind {
2016 CallbackEffectKind::Publishes => "publishes",
2017 CallbackEffectKind::Reads => "reads_parameter",
2018 CallbackEffectKind::Writes => "writes_parameter",
2019 }
2020}
2021
2022#[cfg(feature = "alloc")]
2029fn reliability_json(value: QoSReliabilityPolicy) -> &'static str {
2030 match value {
2031 QoSReliabilityPolicy::SystemDefault => "system_default",
2032 QoSReliabilityPolicy::Reliable => "reliable",
2033 QoSReliabilityPolicy::BestEffort => "best_effort",
2034 QoSReliabilityPolicy::Unknown => "unknown",
2039 QoSReliabilityPolicy::BestAvailable => "best_available",
2043 }
2044}
2045
2046#[cfg(feature = "alloc")]
2047fn durability_json(value: QoSDurabilityPolicy) -> &'static str {
2048 match value {
2049 QoSDurabilityPolicy::SystemDefault => "system_default",
2050 QoSDurabilityPolicy::Volatile => "volatile",
2051 QoSDurabilityPolicy::TransientLocal => "transient_local",
2052 QoSDurabilityPolicy::Unknown => "unknown",
2054 QoSDurabilityPolicy::BestAvailable => "best_available",
2055 }
2056}
2057
2058#[cfg(feature = "alloc")]
2059fn history_json(value: QoSHistoryPolicy) -> &'static str {
2060 match value {
2061 QoSHistoryPolicy::SystemDefault => "system_default",
2062 QoSHistoryPolicy::KeepLast => "keep_last",
2063 QoSHistoryPolicy::KeepAll => "keep_all",
2064 QoSHistoryPolicy::Unknown => "unknown",
2066 }
2067}
2068
2069#[cfg(feature = "alloc")]
2070fn liveliness_json(value: QoSLivelinessPolicy) -> &'static str {
2071 match value {
2072 QoSLivelinessPolicy::None => "system_default",
2073 QoSLivelinessPolicy::Automatic => "automatic",
2074 QoSLivelinessPolicy::ManualByTopic => "manual_by_topic",
2075 QoSLivelinessPolicy::ManualByNode => "manual_by_node",
2076 QoSLivelinessPolicy::Unknown => "unknown",
2078 QoSLivelinessPolicy::BestAvailable => "best_available",
2079 }
2080}
2081
2082#[cfg(feature = "alloc")]
2083struct ParsedInterface {
2084 package: StdString,
2085 name: StdString,
2086 kind: &'static str,
2087}
2088
2089#[cfg(feature = "alloc")]
2090fn parse_interface(type_name: &str, fallback_kind: &'static str) -> ParsedInterface {
2091 let parts: StdVec<&str> = type_name.split("::").collect();
2092 if parts.len() >= 4 {
2093 let package = parts[0].into();
2094 let kind = match parts[1] {
2095 "msg" => "message",
2096 "srv" => "service",
2097 "action" => "action",
2098 _ => fallback_kind,
2099 };
2100 let mut type_leaf = parts[3].trim_end_matches('_');
2101 if type_leaf.is_empty() {
2102 type_leaf = parts.last().copied().unwrap_or("");
2103 }
2104 return ParsedInterface {
2105 package,
2106 name: format!("{}/{}", parts[1], type_leaf),
2107 kind,
2108 };
2109 }
2110
2111 ParsedInterface {
2112 package: StdString::new(),
2113 name: type_name.into(),
2114 kind: fallback_kind,
2115 }
2116}
2117
2118#[cfg(test)]
2119mod tests {
2120 #[cfg(feature = "alloc")]
2126 #[test]
2127 fn the_declaration_watch_is_stated_only_when_armed_and_stays_broken() {
2128 let export = super::SourceMetadataExport::new("p", "c");
2129 let mut r: super::MetadataRecorder = super::MetadataRecorder::new();
2130 r.break_parameter_declarations();
2131 assert_eq!(r.parameter_declarations_watched(), None);
2132 let json = r.to_source_metadata_json(&export).unwrap();
2133 assert!(!json.contains("parameter_declarations_watched"), "{json}");
2134
2135 r.arm_parameter_declarations();
2136 let json = r.to_source_metadata_json(&export).unwrap();
2137 assert!(
2138 json.contains("\"parameter_declarations_watched\":true,"),
2139 "{json}"
2140 );
2141
2142 r.break_parameter_declarations();
2143 r.arm_parameter_declarations();
2144 assert_eq!(r.parameter_declarations_watched(), Some(false));
2145 let json = r.to_source_metadata_json(&export).unwrap();
2146 assert!(
2147 json.contains("\"parameter_declarations_watched\":false,"),
2148 "{json}"
2149 );
2150 }
2151
2152 #[test]
2159 fn a_path_longer_than_the_buffer_keeps_its_tail() {
2160 let deep = concat!(
2163 "/deep/nested/nested/nested/nested/nested/nested/nested/nested/",
2164 "nested/nested/nested/nested/nested/nested/nested/nested/nested/",
2165 "ws/build/nros-metadata/metadata-probe/listener/src/lib.rs"
2166 );
2167 assert!(deep.len() > super::METADATA_STRING_CAPACITY);
2168
2169 let got = super::copy_str_keep_tail(deep).expect("must not error on depth");
2170 assert!(got.len() <= super::METADATA_STRING_CAPACITY);
2171 assert!(
2172 got.ends_with("src/lib.rs"),
2173 "the informative tail must survive, got {got:?}"
2174 );
2175 assert!(got.starts_with('…'), "a cut must be visible, got {got:?}");
2176
2177 let short = "src/lib.rs";
2179 assert_eq!(super::copy_str_keep_tail(short).unwrap().as_str(), short);
2180 }
2181
2182 use super::*;
2183 use crate::qos;
2184
2185 #[cfg(feature = "alloc")]
2189 #[test]
2190 fn a_non_finite_double_default_is_valid_json() {
2191 let mut out = StdString::new();
2192 for (value, want) in [
2193 (f64::INFINITY, "\"inf\""),
2194 (f64::NEG_INFINITY, "\"-inf\""),
2195 (f64::NAN, "\"NaN\""),
2196 (1.5, "1.5"),
2197 ] {
2198 out.clear();
2199 let default = ParameterDefault::from_value(&ParameterValue::Double(value)).unwrap();
2200 write_parameter_default(&mut out, Some(&default)).unwrap();
2201 assert_eq!(out, want);
2202 }
2203 }
2204
2205 #[test]
2206 fn source_name_kind_preserves_unresolved_names() {
2207 assert_eq!(
2208 SourceNameKind::from_source_name("/scan"),
2209 SourceNameKind::Absolute
2210 );
2211 assert_eq!(
2212 SourceNameKind::from_source_name("~/scan"),
2213 SourceNameKind::Private
2214 );
2215 assert_eq!(
2216 SourceNameKind::from_source_name("scan"),
2217 SourceNameKind::Relative
2218 );
2219 }
2220
2221 #[test]
2225 fn expand_name_covers_each_source_name_kind() {
2226 assert_eq!(
2228 expand_name("/scan", "lidar", "/sensing").unwrap().as_str(),
2229 "/scan"
2230 );
2231 assert_eq!(
2233 expand_name("~/scan", "lidar", "/sensing").unwrap().as_str(),
2234 "/sensing/lidar/scan"
2235 );
2236 assert_eq!(
2237 expand_name("~/scan", "lidar", "/").unwrap().as_str(),
2238 "/lidar/scan"
2239 );
2240 assert_eq!(
2242 expand_name("scan", "lidar", "/sensing").unwrap().as_str(),
2243 "/sensing/scan"
2244 );
2245 assert_eq!(expand_name("scan", "lidar", "/").unwrap().as_str(), "/scan");
2246 }
2247
2248 #[test]
2249 fn resolve_name_substitutes_first_matching_rule() {
2250 let remaps = [
2251 ("~/scan", "/points_raw"),
2252 ("/sensing/lidar/scan", "/ignored"),
2253 ];
2254 assert_eq!(
2255 resolve_name("~/scan", "lidar", "/sensing", remaps)
2256 .unwrap()
2257 .as_str(),
2258 "/points_raw"
2259 );
2260 assert_eq!(
2262 resolve_name("other", "lidar", "/sensing", [("/x", "/y")])
2263 .unwrap()
2264 .as_str(),
2265 "/sensing/other"
2266 );
2267 }
2268
2269 #[test]
2270 fn recorder_rejects_duplicate_stable_ids() {
2271 let mut recorder = MetadataRecorder::<1, 2, 1>::new();
2272 recorder
2273 .push_node(NodeId::new("node"), "talker", "/", 0)
2274 .unwrap();
2275
2276 let first = entity_metadata(EntityMetadataSpec {
2277 id: EntityId::new("pub"),
2278 node_id: NodeId::new("node"),
2279 kind: EntityKind::Publisher,
2280 source_name: "chatter",
2281 type_name: "std_msgs::msg::dds_::String_",
2282 type_hash: "hash",
2283 qos: qos::DEFAULT,
2284 })
2285 .unwrap();
2286 recorder.push_entity(first.clone()).unwrap();
2287
2288 assert_eq!(
2289 recorder.push_entity(first),
2290 Err(NodeMetadataError::DuplicateId)
2291 );
2292 }
2293
2294 #[test]
2295 fn recorder_rejects_duplicate_nodes_and_unknown_node_entities() {
2296 let mut recorder = MetadataRecorder::<1, 1, 1>::new();
2297 recorder
2298 .push_node(NodeId::new("node"), "talker", "/", 0)
2299 .unwrap();
2300
2301 assert_eq!(
2302 recorder.push_node(NodeId::new("node"), "other", "/", 0),
2303 Err(NodeMetadataError::DuplicateId)
2304 );
2305
2306 let entity = entity_metadata(EntityMetadataSpec {
2307 id: EntityId::new("pub"),
2308 node_id: NodeId::new("missing_node"),
2309 kind: EntityKind::Publisher,
2310 source_name: "chatter",
2311 type_name: "std_msgs::msg::dds_::String_",
2312 type_hash: "hash",
2313 qos: qos::DEFAULT,
2314 })
2315 .unwrap();
2316
2317 assert_eq!(
2318 recorder.push_entity(entity),
2319 Err(NodeMetadataError::UnknownNode)
2320 );
2321 }
2322
2323 #[test]
2324 fn recorder_assigns_slots_and_source_default_names_by_declaration_order() {
2325 let mut recorder = MetadataRecorder::<2, 4, 3>::new();
2326 recorder
2327 .push_node(NodeId::new("node_alpha"), "talker", "/", 0)
2328 .unwrap();
2329 recorder
2330 .push_node(NodeId::new("node_beta"), "listener", "/demo", 42)
2331 .unwrap();
2332
2333 assert_eq!(recorder.nodes()[0].slot, NodeSlot::new(0));
2334 assert_eq!(recorder.nodes()[0].source_default_name.as_str(), "talker");
2335 assert_eq!(recorder.nodes()[1].slot, NodeSlot::new(1));
2336 assert_eq!(recorder.nodes()[1].source_default_name.as_str(), "listener");
2337
2338 recorder
2339 .push_entity(
2340 entity_metadata(EntityMetadataSpec {
2341 id: EntityId::new("pub_chatter"),
2342 node_id: NodeId::new("node_alpha"),
2343 kind: EntityKind::Publisher,
2344 source_name: "/chatter",
2345 type_name: "std_msgs::msg::dds_::String_",
2346 type_hash: "hash",
2347 qos: qos::DEFAULT,
2348 })
2349 .unwrap(),
2350 )
2351 .unwrap();
2352 let mut subscription = entity_metadata(EntityMetadataSpec {
2353 id: EntityId::new("sub_chatter"),
2354 node_id: NodeId::new("node_beta"),
2355 kind: EntityKind::Subscription,
2356 source_name: "/chatter",
2357 type_name: "std_msgs::msg::dds_::String_",
2358 type_hash: "hash",
2359 qos: qos::DEFAULT,
2360 })
2361 .unwrap();
2362 subscription.callback_id = Some(copy_str("on_message").unwrap());
2363 recorder.push_entity(subscription).unwrap();
2364 let mut timer = entity_metadata(EntityMetadataSpec {
2365 id: EntityId::new("timer_tick"),
2366 node_id: NodeId::new("node_alpha"),
2367 kind: EntityKind::Timer,
2368 source_name: "",
2369 type_name: "",
2370 type_hash: "",
2371 qos: qos::DEFAULT,
2372 })
2373 .unwrap();
2374 timer.callback_id = Some(copy_str("on_tick").unwrap());
2375 recorder.push_entity(timer).unwrap();
2376
2377 assert_eq!(recorder.entities()[0].slot, Some(EntitySlot::new(0)));
2378 assert_eq!(recorder.entities()[0].node_slot, Some(NodeSlot::new(0)));
2379 assert_eq!(recorder.entities()[0].callback_slot, None);
2380 assert_eq!(recorder.entities()[1].slot, Some(EntitySlot::new(1)));
2381 assert_eq!(recorder.entities()[1].node_slot, Some(NodeSlot::new(1)));
2382 assert_eq!(
2383 recorder.entities()[1].callback_slot,
2384 Some(CallbackSlot::new(0))
2385 );
2386 assert_eq!(
2387 recorder.entities()[2].callback_slot,
2388 Some(CallbackSlot::new(1))
2389 );
2390
2391 recorder
2392 .push_callback_effect(
2393 CallbackId::new("on_tick"),
2394 CallbackEffectKind::Publishes,
2395 EntityId::new("pub_chatter"),
2396 )
2397 .unwrap();
2398 assert_eq!(
2399 recorder.callback_effects()[0].callback_slot,
2400 Some(CallbackSlot::new(1))
2401 );
2402 assert_eq!(
2403 recorder.callback_effects()[0].entity_slot,
2404 Some(EntitySlot::new(0))
2405 );
2406 }
2407
2408 #[test]
2409 fn recorder_assigns_distinct_callback_slots_within_one_action_entity() {
2410 let mut recorder = MetadataRecorder::<1, 1, 3>::new();
2411 recorder
2412 .push_node(NodeId::new("node"), "action_node", "/", 0)
2413 .unwrap();
2414 let mut action = entity_metadata(EntityMetadataSpec {
2415 id: EntityId::new("act_count"),
2416 node_id: NodeId::new("node"),
2417 kind: EntityKind::ActionServer,
2418 source_name: "/count",
2419 type_name: "example_interfaces::action::dds_::Fibonacci_",
2420 type_hash: "hash",
2421 qos: qos::DEFAULT,
2422 })
2423 .unwrap();
2424 action.callback_id = Some(copy_str("on_goal").unwrap());
2425 action.action_cancel_callback_id = Some(copy_str("on_cancel").unwrap());
2426 action.action_accepted_callback_id = Some(copy_str("on_accepted").unwrap());
2427
2428 recorder.push_entity(action).unwrap();
2429
2430 assert_eq!(
2431 recorder.entities()[0].callback_slot,
2432 Some(CallbackSlot::new(0))
2433 );
2434 assert_eq!(
2435 recorder.entities()[0].action_cancel_callback_slot,
2436 Some(CallbackSlot::new(1))
2437 );
2438 assert_eq!(
2439 recorder.entities()[0].action_accepted_callback_slot,
2440 Some(CallbackSlot::new(2))
2441 );
2442 }
2443
2444 #[cfg(feature = "alloc")]
2445 #[test]
2446 fn source_metadata_json_uses_agent_a_schema_shape() {
2447 let mut recorder = MetadataRecorder::<1, 7, 1>::new();
2451 recorder
2452 .push_node(NodeId::new("node_talker"), "talker", "/", 0)
2453 .unwrap();
2454 recorder
2455 .push_entity(
2456 entity_metadata(EntityMetadataSpec {
2457 id: EntityId::new("pub_chatter"),
2458 node_id: NodeId::new("node_talker"),
2459 kind: EntityKind::Publisher,
2460 source_name: "chatter",
2461 type_name: "std_msgs::msg::dds_::String_",
2462 type_hash: "hash",
2463 qos: crate::qos::DEFAULT,
2464 })
2465 .unwrap(),
2466 )
2467 .unwrap();
2468 let mut timer = entity_metadata(EntityMetadataSpec {
2469 id: EntityId::new("timer_publish"),
2470 node_id: NodeId::new("node_talker"),
2471 kind: EntityKind::Timer,
2472 source_name: "",
2473 type_name: "",
2474 type_hash: "",
2475 qos: crate::qos::DEFAULT,
2476 })
2477 .unwrap();
2478 timer.callback_id = Some(copy_str("cb_timer").unwrap());
2479 timer.callback_source = SourceLocationMetadata {
2480 artifact: copy_str("src/talker.rs").unwrap(),
2481 line: Some(42),
2482 column: Some(5),
2483 };
2484 timer.period_ms = Some(100);
2485 recorder.push_entity(timer).unwrap();
2486 let mut param = entity_metadata(EntityMetadataSpec {
2487 id: EntityId::new("param_rate"),
2488 node_id: NodeId::new("node_talker"),
2489 kind: EntityKind::Parameter,
2490 source_name: "rate_hz",
2491 type_name: "",
2492 type_hash: "",
2493 qos: crate::qos::DEFAULT,
2494 })
2495 .unwrap();
2496 param.parameter_type = Some(ParameterType::Integer);
2497 param.parameter_default = Some(ParameterDefault::Integer(10));
2498 param.source = SourceLocationMetadata {
2499 artifact: copy_str("src/talker.rs").unwrap(),
2500 line: Some(25),
2501 column: Some(9),
2502 };
2503 recorder.push_entity(param).unwrap();
2504 let mut action = entity_metadata(EntityMetadataSpec {
2505 id: EntityId::new("act_count"),
2506 node_id: NodeId::new("node_talker"),
2507 kind: EntityKind::ActionServer,
2508 source_name: "~/count",
2509 type_name: "example_interfaces::action::dds_::Fibonacci_",
2510 type_hash: "hash",
2511 qos: crate::qos::DEFAULT,
2512 })
2513 .unwrap();
2514 action.callback_id = Some(copy_str("cb_count_goal").unwrap());
2515 action.callback_source = SourceLocationMetadata {
2516 artifact: copy_str("src/talker.rs").unwrap(),
2517 line: Some(90),
2518 column: Some(5),
2519 };
2520 action.action_cancel_callback_id = Some(copy_str("cb_count_cancel").unwrap());
2521 action.action_cancel_source = SourceLocationMetadata {
2522 artifact: copy_str("src/talker.rs").unwrap(),
2523 line: Some(96),
2524 column: Some(5),
2525 };
2526 action.action_accepted_callback_id = Some(copy_str("cb_count_accepted").unwrap());
2527 action.action_accepted_source = SourceLocationMetadata {
2528 artifact: copy_str("src/talker.rs").unwrap(),
2529 line: Some(104),
2530 column: Some(5),
2531 };
2532 recorder.push_entity(action).unwrap();
2533 recorder
2534 .push_callback_effect(
2535 CallbackId::new("cb_timer"),
2536 CallbackEffectKind::Publishes,
2537 EntityId::new("pub_chatter"),
2538 )
2539 .unwrap();
2540
2541 recorder
2545 .push_entity(
2546 entity_metadata(EntityMetadataSpec {
2547 id: EntityId::new("client_fib"),
2548 node_id: NodeId::new("node_talker"),
2549 kind: EntityKind::ActionClient,
2550 source_name: "/fibonacci",
2551 type_name: "example_interfaces::action::dds_::Fibonacci_",
2552 type_hash: "hash",
2553 qos: crate::qos::DEFAULT,
2554 })
2555 .unwrap(),
2556 )
2557 .unwrap();
2558 recorder
2559 .push_entity(
2560 entity_metadata(EntityMetadataSpec {
2561 id: EntityId::new("client_add"),
2562 node_id: NodeId::new("node_talker"),
2563 kind: EntityKind::ServiceClient,
2564 source_name: "/add_two_ints",
2565 type_name: "example_interfaces::srv::dds_::AddTwoInts_",
2566 type_hash: "hash",
2567 qos: crate::qos::DEFAULT,
2568 })
2569 .unwrap(),
2570 )
2571 .unwrap();
2572
2573 let json = recorder
2574 .to_source_metadata_json(
2575 &SourceMetadataExport::new("demo_nodes_rs", "talker")
2576 .executable("talker")
2577 .exported_symbol("nros_node_talker")
2578 .source_artifacts(&["src/talker.rs"]),
2579 )
2580 .unwrap();
2581
2582 assert!(
2586 json.contains(&format!("\"version\":{SOURCE_METADATA_SCHEMA_VERSION}")),
2587 "the current schema version, got {json}"
2588 );
2589 assert!(json.contains("\"language\":\"rust\""));
2590 assert!(json.contains("\"unresolved_name\":{\"value\":\"talker\",\"kind\":\"relative\"}"));
2591 assert!(json.contains(
2592 "\"interface\":{\"package\":\"std_msgs\",\"name\":\"msg/String\",\"kind\":\"message\"}"
2593 ));
2594 assert!(json.contains("\"kind\":\"publishes\",\"entity\":\"pub_chatter\""));
2595 assert!(
2596 json.contains("\"source\":{\"artifact\":\"src/talker.rs\",\"line\":42,\"column\":5}")
2597 );
2598 assert!(
2600 json.contains(
2601 "\"name\":\"rate_hz\",\"type\":\"integer\",\"default\":10,\"read_only\":false"
2602 ),
2603 "got {json}"
2604 );
2605 assert!(json.contains("\"goal_callback\":\"cb_count_goal\""));
2606 assert!(json.contains("\"cancel_callback\":\"cb_count_cancel\""));
2607 assert!(json.contains("\"accepted_callback\":\"cb_count_accepted\""));
2608 assert!(json.contains("\"kind\":\"action_cancel\""));
2609 assert!(json.contains("\"kind\":\"action_accepted\""));
2610
2611 assert!(
2622 json.contains("\"action_clients\":[{"),
2623 "an action client must reach the sidecar, got {json}"
2624 );
2625 assert!(
2626 json.contains("\"service_clients\":[{"),
2627 "a service client must reach the sidecar, got {json}"
2628 );
2629 let action_clients = &json[json.find("\"action_clients\":").expect("array present")..];
2636 let action_clients = &action_clients[..action_clients.find(']').unwrap()];
2637 let service_clients = &json[json.find("\"service_clients\":").expect("array present")..];
2638 let service_clients = &service_clients[..service_clients.find(']').unwrap()];
2639
2640 assert!(
2646 action_clients.contains(
2647 "\"interface\":{\"package\":\"example_interfaces\",\"name\":\"action/Fibonacci\",\"kind\":\"action\"}"
2648 ),
2649 "action client interface must be parsed, got {action_clients}"
2650 );
2651 assert!(
2652 service_clients.contains(
2653 "\"interface\":{\"package\":\"example_interfaces\",\"name\":\"srv/AddTwoInts\",\"kind\":\"service\"}"
2654 ),
2655 "service client interface must be parsed, got {service_clients}"
2656 );
2657 assert!(
2660 !action_clients.contains("\"kind\":\"service\"")
2661 && !service_clients.contains("\"kind\":\"action\""),
2662 "the client kind word is what distinguishes the arrays"
2663 );
2664 assert!(
2667 !action_clients.contains("callback") && !service_clients.contains("callback"),
2668 "a client registers no callback; emitting one would misdescribe it"
2669 );
2670 assert!(json.contains("\"generator\":\"nros-metadata-rust\""));
2671 }
2672
2673 #[cfg(feature = "alloc")]
2678 #[test]
2679 fn only_the_node_whose_code_registered_a_machine_is_stated_managed() {
2680 let mut recorder = MetadataRecorder::<2, 1, 1>::new();
2681 recorder
2682 .push_node(NodeId::new("plain"), "talker", "/", 0)
2683 .unwrap();
2684 recorder
2685 .push_node(NodeId::new("coded"), "managed", "/demo", 0)
2686 .unwrap();
2687
2688 let json = recorder
2690 .to_source_metadata_json(&SourceMetadataExport::new("p", "c"))
2691 .unwrap();
2692 assert!(
2693 !json.contains("\"lifecycle\""),
2694 "nothing registered, got {json}"
2695 );
2696
2697 assert!(recorder.observe_lifecycle_registration("managed", "/demo/"));
2700 assert!(
2701 !recorder.observe_lifecycle_registration("ghost", "/"),
2702 "a registration naming no recorded node is refused"
2703 );
2704 assert!(
2705 !recorder.observe_lifecycle_registration("managed", "/"),
2706 "the namespace is part of the key"
2707 );
2708
2709 let json = recorder
2710 .to_source_metadata_json(&SourceMetadataExport::new("p", "c"))
2711 .unwrap();
2712 assert_eq!(json.matches("\"lifecycle\":true").count(), 1, "got {json}");
2713 let coded = json.find("\"id\":\"coded\"").unwrap();
2714 let mark = json.find("\"lifecycle\":true").unwrap();
2715 let plain = json.find("\"id\":\"plain\"").unwrap();
2716 assert!(
2717 plain < coded && coded < mark,
2718 "the mark is on the coded node's row, got {json}"
2719 );
2720 }
2721
2722 #[cfg(feature = "alloc")]
2736 #[test]
2737 fn the_golden_probe_sidecar_is_what_the_recorder_writes() {
2738 extern crate std;
2739
2740 let mut recorder = MetadataRecorder::<2, 12, 2>::new();
2741 recorder
2742 .push_node(NodeId::new("node_planner"), "planner", "/demo", 0)
2743 .unwrap();
2744 recorder
2745 .push_node(NodeId::new("node_plain"), "plain", "/", 0)
2746 .unwrap();
2747 assert!(recorder.observe_lifecycle_registration("planner", "/demo"));
2749
2750 let spec = |id: &'static str, kind, source_name, type_name| EntityMetadataSpec {
2751 id: EntityId::new(id),
2752 node_id: NodeId::new("node_planner"),
2753 kind,
2754 source_name,
2755 type_name,
2756 type_hash: "hash",
2757 qos: crate::qos::DEFAULT,
2758 };
2759 let at = |line| SourceLocationMetadata {
2760 artifact: copy_str("src/planner.cpp").unwrap(),
2761 line: Some(line),
2762 column: Some(5),
2763 };
2764
2765 recorder
2766 .push_entity(
2767 entity_metadata(spec(
2768 "pub_path",
2769 EntityKind::Publisher,
2770 "path",
2771 "nav_msgs::msg::dds_::Path_",
2772 ))
2773 .unwrap(),
2774 )
2775 .unwrap();
2776
2777 let mut sub = entity_metadata(spec(
2780 "sub_odom",
2781 EntityKind::Subscription,
2782 "/odom",
2783 "nav_msgs::msg::dds_::Odometry_",
2784 ))
2785 .unwrap();
2786 sub.callback_id = Some(copy_str("cb_odom").unwrap());
2787 sub.callback_source = at(30);
2788 sub.callback_group = Some(copy_str("sensors").unwrap());
2789 recorder.push_entity(sub).unwrap();
2790 assert!(recorder.observe_subscription_registration(
2791 "/odom",
2792 "nav_msgs::msg::dds_::Odometry_",
2793 true,
2794 BufferedRow::TypedBound,
2795 ));
2796
2797 let mut timer = entity_metadata(spec("timer_plan", EntityKind::Timer, "", "")).unwrap();
2798 timer.callback_id = Some(copy_str("cb_plan").unwrap());
2799 timer.callback_source = at(40);
2800 timer.period_ms = Some(33);
2801 timer.period_us = Some(33_333);
2802 recorder.push_entity(timer).unwrap();
2803
2804 let mut guard = entity_metadata(spec("guard_wake", EntityKind::Timer, "", "")).unwrap();
2806 guard.callback_id = Some(copy_str("cb_wake").unwrap());
2807 guard.callback_source = at(45);
2808 guard.timer_kind = TimerKind::GuardCondition;
2809 recorder.push_entity(guard).unwrap();
2810
2811 let mut srv = entity_metadata(spec(
2812 "srv_reset",
2813 EntityKind::ServiceServer,
2814 "~/reset",
2815 "std_srvs::srv::dds_::Trigger_",
2816 ))
2817 .unwrap();
2818 srv.callback_id = Some(copy_str("cb_reset").unwrap());
2819 srv.callback_source = at(50);
2820 recorder.push_entity(srv).unwrap();
2821
2822 let mut action = entity_metadata(spec(
2823 "act_route",
2824 EntityKind::ActionServer,
2825 "route",
2826 "example_interfaces::action::dds_::Fibonacci_",
2827 ))
2828 .unwrap();
2829 action.callback_id = Some(copy_str("cb_route_goal").unwrap());
2830 action.callback_source = at(60);
2831 action.action_cancel_callback_id = Some(copy_str("cb_route_cancel").unwrap());
2832 action.action_cancel_source = at(61);
2833 action.action_accepted_callback_id = Some(copy_str("cb_route_accepted").unwrap());
2834 action.action_accepted_source = at(62);
2835 recorder.push_entity(action).unwrap();
2836
2837 recorder
2838 .push_entity(
2839 entity_metadata(spec(
2840 "client_fib",
2841 EntityKind::ActionClient,
2842 "/fibonacci",
2843 "example_interfaces::action::dds_::Fibonacci_",
2844 ))
2845 .unwrap(),
2846 )
2847 .unwrap();
2848 recorder
2849 .push_entity(
2850 entity_metadata(spec(
2851 "client_add",
2852 EntityKind::ServiceClient,
2853 "/add_two_ints",
2854 "example_interfaces::srv::dds_::AddTwoInts_",
2855 ))
2856 .unwrap(),
2857 )
2858 .unwrap();
2859
2860 let mut declared =
2861 entity_metadata(spec("param_rate", EntityKind::Parameter, "rate_hz", "")).unwrap();
2862 declared.parameter_type = Some(ParameterType::Double);
2863 declared.parameter_default = Some(ParameterDefault::Double(copy_str("30.0").unwrap()));
2864 declared.parameter_read_only = true;
2865 declared.source = at(20);
2866 recorder.push_entity(declared).unwrap();
2867
2868 let mut read =
2870 entity_metadata(spec("param_period", EntityKind::Parameter, "period_ms", "")).unwrap();
2871 read.parameter_read = true;
2872 read.source = at(21);
2873 recorder.push_entity(read).unwrap();
2874
2875 recorder
2876 .push_callback_effect(
2877 CallbackId::new("cb_plan"),
2878 CallbackEffectKind::Publishes,
2879 EntityId::new("pub_path"),
2880 )
2881 .unwrap();
2882
2883 recorder.arm_descriptor_text();
2885 recorder.observe_descriptor_text(false, 42);
2886 recorder.observe_descriptor_text(true, 7);
2887 recorder.arm_parameter_declarations();
2889
2890 let json = recorder
2891 .to_source_metadata_json(
2892 &SourceMetadataExport::new("demo_planner", "planner")
2893 .language("cpp")
2894 .executable("planner_node")
2895 .exported_symbol("nros_component_planner")
2896 .source_artifacts(&["src/planner.cpp"]),
2897 )
2898 .unwrap();
2899 let json = std::format!("{json}\n");
2900
2901 let golden = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2902 .join("../../cli/nros-cli-core/tests/fixtures/orchestration/probe_sidecar_golden.json");
2903 if std::env::var_os("NROS_BLESS_PROBE_SIDECAR").is_some() {
2904 std::fs::write(&golden, &json).unwrap();
2905 }
2906 let committed = std::fs::read_to_string(&golden).unwrap_or_else(|e| {
2907 panic!(
2908 "{}: {e} -- the golden sidecar moved; update this path",
2909 golden.display()
2910 )
2911 });
2912 assert_eq!(
2913 committed,
2914 json,
2915 "the recorder's output moved off the golden sidecar {}. Re-run with \
2916 NROS_BLESS_PROBE_SIDECAR=1, and teach the CLI's SourceMetadata \
2917 (packages/cli/nros-cli-core/src/orchestration/source_metadata.rs) \
2918 any new key in the same change (issue 2689)",
2919 golden.display()
2920 );
2921 for row in [
2923 "\"lifecycle\":true",
2924 "\"in_place\":true",
2925 "\"buffered\":\"typed_bound\"",
2926 "\"kind\":\"guard_condition\"",
2927 "\"read\":true",
2928 "\"action_clients\":[{",
2929 "\"service_clients\":[{",
2930 "\"parameter_description_max_len\":42,",
2931 "\"parameter_constraints_max_len\":7,",
2932 "\"parameter_declarations_watched\":true,",
2933 ] {
2934 assert!(
2935 json.contains(row),
2936 "the golden must carry {row}, got {json}"
2937 );
2938 }
2939
2940 let keys = writer_keys(include_str!("node_metadata.rs"));
2945 assert!(
2946 keys.len() >= 50,
2947 "the writer scan found only {} keys ({keys:?}); the writer's \
2948 spelling moved, so teach `writer_keys` it",
2949 keys.len()
2950 );
2951 let missing: std::vec::Vec<&str> = keys
2952 .iter()
2953 .map(std::string::String::as_str)
2954 .filter(|k| !json.contains(&std::format!("\"{k}\":")))
2955 .collect();
2956 assert!(
2957 missing.is_empty(),
2958 "writer key(s) {missing:?} are absent from the golden sidecar: set \
2959 them on this test's recorder and re-bless, so the CLI's strict \
2960 parse sees them (issue 2689)"
2961 );
2962 }
2963
2964 #[cfg(feature = "alloc")]
2971 fn writer_keys(source: &str) -> std::collections::BTreeSet<std::string::String> {
2972 extern crate std;
2973 use std::string::String;
2974
2975 let writer = &source[..source
2976 .find("\nmod tests {")
2977 .expect("the tests module marker")];
2978 let code: String = writer
2979 .lines()
2980 .filter(|l| !l.trim_start().starts_with("//"))
2981 .flat_map(|l| [l, "\n"])
2982 .collect();
2983 let is_key = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_';
2984 let mut keys = std::collections::BTreeSet::new();
2985
2986 let mut rest = code.as_str();
2988 while let Some(at) = rest.find("\\\"") {
2989 rest = &rest[at + 2..];
2990 let end = rest.find(|c: char| !is_key(c)).unwrap_or(rest.len());
2991 if end > 0 && rest[end..].starts_with("\\\":") {
2992 keys.insert(String::from(&rest[..end]));
2993 }
2994 }
2995
2996 let mut rest = code.as_str();
2998 while let Some(at) = rest.find("write_") {
2999 rest = &rest[at + "write_".len()..];
3000 let name_end = rest.find(|c: char| !is_key(c)).unwrap_or(rest.len());
3001 let args = rest[name_end..].trim_start();
3002 let Some(args) = args.strip_prefix('(') else {
3003 continue;
3004 };
3005 let Some(args) = args.trim_start().strip_prefix("out") else {
3006 continue;
3007 };
3008 let Some(args) = args.trim_start().strip_prefix(',') else {
3009 continue;
3010 };
3011 let Some(args) = args.trim_start().strip_prefix('"') else {
3012 continue;
3013 };
3014 let end = args.find(|c: char| !is_key(c)).unwrap_or(args.len());
3015 if end > 0 && args[end..].starts_with('"') {
3016 keys.insert(String::from(&args[..end]));
3017 }
3018 }
3019 keys
3020 }
3021}