1use dora_message::{
2 config::{Input, InputMapping},
3 descriptor::{EnvValue, derive_port_id, single_topic_port_id},
4 id::{DataId, NodeId, OperatorId},
5};
6use eyre::{Context, OptionExt, Result, bail};
7use std::{
8 borrow::Cow,
9 collections::{BTreeMap, BTreeSet, HashMap},
10 env::consts::EXE_EXTENSION,
11 path::{Component, Path, PathBuf},
12 process::Command,
13};
14
15pub use dora_message::descriptor::{
17 CoreNodeKind, CustomNode, DYNAMIC_SOURCE, Descriptor, Node, OperatorConfig, OperatorDefinition,
18 OperatorSource, PythonSource, RUNTIME_PYTHON, RUNTIME_SHARED_LIBRARY, RUNTIME_WASM,
19 ResolvedNode, RmwZenohCompatibility, Ros2BridgeConfig, Ros2Direction, Ros2QosConfig,
20 Ros2TopicConfig, Ros2TransportConfig, RuntimeNode, SHELL_SOURCE, SingleOperatorDefinition,
21 descriptor_for_display,
22};
23pub use validate::ResolvedNodeExt;
24pub use visualize::collect_dora_timers;
25
26mod classify;
27pub(crate) fn normalize_path(path: &Path) -> PathBuf {
34 let mut out = PathBuf::new();
35 for component in path.components() {
36 match component {
37 Component::CurDir => {}
38 Component::ParentDir => {
39 out.pop();
40 }
41 other => out.push(other),
42 }
43 }
44 out
45}
46
47mod expand;
48pub mod validate;
49mod visualize;
50
51pub use expand::{
52 ExpandedDescriptor, ModuleBoundaries, check_module_file, expand_modules,
53 expand_modules_with_boundaries, reject_path_fallback,
54};
55
56pub trait DescriptorExt {
90 fn resolve_aliases_and_set_defaults(&self) -> eyre::Result<BTreeMap<NodeId, ResolvedNode>>;
97 fn visualize_as_mermaid_with_boundaries(
100 &self,
101 boundaries: &ModuleBoundaries,
102 ) -> eyre::Result<String>;
103 fn apply_exit_when_nodes_finish(&mut self, over: Option<bool>);
116
117 fn blocking_read(path: &Path) -> eyre::Result<Descriptor>;
119 fn parse(buf: Vec<u8>) -> eyre::Result<Descriptor>;
124 fn check(&self, working_dir: &Path) -> eyre::Result<()>;
127 fn expand(&self, working_dir: &Path) -> eyre::Result<Descriptor>;
133 fn expand_with_boundaries(
136 &self,
137 working_dir: &Path,
138 ) -> eyre::Result<(Descriptor, ModuleBoundaries)>;
139}
140
141pub const SINGLE_OPERATOR_DEFAULT_ID: &str = "op";
142
143fn prefix_output_with_operator_id(op_name: &OperatorId, output: &DataId) -> eyre::Result<DataId> {
154 format!("{op_name}/{output}")
155 .parse::<DataId>()
156 .map_err(|e| {
157 eyre::eyre!(
158 "operator id `{op_name}` produces an invalid output id `{op_name}/{output}`: {e}"
159 )
160 })
161}
162
163pub fn resolve_aliases_and_set_defaults_in_topology(
184 desc: &Descriptor,
185 topology_nodes: &[Node],
186) -> eyre::Result<BTreeMap<NodeId, ResolvedNode>> {
187 let default_op_id = OperatorId::from(SINGLE_OPERATOR_DEFAULT_ID.to_string());
188
189 let single_operator_nodes: HashMap<_, _> = topology_nodes
190 .iter()
191 .chain(desc.nodes.iter())
192 .filter_map(|n| {
193 n.operator
194 .as_ref()
195 .map(|op| (&n.id, op.id.as_ref().unwrap_or(&default_op_id)))
196 })
197 .collect();
198
199 let mut resolved = BTreeMap::new();
200 for mut node in desc.nodes.clone() {
201 let node_class = classify::classify(&node)?;
203
204 if node.ros2.is_some() {
206 for input in node.inputs.values_mut() {
207 if let InputMapping::User(m) = &mut input.mapping
208 && let Some(op_name) = single_operator_nodes.get(&m.source).copied()
209 {
210 m.output = prefix_output_with_operator_id(op_name, &m.output)?;
211 }
212 }
213 }
214
215 let input_mappings: Vec<_> = match &node_class {
217 classify::NodeClass::Standard { .. } => node.inputs.values_mut().collect(),
218 classify::NodeClass::Runtime => node
219 .operators
220 .as_mut()
221 .ok_or_eyre("no operators")?
222 .operators
223 .iter_mut()
224 .flat_map(|op| op.config.inputs.values_mut())
225 .collect(),
226 classify::NodeClass::Operator => node
227 .operator
228 .as_mut()
229 .ok_or_eyre("no operator")?
230 .config
231 .inputs
232 .values_mut()
233 .collect(),
234 classify::NodeClass::Ros2Bridge => vec![],
235 };
236 for mapping in input_mappings
237 .into_iter()
238 .filter_map(|i| match &mut i.mapping {
239 InputMapping::Timer { .. } | InputMapping::Logs(_) => None,
240 InputMapping::User(m) => Some(m),
241 })
242 {
243 if let Some(op_name) = single_operator_nodes.get(&mapping.source).copied() {
244 mapping.output = prefix_output_with_operator_id(op_name, &mapping.output)?;
245 }
246 }
247
248 let kind = match node_class {
252 classify::NodeClass::Standard { source } => {
253 let path = node.path.take().ok_or_eyre("missing `path` attribute")?;
254 let mut custom = CustomNode::from_node(&mut node, path);
255 custom.source = source;
256 CoreNodeKind::Custom(custom)
257 }
258 classify::NodeClass::Runtime => {
259 let runtime = node.operators.take().ok_or_eyre("no operators")?;
264 CoreNodeKind::Runtime(runtime)
265 }
266 classify::NodeClass::Operator => {
267 let op = node.operator.take().ok_or_eyre("no operator")?;
271 CoreNodeKind::Runtime(RuntimeNode {
272 operators: vec![OperatorDefinition {
273 id: op.id.unwrap_or_else(|| default_op_id.clone()),
274 config: op.config,
275 }],
276 })
277 }
278 classify::NodeClass::Ros2Bridge => {
279 let config = node.ros2.as_ref().ok_or_eyre("no ros2")?;
280 let config =
281 resolve_ros2_single_topic(&node.id, config, &node.inputs, &node.outputs)?;
282 if let Some(topics) = &config.topics {
292 validate_ros2_topic_ports(&node.id, topics, &node.inputs, &node.outputs)?;
293 }
294 let bridge_config_json = serde_json::to_string(&config)
295 .context("failed to serialize ROS2 bridge config")?;
296
297 let mut envs = BTreeMap::new();
298 envs.insert(
299 "DORA_ROS2_BRIDGE_CONFIG".to_string(),
300 EnvValue::String(bridge_config_json),
301 );
302
303 let mut custom =
309 CustomNode::from_node(&mut node, "dora-ros2-bridge-node".to_string());
310 custom.envs = Some(envs);
311 CoreNodeKind::Custom(custom)
312 }
313 };
314
315 if resolved.contains_key(&node.id) {
316 eyre::bail!(
317 "duplicate node ID `{}` — each node must have a unique `id`",
318 node.id
319 );
320 }
321 let mut resolved_node = ResolvedNode::from_node(node, kind);
322 validate::check_operator_ids(&resolved_node)?;
327 validate::check_runtime_operator_count(&resolved_node)?;
328 resolved_node.env = merge_env(desc.env.as_ref(), resolved_node.env.take());
332 resolved.insert(resolved_node.id.clone(), resolved_node);
333 }
334
335 Ok(resolved)
336}
337
338pub(crate) fn resolve_ros2_single_topic<'a>(
352 node_id: &NodeId,
353 config: &'a Ros2BridgeConfig,
354 node_inputs: &BTreeMap<DataId, Input>,
355 node_outputs: &BTreeSet<DataId>,
356) -> eyre::Result<Cow<'a, Ros2BridgeConfig>> {
357 let (Some(topic), Some(message_type), None) =
361 (&config.topic, &config.message_type, &config.topics)
362 else {
363 return Ok(Cow::Borrowed(config));
364 };
365 let (direction, port_kind, declared) = match config.direction {
366 Ros2Direction::Subscribe => (
367 "subscribe",
368 "output",
369 node_outputs
370 .iter()
371 .map(|id| id.as_str())
372 .collect::<Vec<_>>(),
373 ),
374 Ros2Direction::Publish => (
375 "publish",
376 "input",
377 node_inputs.keys().map(|id| id.as_str()).collect(),
378 ),
379 };
380 let Some(port) = single_topic_port_id(topic, &declared) else {
381 if declared.is_empty() {
382 bail!("node `{node_id}`: ros2 {direction} bridge requires at least one {port_kind}");
383 }
384 bail!(
385 "node `{node_id}`: ros2 {direction} topic `{topic}` has no unambiguous {port_kind} \
386 — single-topic mode binds to the node's declared {port_kind}, but it declares \
387 several: {}. Declare a single {port_kind}, name one of them after the topic \
388 (`{}`), or use `topics:` with an explicit `{port_kind}:`",
389 declared
390 .iter()
391 .map(|port| format!("`{port}`"))
392 .collect::<Vec<_>>()
393 .join(", "),
394 derive_port_id(topic),
395 );
396 };
397 let (output, input) = match config.direction {
398 Ros2Direction::Subscribe => (Some(port), None),
399 Ros2Direction::Publish => (None, Some(port)),
400 };
401 let mut resolved = config.clone();
402 resolved.topic = None;
403 resolved.message_type = None;
404 resolved.topics = Some(vec![Ros2TopicConfig {
405 topic: topic.clone(),
406 message_type: message_type.clone(),
407 direction: config.direction.clone(),
408 output,
409 input,
410 qos: None,
413 }]);
414 Ok(Cow::Owned(resolved))
415}
416
417pub(crate) fn validate_ros2_topic_ports(
437 node_id: &NodeId,
438 topics: &[Ros2TopicConfig],
439 node_inputs: &BTreeMap<DataId, Input>,
440 node_outputs: &BTreeSet<DataId>,
441) -> eyre::Result<()> {
442 for t in topics {
443 match &t.direction {
444 Ros2Direction::Subscribe => {
445 let output = t.output_port_id();
446 if !node_outputs.contains(output.as_str()) {
447 bail!(
448 "node `{node_id}`: ros2 subscribe topic `{}` maps to output \
449 `{output}`, which is not declared in the node's `outputs`",
450 t.topic
451 );
452 }
453 }
454 Ros2Direction::Publish => {
455 let input = t.input_port_id();
456 if !node_inputs.contains_key(input.as_str()) {
457 bail!(
458 "node `{node_id}`: ros2 publish topic `{}` maps to input \
459 `{input}`, which is not declared in the node's `inputs`",
460 t.topic
461 );
462 }
463 }
464 }
465 }
466 Ok(())
467}
468
469impl DescriptorExt for Descriptor {
470 fn resolve_aliases_and_set_defaults(&self) -> eyre::Result<BTreeMap<NodeId, ResolvedNode>> {
471 resolve_aliases_and_set_defaults_in_topology(self, &[])
472 }
473
474 fn visualize_as_mermaid_with_boundaries(
475 &self,
476 boundaries: &ModuleBoundaries,
477 ) -> eyre::Result<String> {
478 let resolved = self.resolve_aliases_and_set_defaults()?;
479 let flowchart = visualize::visualize_nodes_with_boundaries(&resolved, boundaries);
480 Ok(flowchart)
481 }
482
483 fn apply_exit_when_nodes_finish(&mut self, over: Option<bool>) {
484 if let Some(over) = over {
485 self.exit_when_nodes_finish = Some(over);
486 }
487 }
488
489 fn blocking_read(path: &Path) -> eyre::Result<Descriptor> {
490 let buf = std::fs::read(path).context("failed to open given file")?;
491 Descriptor::parse(buf)
492 }
493
494 fn parse(buf: Vec<u8>) -> eyre::Result<Descriptor> {
495 let descriptor: Descriptor =
496 serde_yaml::from_slice(&buf).context("failed to parse given descriptor")?;
497 reject_duplicate_keys(&buf).context("failed to parse given descriptor")?;
498 for node in &descriptor.nodes {
502 expand::reject_path_fallback(node, None)?;
503 }
504 Ok(descriptor)
505 }
506
507 fn check(&self, working_dir: &Path) -> eyre::Result<()> {
508 let expanded = self.expand(working_dir)?;
509 validate::check_dataflow(&expanded, working_dir)
510 .wrap_err("Dataflow could not be validated.")
511 }
512
513 fn expand(&self, working_dir: &Path) -> eyre::Result<Descriptor> {
514 expand::expand_modules(self, working_dir)
515 }
516
517 fn expand_with_boundaries(
518 &self,
519 working_dir: &Path,
520 ) -> eyre::Result<(Descriptor, ModuleBoundaries)> {
521 let expanded = expand::expand_modules_with_boundaries(self, working_dir)?;
522 Ok((expanded.descriptor, expanded.boundaries))
523 }
524}
525
526fn merge_env(
533 global: Option<&BTreeMap<String, EnvValue>>,
534 node: Option<BTreeMap<String, EnvValue>>,
535) -> Option<BTreeMap<String, EnvValue>> {
536 let merged = match (global, node) {
537 (None, None) => return None,
538 (None, Some(node)) => node,
539 (Some(global), None) => global.clone(),
540 (Some(global), Some(node)) => {
541 let mut merged = global.clone();
542 merged.extend(node);
544 merged
545 }
546 };
547 (!merged.is_empty()).then_some(merged)
549}
550
551pub fn reject_duplicate_keys(buf: &[u8]) -> eyre::Result<()> {
575 serde_yaml::from_slice::<serde_yaml::Value>(buf)?;
576 Ok(())
577}
578
579pub async fn read_as_descriptor(path: &Path) -> eyre::Result<Descriptor> {
585 let buf = tokio::fs::read(path)
586 .await
587 .context("failed to open given file")?;
588 Descriptor::parse(buf)
589}
590
591pub fn source_is_url(source: &str) -> bool {
612 source.starts_with("https://") || source.starts_with("http://")
613}
614
615pub fn resolve_path(source: &str, working_dir: &Path) -> Result<PathBuf> {
631 let path = with_exe_extension(source);
632
633 let joined = working_dir.join(&path);
636 if is_spawnable(&joined) {
637 absolutize_preserving_symlinks(&joined)
638 } else if which::which("uv").is_ok() {
641 or_on_system_path(resolve_path_via_uv(&path), &path)
642 } else if let Ok(abs_path) = which::which(&path) {
643 Ok(abs_path)
644 } else {
645 bail!("Could not find source path {}", path.display())
646 }
647}
648
649fn is_spawnable(path: &Path) -> bool {
657 path.is_file() || path.join("__main__.py").is_file()
658}
659
660fn with_exe_extension(source: &str) -> PathBuf {
662 let path = Path::new(source);
663 if path.extension().is_none() {
664 path.with_extension(EXE_EXTENSION)
665 } else {
666 path.to_owned()
667 }
668}
669
670pub fn resolve_node_path(
679 path: &str,
680 fallback: Option<&str>,
681 working_dir: &Path,
682) -> Result<PathBuf> {
683 let Some(fallback) = fallback else {
684 return resolve_path(path, working_dir);
685 };
686 let local = working_dir.join(with_exe_extension(path));
687 if local.is_file() {
688 return absolutize_preserving_symlinks(&local);
689 }
690 resolve_path(fallback, working_dir).wrap_err_with(|| {
691 format!("Could not find source path {path}, nor its `path_fallback` `{fallback}`")
692 })
693}
694
695pub fn without_path_fallback(descriptor: &Descriptor) -> Descriptor {
699 let mut descriptor = descriptor.clone();
700 for node in &mut descriptor.nodes {
701 node.path_fallback = None;
702 }
703 descriptor
704}
705
706fn or_on_system_path(uv_result: Result<PathBuf>, path: &Path) -> Result<PathBuf> {
714 uv_result.or_else(|uv_err| {
715 which::which(path).map_err(|_| {
716 uv_err.wrap_err(format!(
717 "Could not find source path {} in the uv environment or on $PATH",
718 path.display()
719 ))
720 })
721 })
722}
723
724pub fn resolve_path_confined(
732 source: &str,
733 working_dir: &Path,
734 python_env_dir: Option<&Path>,
735) -> Result<PathBuf> {
736 let path = Path::new(&source);
737 let path = if path.extension().is_none() {
738 path.with_extension(EXE_EXTENSION)
739 } else {
740 path.to_owned()
741 };
742
743 if let Some(env_dir) = python_env_dir {
745 let bin_dir = env_dir.join(if cfg!(windows) { "Scripts" } else { "bin" });
746 let candidate = bin_dir.join(&path);
747 if candidate.is_file() {
748 return confine(&candidate, &bin_dir);
749 }
750 }
751
752 let candidate = working_dir.join(&path);
754 if is_spawnable(&candidate) {
755 return confine(&candidate, working_dir);
756 }
757
758 bail!(
759 "could not find `{}` in the node's working directory `{}`{} — \
760 hub nodes resolve only within their own package (no $PATH fallback)",
761 path.display(),
762 working_dir.display(),
763 python_env_dir
764 .map(|env| format!(" or its managed environment `{}`", env.display()))
765 .unwrap_or_default(),
766 )
767}
768
769fn confine(candidate: &Path, root: &Path) -> Result<PathBuf> {
771 let resolved = candidate
772 .canonicalize()
773 .with_context(|| format!("failed to canonicalize `{}`", candidate.display()))?;
774 let root = root
775 .canonicalize()
776 .with_context(|| format!("failed to canonicalize `{}`", root.display()))?;
777 if !resolved.starts_with(&root) {
778 bail!(
779 "entrypoint `{}` resolves outside the node's directory `{}` \
780 (symlink escape?) — refusing to run it",
781 resolved.display(),
782 root.display()
783 );
784 }
785 Ok(resolved)
786}
787
788fn absolutize_preserving_symlinks(path: &Path) -> Result<PathBuf> {
804 if !path.exists() {
805 bail!("path {} does not exist", path.display());
806 }
807 std::path::absolute(path)
808 .with_context(|| format!("failed to make path {} absolute", path.display()))
809}
810
811fn resolve_path_via_uv(path: &Path) -> Result<PathBuf> {
820 let which = if cfg!(windows) { "where" } else { "which" };
821 let output = Command::new("uv")
822 .arg("run")
823 .arg(which)
824 .arg(path)
825 .output()
826 .with_context(|| format!("failed to run `uv run {which}`"))?;
827 if !output.status.success() {
828 bail!("Could not find source path {} within uv", path.display());
829 }
830 let stdout = String::from_utf8_lossy(&output.stdout);
833 let resolved = stdout
834 .lines()
835 .map(str::trim)
836 .find(|line| !line.is_empty())
837 .ok_or_else(|| eyre::eyre!("`uv run {which} {}` produced no output", path.display()))?;
838 absolutize_preserving_symlinks(Path::new(resolved))
839 .with_context(|| format!("uv-resolved path {resolved} is not usable"))
840}
841
842pub fn canonicalize_working_dir(
850 override_: Option<&Path>,
851 dataflow_path: &Path,
852) -> eyre::Result<PathBuf> {
853 match override_ {
854 Some(p) => dunce::canonicalize(p)
855 .with_context(|| format!("failed to canonicalize working_dir `{}`", p.display())),
856 None => {
857 let parent = dataflow_path
858 .parent()
859 .filter(|p| !p.as_os_str().is_empty())
860 .unwrap_or_else(|| Path::new("."));
861 dunce::canonicalize(parent).with_context(|| {
862 format!(
863 "failed to canonicalize dataflow parent directory `{}`",
864 parent.display()
865 )
866 })
867 }
868 }
869}
870
871pub trait NodeExt {
874 fn kind(&self) -> eyre::Result<NodeKind<'_>>;
882}
883
884impl NodeExt for Node {
885 fn kind(&self) -> eyre::Result<NodeKind<'_>> {
886 if self.hub.is_some() && self.path.is_none() {
887 eyre::bail!(
892 "node `{}` uses an unresolved `hub:` reference — run `dora build` \
893 first (`dora start` requires a prior build for hub nodes)",
894 self.id
895 );
896 }
897 match (
898 &self.path,
899 &self.operators,
900 &self.operator,
901 &self.ros2,
902 &self.module,
903 ) {
904 (None, None, None, None, None) => {
905 eyre::bail!(
906 "node `{}` requires a `path`, `operators`, `operator`, `ros2`, or `module` field",
907 self.id
908 )
909 }
910 (None, None, Some(operator), None, None) => Ok(NodeKind::Operator(operator)),
911 (None, Some(runtime), None, None, None) => Ok(NodeKind::Runtime(runtime)),
912 (Some(path), None, None, None, None) => Ok(NodeKind::Standard(path)),
913 (None, None, None, Some(ros2), None) => Ok(NodeKind::Ros2Bridge(ros2)),
914 (None, None, None, None, Some(module)) => Ok(NodeKind::Module(module)),
915 _ => {
916 eyre::bail!(
917 "node `{}` has multiple exclusive fields set, only one of `path`, `operators`, `operator`, `ros2`, and `module` is allowed",
918 self.id
919 )
920 }
921 }
922 }
923}
924
925#[derive(Debug)]
929pub enum NodeKind<'a> {
930 Standard(&'a String),
932 Runtime(&'a RuntimeNode),
934 Operator(&'a SingleOperatorDefinition),
936 Ros2Bridge(&'a Ros2BridgeConfig),
938 Module(&'a String),
940}
941
942#[cfg(test)]
943mod tests {
944 fn resolved_bridge_config(yaml: &str) -> Ros2BridgeConfig {
946 let descriptor: Descriptor = serde_yaml::from_str(yaml).expect("parse");
947 let resolved = descriptor
948 .resolve_aliases_and_set_defaults()
949 .expect("resolve");
950 let node = resolved.values().next().expect("one node");
951 let CoreNodeKind::Custom(custom) = &node.kind else {
952 panic!("ros2 bridge must resolve to a custom node");
953 };
954 let Some(EnvValue::String(json)) = custom
955 .envs
956 .as_ref()
957 .and_then(|envs| envs.get("DORA_ROS2_BRIDGE_CONFIG"))
958 else {
959 panic!("bridge node must carry DORA_ROS2_BRIDGE_CONFIG");
960 };
961 serde_json::from_str(json).expect("bridge config round-trips")
962 }
963
964 #[test]
968 fn single_topic_subscribe_binds_the_declared_output() {
969 let config = resolved_bridge_config(
970 "\
971nodes:
972 - id: pose_bridge
973 ros2:
974 topic: /turtle1/pose
975 message_type: turtlesim/Pose
976 direction: subscribe
977 outputs:
978 - pose
979",
980 );
981 let topics = config
982 .topics
983 .expect("single topic is resolved to a mapping");
984 assert_eq!(topics.len(), 1);
985 assert_eq!(topics[0].topic, "/turtle1/pose");
986 assert_eq!(topics[0].output.as_deref(), Some("pose"));
987 assert_eq!(config.topic, None, "the unresolved form must not survive");
988 }
989
990 #[test]
991 fn single_topic_publish_binds_the_declared_input() {
992 let config = resolved_bridge_config(
993 "\
994nodes:
995 - id: cmd_bridge
996 ros2:
997 topic: /turtle1/cmd_vel
998 message_type: geometry_msgs/Twist
999 direction: publish
1000 inputs:
1001 cmd_vel: planner/cmd_vel
1002",
1003 );
1004 let topics = config
1005 .topics
1006 .expect("single topic is resolved to a mapping");
1007 assert_eq!(topics[0].input.as_deref(), Some("cmd_vel"));
1008 }
1009
1010 #[test]
1012 fn multi_topic_config_is_left_alone() {
1013 let config = resolved_bridge_config(
1014 "\
1015nodes:
1016 - id: turtle_bridge
1017 ros2:
1018 topics:
1019 - topic: /turtle1/pose
1020 message_type: turtlesim/Pose
1021 direction: subscribe
1022 output: pose
1023 outputs:
1024 - pose
1025",
1026 );
1027 let topics = config.topics.expect("topics survive resolution");
1028 assert_eq!(topics[0].output.as_deref(), Some("pose"));
1029 }
1030
1031 #[test]
1036 fn ambiguous_single_topic_is_rejected_during_resolution() {
1037 let descriptor: Descriptor = serde_yaml::from_str(
1038 "\
1039nodes:
1040 - id: pose_bridge
1041 ros2:
1042 topic: /turtle1/pose
1043 message_type: turtlesim/Pose
1044 direction: subscribe
1045 outputs:
1046 - pose
1047 - log
1048",
1049 )
1050 .expect("parse");
1051 let err = descriptor
1052 .resolve_aliases_and_set_defaults()
1053 .expect_err("an ambiguous port mapping must not resolve")
1054 .to_string();
1055 assert!(
1056 err.contains("no unambiguous output") && err.contains("turtle1_pose"),
1057 "error should explain the ambiguity, got: {err}"
1058 );
1059 }
1060
1061 #[test]
1065 fn single_topic_rewrite_never_overwrites_an_explicit_topics_list() {
1066 let config = resolved_bridge_config(
1067 "\
1068nodes:
1069 - id: bridge
1070 ros2:
1071 topic: /turtle1/pose
1072 message_type: turtlesim/Pose
1073 direction: subscribe
1074 topics:
1075 - topic: /turtle1/other
1076 message_type: turtlesim/Pose
1077 direction: subscribe
1078 output: pose
1079 outputs:
1080 - pose
1081",
1082 );
1083 assert_eq!(config.topic.as_deref(), Some("/turtle1/pose"));
1084 let topics = config.topics.expect("the explicit list survives");
1085 assert_eq!(topics.len(), 1);
1086 assert_eq!(topics[0].topic, "/turtle1/other");
1087 }
1088
1089 #[test]
1098 fn exit_when_nodes_finish_override_semantics() {
1099 use super::DescriptorExt;
1100
1101 let parse = |yaml: &str| -> Descriptor { serde_yaml::from_str(yaml).expect("parse") };
1102 let with_setting = "exit_when_nodes_finish: true\nnodes:\n - id: a\n path: ./a\n";
1103 let without = "nodes:\n - id: a\n path: ./a\n";
1104
1105 let mut d = parse(with_setting);
1107 d.apply_exit_when_nodes_finish(None);
1108 assert_eq!(
1109 d.exit_when_nodes_finish,
1110 Some(true),
1111 "omitting the flag must not silently disable a policy the \
1112 dataflow file asked for"
1113 );
1114
1115 let mut d = parse(without);
1116 d.apply_exit_when_nodes_finish(None);
1117 assert_eq!(d.exit_when_nodes_finish, None, "and must not invent one");
1118
1119 let mut d = parse(with_setting);
1121 d.apply_exit_when_nodes_finish(Some(false));
1122 assert_eq!(
1123 d.exit_when_nodes_finish,
1124 Some(false),
1125 "`--exit-when-nodes-finish=false` must be able to turn OFF a \
1126 policy the dataflow file turned on"
1127 );
1128
1129 let mut d = parse(without);
1130 d.apply_exit_when_nodes_finish(Some(true));
1131 assert_eq!(d.exit_when_nodes_finish, Some(true));
1132 }
1133
1134 use super::*;
1135 use dora_message::descriptor::{GitRepoRev, NodeSource};
1136 use std::collections::BTreeSet;
1137
1138 fn env(pairs: &[(&str, &str)]) -> BTreeMap<String, EnvValue> {
1139 pairs
1140 .iter()
1141 .map(|(k, v)| (k.to_string(), EnvValue::String(v.to_string())))
1142 .collect()
1143 }
1144
1145 #[test]
1146 fn merge_env_returns_none_when_both_absent() {
1147 assert!(merge_env(None, None).is_none());
1148 }
1149
1150 #[test]
1151 fn merge_env_keeps_per_node_when_no_global() {
1152 let node_env = env(&[("A", "1")]);
1153 let merged = merge_env(None, Some(node_env.clone())).unwrap();
1154 assert_eq!(merged, node_env);
1155 }
1156
1157 #[test]
1158 fn merge_env_keeps_global_when_no_per_node() {
1159 let global = env(&[("A", "1")]);
1160 let merged = merge_env(Some(&global), None).unwrap();
1161 assert_eq!(merged, global);
1162 }
1163
1164 #[test]
1165 fn merge_env_normalizes_empty_node_map_to_none() {
1166 assert!(merge_env(None, Some(env(&[]))).is_none());
1171 }
1172
1173 #[test]
1174 fn merge_env_normalizes_empty_global_and_node_maps_to_none() {
1175 assert!(merge_env(Some(&env(&[])), Some(env(&[]))).is_none());
1176 assert!(merge_env(Some(&env(&[])), None).is_none());
1177 }
1178
1179 #[test]
1180 fn merge_env_per_node_overrides_global_on_conflict() {
1181 let global = env(&[("A", "global"), ("B", "global")]);
1182 let node_env = env(&[("A", "node"), ("C", "node")]);
1183 let merged = merge_env(Some(&global), Some(node_env)).unwrap();
1184 assert_eq!(merged.get("A"), Some(&EnvValue::String("node".into())));
1185 assert_eq!(merged.get("B"), Some(&EnvValue::String("global".into())));
1186 assert_eq!(merged.get("C"), Some(&EnvValue::String("node".into())));
1187 }
1188
1189 fn resolved_input_mapping<'a>(
1190 resolved: &'a BTreeMap<NodeId, ResolvedNode>,
1191 node: &str,
1192 input: &str,
1193 ) -> &'a InputMapping {
1194 let node = resolved
1195 .get(&NodeId::from(node.to_string()))
1196 .expect("node resolved");
1197 let inputs = match &node.kind {
1198 CoreNodeKind::Custom(n) => &n.run_config.inputs,
1199 CoreNodeKind::Runtime(_) => panic!("expected custom node"),
1200 };
1201 &inputs
1202 .get(&DataId::from(input.to_string()))
1203 .expect("input present")
1204 .mapping
1205 }
1206
1207 #[test]
1208 fn add_node_prefixes_single_operator_producer_input_via_topology() {
1209 let topology: Descriptor = serde_yaml::from_str(
1216 "\
1217nodes:
1218 - id: producer
1219 operator:
1220 python: producer.py
1221 outputs:
1222 - result
1223",
1224 )
1225 .expect("parse topology");
1226
1227 let added: Descriptor = serde_yaml::from_str(
1228 "\
1229nodes:
1230 - id: consumer
1231 path: consumer
1232 inputs:
1233 reading: producer/result
1234",
1235 )
1236 .expect("parse added node");
1237
1238 let resolved = resolve_aliases_and_set_defaults_in_topology(&added, &topology.nodes)
1241 .expect("resolve in topology");
1242 match resolved_input_mapping(&resolved, "consumer", "reading") {
1243 InputMapping::User(m) => {
1244 assert_eq!(m.source, NodeId::from("producer".to_string()));
1245 assert_eq!(m.output, DataId::from("op/result".to_string()));
1246 }
1247 other => panic!("expected user mapping, got {other:?}"),
1248 }
1249
1250 let resolved_isolated = added
1255 .resolve_aliases_and_set_defaults()
1256 .expect("resolve isolated");
1257 match resolved_input_mapping(&resolved_isolated, "consumer", "reading") {
1258 InputMapping::User(m) => {
1259 assert_eq!(m.output, DataId::from("result".to_string()));
1260 }
1261 other => panic!("expected user mapping, got {other:?}"),
1262 }
1263 }
1264
1265 #[test]
1273 fn resolve_preserves_operator_subtree() {
1274 let desc: Descriptor = serde_yaml::from_str(
1275 "\
1276nodes:
1277 - id: runtime_node
1278 operators:
1279 - id: op_a
1280 python: a.py
1281 outputs:
1282 - out_a
1283 - id: operator_node
1284 operator:
1285 python: b.py
1286 outputs:
1287 - out_b
1288",
1289 )
1290 .expect("parse");
1291
1292 let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1293
1294 match &resolved[&NodeId::from("runtime_node".to_string())].kind {
1296 CoreNodeKind::Runtime(rt) => {
1297 let ids: Vec<_> = rt.operators.iter().map(|o| o.id.to_string()).collect();
1298 assert_eq!(ids, ["op_a"], "runtime operators must survive resolution");
1299 }
1300 other => panic!("expected Runtime kind, got {other:?}"),
1301 }
1302
1303 match &resolved[&NodeId::from("operator_node".to_string())].kind {
1306 CoreNodeKind::Runtime(rt) => {
1307 assert_eq!(
1308 rt.operators.len(),
1309 1,
1310 "the operator must survive resolution"
1311 );
1312 assert_eq!(rt.operators[0].id.to_string(), SINGLE_OPERATOR_DEFAULT_ID);
1313 }
1314 other => panic!("expected Runtime kind, got {other:?}"),
1315 }
1316 }
1317
1318 #[test]
1319 fn topology_lookup_prefers_the_node_being_added_over_a_same_id_topology_entry() {
1320 let topology: Descriptor = serde_yaml::from_str(
1326 "\
1327nodes:
1328 - id: producer
1329 operator:
1330 id: stale
1331 python: producer.py
1332 outputs:
1333 - result
1334",
1335 )
1336 .expect("parse topology");
1337
1338 let added: Descriptor = serde_yaml::from_str(
1339 "\
1340nodes:
1341 - id: producer
1342 operator:
1343 id: fresh
1344 python: producer.py
1345 outputs:
1346 - result
1347 - id: consumer
1348 path: consumer
1349 inputs:
1350 reading: producer/result
1351",
1352 )
1353 .expect("parse added nodes");
1354
1355 let resolved = resolve_aliases_and_set_defaults_in_topology(&added, &topology.nodes)
1356 .expect("resolve in topology");
1357 match resolved_input_mapping(&resolved, "consumer", "reading") {
1358 InputMapping::User(m) => {
1359 assert_eq!(m.output, DataId::from("fresh/result".to_string()));
1360 }
1361 other => panic!("expected user mapping, got {other:?}"),
1362 }
1363 }
1364
1365 #[test]
1366 fn descriptor_global_env_parses_from_yaml() {
1367 let yaml = r#"
1370env:
1371 RUST_LOG: info
1372 OTEL_ENDPOINT: http://collector:4317
1373nodes:
1374 - id: a
1375 path: ./a
1376 env:
1377 RUST_LOG: debug
1378 - id: b
1379 path: ./b
1380"#;
1381 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1382 let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1383
1384 let a = resolved.get(&NodeId::from("a".to_string())).unwrap();
1385 let a_env = a.env.as_ref().expect("node a inherits env");
1386 assert_eq!(
1388 a_env.get("RUST_LOG"),
1389 Some(&EnvValue::String("debug".into()))
1390 );
1391 assert_eq!(
1393 a_env.get("OTEL_ENDPOINT"),
1394 Some(&EnvValue::String("http://collector:4317".into()))
1395 );
1396
1397 let b = resolved.get(&NodeId::from("b".to_string())).unwrap();
1398 let b_env = b.env.as_ref().expect("node b inherits global env");
1399 assert_eq!(
1400 b_env.get("RUST_LOG"),
1401 Some(&EnvValue::String("info".into()))
1402 );
1403 assert_eq!(
1404 b_env.get("OTEL_ENDPOINT"),
1405 Some(&EnvValue::String("http://collector:4317".into()))
1406 );
1407 }
1408
1409 #[test]
1410 fn invalid_operator_id_prefix_errors_instead_of_panicking() {
1411 let yaml = r#"
1419nodes:
1420 - id: producer
1421 operator:
1422 id: "bad id"
1423 python: op.py
1424 outputs: [result]
1425 - id: consumer
1426 path: ./consumer
1427 inputs:
1428 x: producer/result
1429"#;
1430 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1431 let result = desc.resolve_aliases_and_set_defaults();
1432 assert!(result.is_err(), "expected a clean descriptor error, got Ok");
1433 }
1434
1435 #[test]
1436 fn resolve_path_errors_for_nonexistent_binary() {
1437 let working_dir = std::env::current_dir().expect("cwd");
1443 let result = resolve_path("dora_nonexistent_binary_2016_regression", &working_dir);
1444 assert!(
1445 result.is_err(),
1446 "expected Err for a binary that exists nowhere, got {result:?}"
1447 );
1448 }
1449
1450 #[test]
1460 #[cfg(unix)]
1461 fn resolve_path_preserves_symlinks() {
1462 let tmp = tempfile::tempdir().expect("tempdir");
1463 let target = tmp.path().join("base-interpreter.bin");
1464 std::fs::write(&target, b"x").unwrap();
1465 let link = tmp.path().join("venv-python.bin");
1466 std::os::unix::fs::symlink(&target, &link).unwrap();
1467
1468 let resolved = resolve_path("venv-python.bin", tmp.path()).unwrap();
1470 assert!(resolved.is_absolute());
1471 assert!(
1472 resolved.ends_with("venv-python.bin"),
1473 "resolve_path followed the symlink: {} — venv discovery \
1474 (pyvenv.cfg) is keyed off the symlink location, so execing \
1475 the target bypasses the venv",
1476 resolved.display()
1477 );
1478
1479 let resolved = resolve_path(link.to_str().unwrap(), Path::new("/")).unwrap();
1481 assert!(
1482 resolved.ends_with("venv-python.bin"),
1483 "absolute symlink path was canonicalized: {}",
1484 resolved.display()
1485 );
1486
1487 std::fs::create_dir(tmp.path().join("sub")).unwrap();
1492 let resolved = resolve_path("sub/../venv-python.bin", tmp.path()).unwrap();
1493 assert!(
1494 resolved.ends_with("sub/../venv-python.bin"),
1495 "`..` was normalized away: {}",
1496 resolved.display()
1497 );
1498 }
1499
1500 #[test]
1507 #[cfg(unix)]
1508 fn resolve_path_treats_dangling_symlink_as_missing() {
1509 let tmp = tempfile::tempdir().expect("tempdir");
1510 let link = tmp.path().join("dangling-2918-regression.bin");
1511 std::os::unix::fs::symlink(tmp.path().join("no-such-target"), &link).unwrap();
1512
1513 let result = resolve_path("dangling-2918-regression.bin", tmp.path());
1514 assert!(
1515 result.is_err(),
1516 "a dangling symlink must not resolve (nothing on uv/$PATH matches \
1517 this name either), got {result:?}"
1518 );
1519 }
1520
1521 #[test]
1526 fn resolve_path_skips_a_directory_with_the_executable_name() {
1527 let tmp = tempfile::tempdir().expect("tempdir");
1528 let name = format!(
1529 "dora-dir-not-exe-regression{}",
1530 std::env::consts::EXE_SUFFIX
1531 );
1532 std::fs::create_dir(tmp.path().join(&name)).unwrap();
1533
1534 let result = resolve_path(&name, tmp.path());
1535 assert!(
1536 result.is_err(),
1537 "a directory must not resolve (nothing on uv/$PATH matches this \
1538 name either), got {result:?}"
1539 );
1540 }
1541
1542 #[test]
1545 fn resolve_path_keeps_a_directory_with_a_main_py() {
1546 let tmp = tempfile::tempdir().expect("tempdir");
1547 let name = format!("dora-main-py-dir{}", std::env::consts::EXE_SUFFIX);
1548 let dir = tmp.path().join(&name);
1549 std::fs::create_dir(&dir).unwrap();
1550 std::fs::write(dir.join("__main__.py"), "").unwrap();
1551
1552 let resolved = resolve_path(&name, tmp.path()).unwrap();
1553 assert_eq!(resolved, absolutize_preserving_symlinks(&dir).unwrap());
1554 }
1555
1556 #[test]
1560 fn a_dataflow_file_cannot_set_path_fallback() {
1561 for yaml in [
1562 "nodes:\n - id: x\n path: tool\n path_fallback: tool\n",
1563 "nodes:\n - id: m\n module: m.yml\n - id: x\n path: ./x\n path_fallback: x\n",
1564 ] {
1565 let err = Descriptor::parse(yaml.as_bytes().to_vec()).unwrap_err();
1566 assert_eq!(
1567 format!("{err:#}"),
1568 "node `x` sets `path_fallback`, which is internal \
1569 (module expansion sets it); remove it",
1570 "{yaml}"
1571 );
1572 }
1573 Descriptor::parse(b"nodes:\n - id: x\n path: tool\n".to_vec()).unwrap();
1574 }
1575
1576 #[test]
1580 fn a_dataflow_file_cannot_repeat_a_map_key() {
1581 for (yaml, key) in [
1582 (
1583 "nodes:\n - id: x\n path: tool\n inputs:\n image: cam/img\n image: dora/timer/millis/20\n",
1584 "image",
1585 ),
1586 (
1587 "nodes:\n - id: x\n path: tool\n env:\n A: \"1\"\n A: \"2\"\n",
1588 "A",
1589 ),
1590 ] {
1591 let err = Descriptor::parse(yaml.as_bytes().to_vec()).unwrap_err();
1592 let msg = format!("{err:#}");
1593 assert!(
1594 msg.contains(&format!("duplicate entry with key \"{key}\"")),
1595 "{yaml}: {msg}"
1596 );
1597 }
1598 let ok = Descriptor::parse(
1599 b"nodes:\n - id: x\n path: tool\n inputs:\n a: dora/timer/millis/20\n b: dora/timer/millis/30\n"
1600 .to_vec(),
1601 )
1602 .unwrap();
1603 assert_eq!(ok.nodes[0].inputs.len(), 2);
1604 }
1605
1606 #[test]
1607 fn path_fallbacks_survive_persistence_and_resolution() {
1608 let mut descriptor: Descriptor = serde_yaml::from_str(
1609 "nodes:\n - id: module.worker\n path: modules/worker\n args: --keep\n",
1610 )
1611 .unwrap();
1612 let fallbacks = BTreeMap::from([("module.worker".parse().unwrap(), "worker".into())]);
1613 descriptor.nodes[0].path_fallback = Some("worker".into());
1614 let persisted = serde_json::to_vec(&descriptor).unwrap();
1615 let restored: Descriptor = serde_json::from_slice(&persisted).unwrap();
1616 assert_eq!(restored.path_fallbacks(), fallbacks);
1617 let nodes = restored.resolve_aliases_and_set_defaults().unwrap();
1618 let CoreNodeKind::Custom(node) = &nodes[&NodeId::from("module.worker".to_owned())].kind
1619 else {
1620 panic!("expected a custom node");
1621 };
1622 assert_eq!(node.path_fallback.as_deref(), Some("worker"));
1623 assert_eq!(node.args.as_deref(), Some("--keep"));
1624 }
1625
1626 #[test]
1627 fn without_path_fallback_clears_it_on_every_node_only() {
1628 let nodes =
1629 "nodes:\n - id: a\n path: modules/a\n - id: b\n path: sub/b\n args: --x\n";
1630 let with: Descriptor = serde_yaml::from_str(
1631 &nodes
1632 .replace(
1633 "path: modules/a\n",
1634 "path: modules/a\n path_fallback: a\n",
1635 )
1636 .replace("path: sub/b\n", "path: sub/b\n path_fallback: b\n"),
1637 )
1638 .unwrap();
1639 assert!(with.nodes.iter().all(|node| node.path_fallback.is_some()));
1640 let without: Descriptor = serde_yaml::from_str(nodes).unwrap();
1641
1642 assert_eq!(
1643 serde_yaml::to_value(without_path_fallback(&with)).unwrap(),
1644 serde_yaml::to_value(&without).unwrap()
1645 );
1646 }
1647
1648 #[test]
1654 fn a_bare_module_node_path_falls_back_to_a_top_level_lookup() {
1655 let tmp = tempfile::tempdir().expect("tempdir");
1656 let dir = tmp.path();
1657 std::fs::create_dir_all(dir.join("modules")).unwrap();
1658 std::fs::write(
1659 dir.join("modules/m.yml"),
1660 "module:\n name: m\nnodes:\n - id: worker\n path: worker-3826\n",
1661 )
1662 .unwrap();
1663 let desc: Descriptor =
1664 serde_yaml::from_str("nodes:\n - id: m\n module: modules/m.yml\n").unwrap();
1665 let file = format!("worker-3826{}", std::env::consts::EXE_SUFFIX);
1667
1668 let missing = desc.check(dir).expect_err("no file anywhere");
1669 let missing = format!("{missing:?}");
1670 assert!(
1671 missing.contains("nor its `path_fallback` `worker-3826`"),
1672 "{missing}"
1673 );
1674
1675 std::fs::write(dir.join(&file), "").unwrap();
1677 desc.check(dir).unwrap();
1678 let expanded = desc.expand(dir).unwrap();
1679 let path = expanded.nodes[0].path.clone().unwrap();
1680 let fallback = expanded.nodes[0].path_fallback.as_deref();
1681 assert_eq!(Path::new(&path), Path::new("modules").join("worker-3826"));
1682 assert_eq!(fallback, Some("worker-3826"));
1683 assert_eq!(
1684 resolve_node_path(&path, fallback, dir).unwrap(),
1685 dir.join(&file)
1686 );
1687
1688 std::fs::write(dir.join("modules").join(&file), "").unwrap();
1690 assert_eq!(
1691 resolve_node_path(&path, fallback, dir).unwrap(),
1692 dir.join("modules").join(&file)
1693 );
1694 }
1695
1696 #[test]
1700 fn a_folder_next_to_the_module_does_not_block_the_fallback() {
1701 let tmp = tempfile::tempdir().expect("tempdir");
1702 let dir = tmp.path();
1703 let file = format!("my-node{}", std::env::consts::EXE_SUFFIX);
1704 std::fs::create_dir_all(dir.join("modules").join(&file)).unwrap();
1705 std::fs::write(dir.join(&file), "").unwrap();
1706
1707 let path = Path::new("modules").join("my-node");
1708 assert_eq!(
1709 resolve_node_path(path.to_str().unwrap(), Some("my-node"), dir).unwrap(),
1710 dir.join(&file)
1711 );
1712 }
1713
1714 #[test]
1715 fn resolve_path_confined_has_no_path_fallback() {
1716 let tmp = tempfile::tempdir().expect("tempdir");
1717 let result = resolve_path_confined("sh", tmp.path(), None);
1721 assert!(result.is_err(), "expected Err, got {result:?}");
1722
1723 let exe = if cfg!(windows) {
1725 "node.exe"
1726 } else {
1727 "node.bin"
1728 };
1729 std::fs::write(tmp.path().join(exe), b"x").unwrap();
1730 let resolved = resolve_path_confined(exe, tmp.path(), None).unwrap();
1731 assert!(resolved.is_absolute());
1732
1733 let env_dir = tmp.path().join("env");
1735 let bin_dir = env_dir.join(if cfg!(windows) { "Scripts" } else { "bin" });
1736 std::fs::create_dir_all(&bin_dir).unwrap();
1737 std::fs::write(bin_dir.join(exe), b"x").unwrap();
1738 let resolved =
1739 resolve_path_confined(exe, tmp.path().join("empty").as_path(), Some(&env_dir));
1740 assert!(resolved.is_ok(), "{resolved:?}");
1741 }
1742
1743 #[test]
1748 fn resolve_path_confined_skips_a_directory_with_the_entrypoint_name() {
1749 let tmp = tempfile::tempdir().expect("tempdir");
1750 let name = format!("talker{}", std::env::consts::EXE_SUFFIX);
1751 std::fs::create_dir(tmp.path().join(&name)).unwrap();
1752 let env_dir = tmp.path().join("env");
1753 std::fs::create_dir_all(env_dir.join(if cfg!(windows) { "Scripts" } else { "bin" }))
1754 .unwrap();
1755
1756 let err = resolve_path_confined(&name, tmp.path(), Some(&env_dir)).unwrap_err();
1757 assert!(
1758 format!("{err:#}").contains("could not find"),
1759 "unexpected error: {err:#}"
1760 );
1761 }
1762
1763 #[test]
1766 fn resolve_path_confined_keeps_a_directory_with_a_main_py() {
1767 let tmp = tempfile::tempdir().expect("tempdir");
1768 let name = format!("talker{}", std::env::consts::EXE_SUFFIX);
1769 let dir = tmp.path().join(&name);
1770 std::fs::create_dir(&dir).unwrap();
1771 std::fs::write(dir.join("__main__.py"), "").unwrap();
1772
1773 let resolved = resolve_path_confined(&name, tmp.path(), None).unwrap();
1774 assert_eq!(resolved, dir.canonicalize().unwrap());
1775 }
1776
1777 #[cfg(unix)]
1778 #[test]
1779 fn resolve_path_confined_rejects_symlink_escape() {
1780 let tmp = tempfile::tempdir().expect("tempdir");
1781 let working_dir = tmp.path().join("work");
1782 std::fs::create_dir_all(&working_dir).unwrap();
1783 let outside = tmp.path().join("outside.bin");
1784 std::fs::write(&outside, b"x").unwrap();
1785 std::os::unix::fs::symlink(&outside, working_dir.join("escape.bin")).unwrap();
1786 let result = resolve_path_confined("escape.bin", &working_dir, None);
1787 assert!(
1788 result.is_err(),
1789 "a symlink pointing outside the working dir must be rejected, got {result:?}"
1790 );
1791 let msg = format!("{:#}", result.unwrap_err());
1792 assert!(msg.contains("outside"), "{msg}");
1793 }
1794
1795 #[test]
1796 fn unresolved_hub_node_has_clear_kind_error() {
1797 let node: Node = serde_yaml::from_str("id: x\nhub: dora-yolo@^0.5\n").unwrap();
1798 let err = node.kind().unwrap_err();
1799 assert!(format!("{err}").contains("dora build"), "{err}");
1800 }
1801
1802 #[test]
1803 fn resolve_path_via_uv_errors_for_nonexistent_binary() {
1804 if which::which("uv").is_err() {
1812 return;
1813 }
1814 let path = Path::new("dora_nonexistent_binary_2016_regression");
1815 let result = resolve_path_via_uv(path);
1816 assert!(
1817 result.is_err(),
1818 "expected Err from `uv run which` for a missing binary, got {result:?}"
1819 );
1820 }
1821
1822 #[test]
1825 #[cfg(unix)]
1826 fn failed_uv_lookup_falls_back_to_system_path() {
1827 let resolved = or_on_system_path(Err(eyre::eyre!("uv failed")), Path::new("sh"))
1828 .expect("`sh` is on $PATH");
1829 assert!(resolved.is_absolute(), "{}", resolved.display());
1830
1831 let missing = Path::new("dora_nonexistent_binary_2016_regression");
1832 let err = or_on_system_path(Err(eyre::eyre!("uv failed")), missing).unwrap_err();
1833 assert!(err.to_string().contains("or on $PATH"), "{err:?}");
1834 assert_eq!(err.root_cause().to_string(), "uv failed");
1835 }
1836
1837 #[test]
1838 fn descriptor_without_global_env_preserves_per_node_env() {
1839 let yaml = r#"
1842nodes:
1843 - id: a
1844 path: ./a
1845 env:
1846 FOO: bar
1847 - id: b
1848 path: ./b
1849"#;
1850 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1851 let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1852 let a = resolved.get(&NodeId::from("a".to_string())).unwrap();
1853 assert_eq!(
1854 a.env.as_ref().and_then(|e| e.get("FOO")),
1855 Some(&EnvValue::String("bar".into()))
1856 );
1857 let b = resolved.get(&NodeId::from("b".to_string())).unwrap();
1858 assert!(b.env.is_none(), "node b has no env anywhere");
1859 }
1860
1861 #[test]
1862 fn duplicate_node_id_is_rejected() {
1863 let yaml = r#"
1866nodes:
1867 - id: my-node
1868 path: ./a
1869 - id: my-node
1870 path: ./b
1871"#;
1872 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1873 let err = desc
1874 .resolve_aliases_and_set_defaults()
1875 .expect_err("duplicate node ID must be rejected");
1876 let msg = format!("{err:#}");
1877 assert!(
1878 msg.contains("duplicate node ID") && msg.contains("my-node"),
1879 "unexpected error message: {msg}"
1880 );
1881 }
1882
1883 fn custom_node_field_names() -> BTreeSet<String> {
1889 let schema = schemars::schema_for!(dora_message::descriptor::CustomNode);
1890 let schema = serde_json::to_value(schema).expect("schema should serialize");
1891 schema
1892 .pointer("/$defs/CustomNode/properties")
1893 .or_else(|| schema.pointer("/definitions/CustomNode/properties"))
1894 .or_else(|| schema.pointer("/properties"))
1895 .and_then(serde_json::Value::as_object)
1896 .expect("CustomNode schema should expose properties")
1897 .keys()
1898 .cloned()
1899 .collect()
1900 }
1901
1902 const SHARED_CUSTOM_NODE_KEYS: &str = r#"
1906 args: --verbose
1907 send_stdout_as: stdout-topic
1908 send_logs_as: logs-topic
1909 min_log_level: debug
1910 max_log_size: 4MB
1911 max_rotated_files: 3
1912 restart_policy: always
1913 max_restarts: 7
1914 restart_delay: 1.5
1915 max_restart_delay: 9.5
1916 restart_window: 60.0
1917 health_check_timeout: 2.5
1918 startup_timeout: 4.5
1919 finish_grace_secs: 3.5
1920 shared_memory_pool_size: 8MB
1921 inputs:
1922 tick: dora/timer/millis/100
1923 outputs:
1924 - out
1925 output_types:
1926 out: arrow.int32
1927 output_framing:
1928 out: arrow-ipc
1929 input_types:
1930 tick: arrow.uint64
1931"#;
1932
1933 fn resolve_and_check_carried_through(yaml: &str, kind_specific: &[&str]) -> CustomNode {
1946 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
1947 let declared = serde_json::to_value(&desc.nodes[0]).expect("serialize declared");
1948 let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
1949 let node = resolved.values().next().expect("one node");
1950 let CoreNodeKind::Custom(custom) = &node.kind else {
1951 panic!("expected a custom node, got {:?}", node.kind);
1952 };
1953
1954 let actual = serde_json::to_value(custom).expect("serialize resolved");
1955 let default =
1958 serde_json::to_value(CustomNode::new("<unset>".to_owned())).expect("serialize default");
1959
1960 for field in custom_node_field_names() {
1961 if kind_specific.contains(&field.as_str()) {
1962 continue;
1963 }
1964 assert_ne!(
1965 actual.get(&field),
1966 default.get(&field),
1967 "`{field}` is still at its `CustomNode::new` default after \
1968 resolution — either the YAML does not set it (add it to \
1969 `SHARED_CUSTOM_NODE_KEYS`) or the key is parsed and then \
1970 dropped (carry it in `CustomNode::from_node`)."
1971 );
1972 assert_eq!(
1973 actual.get(&field),
1974 declared.get(&field),
1975 "`{field}` resolved to a different value than the YAML declared \
1976 — `CustomNode::from_node` copies it from the wrong `Node` field."
1977 );
1978 }
1979 custom.clone()
1980 }
1981
1982 #[test]
1987 fn every_custom_node_field_is_carried_through() {
1988 let yaml = format!(
1989 "nodes:\n - id: full\n path: ./full-node\n path_sha256: abc123\n \
1990 path_fallback: full-node\n build: cargo build{SHARED_CUSTOM_NODE_KEYS}"
1991 );
1992 let custom = resolve_and_check_carried_through(&yaml, &["source", "envs"]);
1993 assert!(
1994 matches!(custom.source, NodeSource::Local),
1995 "{:?}",
1996 custom.source
1997 );
1998 assert!(custom.envs.is_none(), "{:?}", custom.envs);
1999 }
2000
2001 #[test]
2005 fn git_source_is_carried_through() {
2006 let yaml = format!(
2007 "nodes:\n - id: full\n path: node\n path_sha256: abc123\n \
2008 path_fallback: full-node\n build: cargo build\n git: https://github.com/example/node.git\n \
2009 branch: main{SHARED_CUSTOM_NODE_KEYS}"
2010 );
2011 let custom = resolve_and_check_carried_through(&yaml, &["source", "envs"]);
2012 assert!(
2013 matches!(
2014 &custom.source,
2015 NodeSource::GitBranch { repo, rev: Some(GitRepoRev::Branch(branch)) }
2016 if repo == "https://github.com/example/node.git" && branch == "main"
2017 ),
2018 "{:?}",
2019 custom.source
2020 );
2021 assert!(custom.envs.is_none(), "{:?}", custom.envs);
2022 }
2023
2024 #[test]
2029 fn ros2_bridge_node_is_carried_through() {
2030 let yaml = format!(
2031 "nodes:\n - id: bridge\n ros2:\n topic: /odom\n \
2032 message_type: nav_msgs/msg/Odometry\n direction: subscribe\
2033 {SHARED_CUSTOM_NODE_KEYS}"
2034 );
2035 let custom = resolve_and_check_carried_through(
2036 &yaml,
2037 &[
2038 "path",
2039 "source",
2040 "path_sha256",
2041 "path_fallback",
2042 "build",
2043 "envs",
2044 ],
2045 );
2046 assert_eq!(custom.path, "dora-ros2-bridge-node");
2047 assert!(
2048 matches!(custom.source, NodeSource::Local),
2049 "{:?}",
2050 custom.source
2051 );
2052 assert!(custom.path_sha256.is_none(), "{:?}", custom.path_sha256);
2053 assert!(custom.path_fallback.is_none(), "{:?}", custom.path_fallback);
2054 assert!(custom.build.is_none(), "{:?}", custom.build);
2055 let envs = custom
2056 .envs
2057 .expect("the bridge is configured through its environment");
2058 let Some(EnvValue::String(config)) = envs.get("DORA_ROS2_BRIDGE_CONFIG") else {
2059 panic!("DORA_ROS2_BRIDGE_CONFIG missing from {envs:?}");
2060 };
2061 assert!(config.contains("/odom"), "{config}");
2062 }
2063
2064 #[test]
2071 fn node_level_keys_are_carried_through() {
2072 let yaml = r#"
2073env:
2074 RUST_LOG: info
2075 SHARED: global
2076nodes:
2077 - id: full
2078 name: Full Node
2079 description: Sets every node-level key
2080 path: ./full-node
2081 env:
2082 SHARED: per-node
2083 cpu_affinity: [0, 1]
2084 deploy:
2085 machine: gpu-box
2086"#;
2087 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2088 let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
2089 let node = resolved.values().next().expect("one node");
2090
2091 assert_eq!(node.id.to_string(), "full");
2092 assert_eq!(node.name.as_deref(), Some("Full Node"));
2093 assert_eq!(
2094 node.description.as_deref(),
2095 Some("Sets every node-level key")
2096 );
2097 assert_eq!(
2098 node.env,
2099 Some(env(&[("RUST_LOG", "info"), ("SHARED", "per-node")]))
2100 );
2101 assert_eq!(node.cpu_affinity, Some(vec![0, 1]));
2102 assert_eq!(
2103 node.deploy.as_ref().and_then(|d| d.machine.as_deref()),
2104 Some("gpu-box")
2105 );
2106 }
2107
2108 #[test]
2115 fn runtime_node_subgraph_id_is_sanitized_for_dotted_ids() {
2116 let yaml = r#"
2117nodes:
2118 - id: camera.front
2119 operators:
2120 - id: detect
2121 python: detect.py
2122 inputs:
2123 tick: dora/timer/millis/100
2124 outputs:
2125 - bbox
2126"#;
2127 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2128 let resolved = desc.resolve_aliases_and_set_defaults().expect("resolve");
2129 let flowchart =
2130 visualize::visualize_nodes_with_boundaries(&resolved, &ModuleBoundaries::default());
2131
2132 assert!(
2133 flowchart.contains("subgraph camera_front [camera.front]"),
2134 "runtime-node subgraph id must be sanitized and labelled; got:\n{flowchart}"
2135 );
2136 assert!(
2137 !flowchart.contains("subgraph camera.front"),
2138 "an unsanitized dotted subgraph id is invalid Mermaid; got:\n{flowchart}"
2139 );
2140 }
2141
2142 #[test]
2148 fn resolve_rejects_undeclared_multi_topic_subscribe_output() {
2149 let yaml = r#"
2150nodes:
2151 - id: lidar_bridge
2152 outputs: [scan]
2153 ros2:
2154 topics:
2155 - topic: /scan
2156 message_type: sensor_msgs/LaserScan
2157 direction: subscribe
2158 output: scna
2159"#;
2160 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2161 let err = desc
2162 .resolve_aliases_and_set_defaults()
2163 .expect_err("resolution must reject a topic mapped to an undeclared output")
2164 .to_string();
2165 assert!(
2166 err.contains("scna") && err.contains("not declared"),
2167 "error should name the undeclared output, got: {err}"
2168 );
2169 }
2170
2171 #[test]
2174 fn resolve_rejects_undeclared_multi_topic_publish_input() {
2175 let yaml = r#"
2176nodes:
2177 - id: source
2178 path: ./source
2179 outputs: [cmd]
2180 - id: cmd_bridge
2181 inputs:
2182 cmd: source/cmd
2183 ros2:
2184 topics:
2185 - topic: /cmd_vel
2186 message_type: geometry_msgs/Twist
2187 direction: publish
2188 input: typo_in
2189"#;
2190 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2191 let err = desc
2192 .resolve_aliases_and_set_defaults()
2193 .expect_err("resolution must reject a topic mapped to an undeclared input")
2194 .to_string();
2195 assert!(
2196 err.contains("typo_in") && err.contains("not declared"),
2197 "error should name the undeclared input, got: {err}"
2198 );
2199 }
2200
2201 #[test]
2204 fn resolve_accepts_declared_multi_topic_ports() {
2205 let yaml = r#"
2206nodes:
2207 - id: bridge
2208 outputs: [scan, laser]
2209 ros2:
2210 topics:
2211 - topic: /scan
2212 message_type: sensor_msgs/LaserScan
2213 direction: subscribe
2214 output: scan
2215 - topic: /laser
2216 message_type: sensor_msgs/LaserScan
2217 direction: subscribe
2218"#;
2219 let desc: Descriptor = serde_yaml::from_str(yaml).expect("parse");
2220 desc.resolve_aliases_and_set_defaults().expect(
2221 "a multi-topic config mapping declared ports (explicit and derived) must resolve",
2222 );
2223 }
2224
2225 #[test]
2232 fn node_kind_error_lists_the_operator_field() {
2233 let descriptor: Descriptor =
2234 serde_yaml::from_str("nodes:\n - id: lonely\n").expect("parse");
2235 let node = descriptor.nodes.first().expect("one node");
2236 let err = node
2237 .kind()
2238 .expect_err("a node with no implementation field must be rejected");
2239 let msg = format!("{err}");
2240 assert!(
2241 msg.contains("`operator`"),
2242 "the error must list the single-`operator` kind, got: {msg}"
2243 );
2244 }
2245}