dora_message/descriptor.rs
1#![warn(missing_docs)]
2
3use crate::{
4 config::{ByteSize, Input, NodeRunConfig},
5 id::{DataId, NodeId, OperatorId},
6};
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use std::{
10 collections::{BTreeMap, BTreeSet},
11 fmt,
12 path::PathBuf,
13};
14
15/// Wire framing requested for an output via `output_framing`.
16///
17/// Accepted for dora 1.x schema compatibility only: neither value changes
18/// anything. Every output is encoded as Arrow IPC regardless of this
19/// setting.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
21#[serde(rename_all = "kebab-case")]
22pub enum OutputFraming {
23 /// The default.
24 #[default]
25 Raw,
26 /// Arrow IPC stream format.
27 ArrowIpc,
28}
29
30/// Source identifier for shell-based nodes.
31pub const SHELL_SOURCE: &str = "shell";
32/// Set the [`Node::path`] field to this value to treat the node as a
33/// [_dynamic node_](https://docs.rs/dora-node-api/latest/dora_node_api/).
34pub const DYNAMIC_SOURCE: &str = "dynamic";
35
36/// # Dataflow Specification
37///
38/// The main configuration structure for defining a Dora dataflow. Dataflows are
39/// specified through YAML files that describe the nodes, their connections, and
40/// execution parameters.
41///
42/// ## Structure
43///
44/// A dataflow consists of:
45/// - **Nodes**: The computational units that process data
46/// - **Deployment**: Optional deployment configuration
47/// - **Debug options**: Optional development and debugging settings
48///
49/// ## Example
50///
51/// ```
52/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
53/// use dora_message::descriptor::Descriptor;
54/// let yaml = r#"
55/// nodes:
56/// - id: webcam
57/// operator:
58/// python: webcam.py
59/// inputs:
60/// tick: dora/timer/millis/100
61/// outputs:
62/// - image
63/// - id: plot
64/// operator:
65/// python: plot.py
66/// inputs:
67/// image: webcam/image
68/// "#;
69/// let descriptor: Descriptor = serde_yaml::from_str(yaml)?;
70/// assert_eq!(descriptor.nodes.len(), 2);
71/// # Ok(())
72/// # }
73/// ```
74#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
75#[serde(deny_unknown_fields)]
76#[schemars(title = "dora-rs specification")]
77// Same rationale as `Node`: keeps a new *dataflow-level* key a minor release.
78// This is where `exit_when_nodes_finish`, `health_check_interval`, `type_rules`
79// and `strict_types` landed, so it grows at least as often as `Node` does.
80// Construct with `Descriptor::new`; the fields remain `pub`.
81#[non_exhaustive]
82pub struct Descriptor {
83 /// List of nodes in the dataflow
84 ///
85 /// This is the most important field of the dataflow specification.
86 /// Each node must be identified by a unique `id`:
87 ///
88 /// ## Example
89 ///
90 /// ```yaml
91 /// nodes:
92 /// - id: foo
93 /// path: path/to/the/executable
94 /// # ... (see below)
95 /// - id: bar
96 /// path: path/to/another/executable
97 /// # ... (see below)
98 /// ```
99 ///
100 /// For each node, you need to specify the `path` of the executable or script that Dora should run when starting the node.
101 /// Most of the other node fields are optional, but you typically want to specify at least some `inputs` and/or `outputs`.
102 pub nodes: Vec<Node>,
103
104 /// Deployment configuration (optional).
105 pub deploy: Option<Deploy>,
106
107 /// Debug options (optional).
108 #[serde(default)]
109 // An empty key is YAML `null`, which deserializes to the default.
110 #[schemars(with = "Option<Debug>")]
111 pub debug: Debug,
112
113 /// How often the daemon checks node health (in seconds).
114 ///
115 /// Defaults to 5.0 seconds if not specified. Lower values detect hung nodes
116 /// faster but add more overhead.
117 #[serde(default)]
118 pub health_check_interval: Option<f64>,
119
120 /// Enable strict type checking: type warnings become errors during build.
121 ///
122 /// Can also be enabled via `--strict-types` CLI flag on `dora build`.
123 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub strict_types: Option<bool>,
125
126 /// Finish the dataflow once every node has, treating
127 /// `dora/timer/...` inputs as a clock rather than as work.
128 ///
129 /// A timer input has no upstream node, so it never closes. By default
130 /// a node consuming one is therefore never told its inputs are done
131 /// and the graph cannot end on its own, even after every node doing
132 /// real work has exited (dora-rs/dora#2920).
133 ///
134 /// Off by default: for a long-lived dataflow the timer is precisely
135 /// what keeps it alive. Nodes with no data inputs at all (timer-only
136 /// sources, or no inputs) are unaffected either way -- they have no
137 /// dependency that could finish, so they are treated as sources.
138 ///
139 /// Set by `dora run --exit-when-nodes-finish` and `dora start
140 /// --exit-when-nodes-finish`, and settable directly in YAML. It lives
141 /// on the descriptor rather than on the wire so that it survives the
142 /// events a dataflow outlives: auto-recovery re-spawn, coordinator
143 /// restart with state reconstruction, and `dora restart`.
144 ///
145 /// ## Example
146 ///
147 /// ```yaml
148 /// exit_when_nodes_finish: true
149 /// nodes:
150 /// - id: worker
151 /// path: ./worker
152 /// inputs:
153 /// tick: dora/timer/millis/100
154 /// ```
155 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub exit_when_nodes_finish: Option<bool>,
157
158 /// Custom type compatibility rules.
159 ///
160 /// Each rule declares that a source type can be implicitly converted to
161 /// a target type. These supplement the built-in widening rules.
162 ///
163 /// ## Example
164 ///
165 /// ```yaml
166 /// type_rules:
167 /// - from: myproject/SensorV1
168 /// to: myproject/SensorV2
169 /// ```
170 #[serde(default, skip_serializing_if = "Vec::is_empty")]
171 // An empty key is YAML `null`, which deserializes to the default.
172 #[schemars(with = "Option<Vec<TypeRuleDef>>")]
173 pub type_rules: Vec<TypeRuleDef>,
174
175 /// Global environment variables inherited by every node.
176 ///
177 /// Each node's own `env` map takes precedence on key conflicts, so nodes
178 /// can override a global default without repeating shared values like
179 /// `RUST_LOG`, `OTEL_EXPORTER_OTLP_ENDPOINT`, or `CUDA_VISIBLE_DEVICES`.
180 ///
181 /// ## Example
182 ///
183 /// ```yaml
184 /// env:
185 /// RUST_LOG: info
186 /// OTEL_EXPORTER_OTLP_ENDPOINT: http://collector:4317
187 /// nodes:
188 /// - id: verbose-node
189 /// path: path/to/node
190 /// env:
191 /// RUST_LOG: debug # overrides the global RUST_LOG for this node
192 /// ```
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub env: Option<BTreeMap<String, EnvValue>>,
195}
196
197// Wire descriptors must remain readable by peers whose strict `Node` schema
198// predates `path_fallback`. Control requests carry it separately; daemon spawn
199// requests already carry it in the permissive resolved `CustomNode`.
200pub(crate) fn serialize_without_path_fallback<S>(
201 descriptor: &Descriptor,
202 serializer: S,
203) -> Result<S::Ok, S::Error>
204where
205 S: serde::Serializer,
206{
207 let mut descriptor = descriptor.clone();
208 for node in &mut descriptor.nodes {
209 node.path_fallback = None;
210 }
211 descriptor.serialize(serializer)
212}
213
214impl Descriptor {
215 /// Fallback commands keyed by expanded node id, for the control protocol.
216 pub fn path_fallbacks(&self) -> BTreeMap<NodeId, String> {
217 self.nodes
218 .iter()
219 .filter_map(|node| {
220 node.path_fallback
221 .as_ref()
222 .map(|name| (node.id.clone(), name.clone()))
223 })
224 .collect()
225 }
226
227 /// A dataflow of `nodes` with every dataflow-level option left at its
228 /// default (the state a YAML file with only a `nodes:` key deserializes
229 /// to).
230 ///
231 /// `Descriptor` is `#[non_exhaustive]`, so other crates cannot build one
232 /// with a struct literal. Start here and assign the options you need — the
233 /// fields are all still `pub`.
234 pub fn new(nodes: Vec<Node>) -> Self {
235 Self {
236 nodes,
237 deploy: None,
238 debug: Default::default(),
239 health_check_interval: None,
240 strict_types: None,
241 exit_when_nodes_finish: None,
242 type_rules: Default::default(),
243 env: None,
244 }
245 }
246}
247
248/// A type compatibility rule declared in the dataflow YAML.
249#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
250#[serde(deny_unknown_fields)]
251// See the note on `Node`: `type_rules:` is a dataflow-level YAML surface, so a
252// per-rule option added later (a direction flag, a coercion mode) must stay a
253// minor release. Construct with `TypeRuleDef::new`; the fields remain `pub`.
254#[non_exhaustive]
255pub struct TypeRuleDef {
256 /// Source type URN
257 pub from: String,
258 /// Target type URN
259 pub to: String,
260}
261
262impl TypeRuleDef {
263 /// A rule declaring that `from` is compatible with `to`.
264 ///
265 /// `TypeRuleDef` is `#[non_exhaustive]`, so other crates cannot build one
266 /// with a struct literal. Start here and assign any further options — the
267 /// fields are all still `pub`.
268 pub fn new(from: String, to: String) -> Self {
269 Self { from, to }
270 }
271}
272
273/// Specifies when a node should be restarted.
274#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
275#[serde(rename_all = "kebab-case")]
276// The descriptor *enums* — this one, `OutputFraming`, `DistributeStrategy`,
277// `NodeSource`, `GitRepoRev`, `EnvValue`, `OperatorSource`, `PythonSourceDef`,
278// the four `Ros2*` enums and `config::QueuePolicy` — are deliberately NOT
279// `#[non_exhaustive]`, unlike the descriptor structs.
280//
281// The cost of that is real and known: adding a variant (`restart-policy:
282// unless-stopped`, a third `output_framing`, an rsync `distribute` strategy) is
283// `enum_variant_added` — a semver-major break — so it cannot land until 2.0.
284//
285// It is deliberate because the alternative is worse here. `#[non_exhaustive]`
286// forces a `_ =>` arm in every downstream match. Marking all of them stops the
287// build with 11 such matches in `dora-core` and the ROS2 bridge alone, before
288// it even reaches the ones in `dora-daemon` and `dora-cli` — restart decisions,
289// git-ref resolution, lockfile cache keys, operator-runtime dispatch, ROS2
290// transport selection. Those crates ship in lockstep with this one, so today a
291// new variant is a compile error naming every site that must handle it; behind
292// a catch-all it becomes a silent wrong answer (a new `GitRepoRev` colliding in
293// the build lockfile key, a new `RestartPolicy` reading as "never restart").
294// Exhaustive matching is the thing actually preventing those bugs, and no
295// external consumer gets a comparable guarantee back.
296//
297// The structs have no such tension: a new field breaks only struct literals,
298// which the `::new` constructors already replace.
299pub enum RestartPolicy {
300 /// Never restart the node (default)
301 #[default]
302 Never,
303 /// Restart the node if it exits with a non-zero exit code.
304 OnFailure,
305 /// Always restart the node when it exits, regardless of exit code.
306 ///
307 /// The node will not be restarted on the following conditions:
308 ///
309 /// - The node was stopped by the user (e.g., via `dora stop`).
310 /// - All inputs to the node have been closed and the node finished with a non-zero exit code.
311 Always,
312}
313
314/// Deployment configuration for distributing nodes across machines.
315#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
316#[serde(deny_unknown_fields)]
317// Same rationale as `Node`: keeps a new deployment key a minor release.
318// Every field has a meaningful default, so `Deploy::default()` is the
319// construction entry point rather than a bespoke `new`; the fields remain
320// `pub`.
321#[non_exhaustive]
322pub struct Deploy {
323 /// Target machine for deployment
324 pub machine: Option<String>,
325 /// Working directory for the deployment
326 pub working_dir: Option<PathBuf>,
327 /// Labels for label-based scheduling (e.g. `gpu: "true"`, `arch: arm64`).
328 /// The coordinator matches these against daemon labels reported at registration.
329 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
330 // An empty key is YAML `null`, which deserializes to the default.
331 #[schemars(with = "Option<BTreeMap<String, String>>")]
332 pub labels: BTreeMap<String, String>,
333 /// How built binaries are distributed to remote daemons.
334 #[serde(default)]
335 pub distribute: DistributeStrategy,
336}
337
338/// Strategy for distributing built binaries to daemons.
339#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
340#[serde(rename_all = "lowercase")]
341pub enum DistributeStrategy {
342 /// Each daemon builds from source (current/default behavior).
343 #[default]
344 Local,
345 /// Reserved for SCP distribution. Currently uses local builds.
346 Scp,
347 /// Reserved for HTTP distribution. Currently uses local builds.
348 Http,
349}
350
351/// Debug options for dataflow development and troubleshooting.
352#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
353#[serde(deny_unknown_fields)]
354// See the note on `Node`: `debug:` is a dataflow-level YAML surface and a
355// second debug option must stay a minor release. Every field has a meaningful
356// default, so `Debug::default()` is the construction entry point; the fields
357// remain `pub`.
358#[non_exhaustive]
359pub struct Debug {
360 /// When true, daemons mirror every node output to the coordinator WebSocket
361 /// so that `dora topic echo`, `dora topic hz`, and `dora topic info` can
362 /// inspect runtime messages.
363 #[serde(default)]
364 pub enable_debug_inspection: bool,
365}
366
367/// # Dora Node Configuration
368///
369/// A node represents a computational unit in a Dora dataflow. Each node runs as a
370/// separate process and can communicate with other nodes through inputs and outputs.
371#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
372#[serde(deny_unknown_fields)]
373// Adding a descriptor key must stay a *minor* release. Without this, every new
374// per-node field is `constructible_struct_adds_field` — a semver-major break
375// for `dora-message` — which turns routine feature work into a "land it before
376// the next major or wait" scramble. `Node::new` is the construction entry point
377// for other crates; the fields stay `pub`, so they are still freely readable
378// and assignable. The *wire-protocol* enums in this crate (`daemon_to_node.rs`,
379// `node_to_daemon.rs`, `daemon_to_coordinator.rs`, `daemon_to_daemon.rs`) were
380// marked for the same reason in #3151, and `RunDataflowOptions` in the daemon
381// is the existing struct-shaped precedent. The descriptor *enums* are a
382// separate axis and are not covered — see the note on `RestartPolicy`.
383//
384// The construction advice lives here and on `Node::new`, not in the `///`
385// doc: that doc is the description schemars writes into `dora-schema.json`,
386// which YAML editors show to dataflow authors, and rustdoc already flags
387// `#[non_exhaustive]` types on its own.
388#[non_exhaustive]
389pub struct Node {
390 /// Unique node identifier.
391 ///
392 /// Node IDs may only contain ASCII letters, digits, `_`, `.` and `-`
393 /// (no `/`, no whitespace), with the following further limitations:
394 ///
395 /// - They must not be empty or start with `.`.
396 /// - They must not be the reserved id `dora`.
397 ///
398 /// Each node must have an ID field.
399 ///
400 /// ## Example
401 ///
402 /// ```yaml
403 /// nodes:
404 /// - id: camera_node
405 /// - id: some_other_node
406 /// ```
407 pub id: NodeId,
408
409 /// Human-readable node name for documentation.
410 ///
411 /// This optional field can be used to define a more descriptive name in addition to a short
412 /// [`id`](Self::id).
413 ///
414 /// ## Example
415 ///
416 /// ```yaml
417 /// nodes:
418 /// - id: camera_node
419 /// name: "Camera Input Handler"
420 pub name: Option<String>,
421
422 /// Detailed description of the node's functionality.
423 ///
424 /// ## Example
425 ///
426 /// ```yaml
427 /// nodes:
428 /// - id: camera_node
429 /// description: "Captures video frames from webcam"
430 /// ```
431 pub description: Option<String>,
432
433 /// Path to executable or script that should be run.
434 ///
435 /// Specifies the path of the executable or script that Dora should run when starting the
436 /// dataflow.
437 /// This can point to a normal executable (e.g. when using a compiled language such as Rust) or
438 /// a Python script.
439 ///
440 /// Dora will automatically append a `.exe` extension on Windows systems when the specified
441 /// file name has no extension.
442 ///
443 /// ## Example
444 ///
445 /// ```yaml
446 /// nodes:
447 /// - id: rust-example
448 /// path: target/release/rust-node
449 /// - id: python-example
450 /// path: ./receive_data.py
451 /// ```
452 ///
453 /// ## URL as Path
454 ///
455 /// The `path` field can also point to a URL instead of a local path.
456 /// In this case, Dora will download the given file when starting the dataflow.
457 ///
458 /// Note that this is quite an old feature and using this functionality is **not recommended**
459 /// anymore. Instead, we recommend using a [`git`][Self::git] and/or [`build`](Self::build)
460 /// key.
461 #[serde(default, skip_serializing_if = "Option::is_none")]
462 pub path: Option<String>,
463
464 /// SHA-256 checksum the `path` download must match, verified after fetch
465 /// and on cache reuse (spec §8.2/§8.4). Set internally when a `hub:`
466 /// reference resolves to a prebuilt binary artifact; rarely set by hand.
467 #[serde(default, skip_serializing_if = "Option::is_none")]
468 pub path_sha256: Option<String>,
469
470 /// Command-line arguments passed to the executable.
471 ///
472 /// The command-line arguments that should be passed to the executable/script specified in `path`.
473 /// The arguments should be separated by space.
474 /// This field is optional and defaults to an empty argument list.
475 ///
476 /// ## Example
477 /// ```yaml
478 /// nodes:
479 /// - id: example
480 /// path: example-node
481 /// args: -v --some-flag foo
482 /// ```
483 #[serde(default, skip_serializing_if = "Option::is_none")]
484 pub args: Option<String>,
485
486 /// Environment variables for node builds and execution.
487 ///
488 /// Key-value map of environment variables that should be set for both the
489 /// [`build`](Self::build) operation and the node execution (i.e. when the node is spawned
490 /// through [`path`](Self::path)).
491 ///
492 /// Supports strings, numbers, and booleans.
493 ///
494 /// ## Example
495 ///
496 /// ```yaml
497 /// nodes:
498 /// - id: example-node
499 /// path: path/to/node
500 /// env:
501 /// DEBUG: true
502 /// PORT: 8080
503 /// API_KEY: "secret-key"
504 /// ```
505 pub env: Option<BTreeMap<String, EnvValue>>,
506
507 /// Multiple operators running in a shared runtime process.
508 ///
509 /// Operators are an experimental, lightweight alternative to nodes.
510 /// Instead of running as a separate process, operators are linked into a runtime process.
511 /// This allows running multiple operators to share a single address space (not supported for
512 /// Python currently).
513 ///
514 /// Operators are defined as part of the node list, as children of a runtime node.
515 /// A runtime node is a special node that specifies no [`path`](Self::path) field, but contains
516 /// an `operators` field instead.
517 ///
518 /// ## Example
519 ///
520 /// ```yaml
521 /// nodes:
522 /// - id: runtime-node
523 /// operators:
524 /// - id: processor
525 /// python: process.py
526 /// ```
527 #[serde(default, skip_serializing_if = "Option::is_none")]
528 pub operators: Option<RuntimeNode>,
529
530 /// Single operator configuration.
531 ///
532 /// This is a convenience field for defining runtime nodes that contain only a single operator.
533 /// This field is an alternative to the [`operators`](Self::operators) field, which can be used
534 /// if there is only a single operator defined for the runtime node.
535 ///
536 /// ## Example
537 ///
538 /// ```yaml
539 /// nodes:
540 /// - id: runtime-node
541 /// operator:
542 /// id: processor
543 /// python: script.py
544 /// outputs: [data]
545 /// ```
546 #[serde(default, skip_serializing_if = "Option::is_none")]
547 pub operator: Option<SingleOperatorDefinition>,
548
549 /// ROS2 bridge configuration (unstable).
550 ///
551 /// Declares this node as a ROS2 bridge that automatically subscribes to or
552 /// publishes on ROS2 topics. No custom code is needed -- the framework spawns
553 /// a bridge binary that converts between ROS2 DDS messages and Dora's Arrow
554 /// format.
555 ///
556 /// ## Example
557 ///
558 /// ```yaml
559 /// nodes:
560 /// - id: camera_bridge
561 /// ros2:
562 /// topic: /camera/image_raw
563 /// message_type: sensor_msgs/Image
564 /// direction: subscribe
565 /// outputs:
566 /// - image
567 /// ```
568 #[serde(default, skip_serializing_if = "Option::is_none")]
569 pub ros2: Option<Ros2BridgeConfig>,
570
571 /// Output data identifiers produced by this node.
572 ///
573 /// List of output identifiers that the node sends.
574 /// Must contain all `output_id` values that the node uses when sending output, e.g. through the
575 /// [`send_output`](https://docs.rs/dora-node-api/latest/dora_node_api/struct.DoraNode.html#method.send_output)
576 /// function.
577 ///
578 /// ## Example
579 ///
580 /// ```yaml
581 /// nodes:
582 /// - id: example-node
583 /// outputs:
584 /// - processed_image
585 /// - metadata
586 /// ```
587 #[serde(default)]
588 // An empty `outputs:` is YAML `null`, which deserializes to an empty set.
589 #[schemars(with = "Option<BTreeSet<DataId>>")]
590 pub outputs: BTreeSet<DataId>,
591
592 /// Optional type annotations for outputs.
593 ///
594 /// Maps output identifiers to type URNs (e.g. `std/media/v1/Image`).
595 /// Only annotated outputs are type-checked; unannotated outputs remain dynamic.
596 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
597 // An empty key is YAML `null`, which deserializes to the default.
598 #[schemars(with = "Option<BTreeMap<DataId, String>>")]
599 pub output_types: BTreeMap<DataId, String>,
600
601 /// Per-output framing overrides. Accepted for 1.x schema compatibility
602 /// but ignored: every output is encoded as Arrow IPC whatever its entry
603 /// here says (see [`OutputFraming`]).
604 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
605 // An empty key is YAML `null`, which deserializes to the default.
606 #[schemars(with = "Option<BTreeMap<DataId, OutputFraming>>")]
607 pub output_framing: BTreeMap<DataId, OutputFraming>,
608
609 /// Input data connections from other nodes.
610 ///
611 /// Defines the inputs that this node is subscribing to.
612 ///
613 /// The `inputs` field should be a key-value map of the following format:
614 ///
615 /// `input_id: source_node_id/source_node_output_id`
616 ///
617 /// The components are defined as follows:
618 ///
619 /// - `input_id` is the local identifier that should be used for this input.
620 ///
621 /// This will map to the `id` field of
622 /// [`Event::Input`](https://docs.rs/dora-node-api/latest/dora_node_api/enum.Event.html#variant.Input)
623 /// events sent to the node event loop.
624 /// - `source_node_id` should be the `id` field of the node that sends the output that we want
625 /// to subscribe to
626 /// - `source_node_output_id` should be the identifier of the output that that we want
627 /// to subscribe to
628 ///
629 /// ## Example
630 ///
631 /// ```yaml
632 /// nodes:
633 /// - id: example-node
634 /// outputs:
635 /// - one
636 /// - two
637 /// - id: receiver
638 /// inputs:
639 /// my_input: example-node/two
640 /// ```
641 #[serde(default)]
642 // Like `outputs`: an empty `inputs:` is `null`, which deserializes to an empty map.
643 #[schemars(with = "Option<BTreeMap<DataId, Input>>")]
644 pub inputs: BTreeMap<DataId, Input>,
645
646 /// Optional type annotations for inputs.
647 ///
648 /// Maps input identifiers to expected type URNs. Used by `dora validate`
649 /// to check that upstream output types match expectations.
650 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
651 // An empty key is YAML `null`, which deserializes to the default.
652 #[schemars(with = "Option<BTreeMap<DataId, String>>")]
653 pub input_types: BTreeMap<DataId, String>,
654
655 /// Required metadata keys per output.
656 ///
657 /// Maps output identifiers to lists of required metadata key names.
658 /// These are checked at build/validate time.
659 ///
660 /// ## Example
661 ///
662 /// ```yaml
663 /// output_metadata:
664 /// response: [request_id]
665 /// ```
666 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
667 // An empty key is YAML `null`, which deserializes to the default.
668 #[schemars(with = "Option<BTreeMap<DataId, Vec<String>>>")]
669 pub output_metadata: BTreeMap<DataId, Vec<String>>,
670
671 /// Communication pattern shorthand (e.g. `service-server`).
672 ///
673 /// Automatically implies required metadata keys on all outputs.
674 /// See `pattern_metadata_keys()` for supported patterns.
675 #[serde(default, skip_serializing_if = "Option::is_none")]
676 pub pattern: Option<String>,
677
678 /// Redirect stdout/stderr to a data output.
679 ///
680 /// This field can be used to send all stdout and stderr output of the node as a Dora output.
681 /// Each output line is sent as a separate message.
682 ///
683 ///
684 /// ## Example
685 ///
686 /// ```yaml
687 /// nodes:
688 /// - id: example
689 /// send_stdout_as: stdout_output
690 /// - id: logger
691 /// inputs:
692 /// example_output: example/stdout_output
693 /// ```
694 #[serde(skip_serializing_if = "Option::is_none")]
695 pub send_stdout_as: Option<String>,
696
697 /// Redirect structured log entries to a data output as JSON strings.
698 ///
699 /// Unlike `send_stdout_as` which sends raw stdout lines, this sends only
700 /// parsed structured log entries (with level, timestamp, message, fields).
701 ///
702 /// ## Example
703 ///
704 /// ```yaml
705 /// nodes:
706 /// - id: sensor
707 /// path: ./sensor
708 /// send_logs_as: logs
709 /// outputs:
710 /// - data
711 /// - logs
712 /// ```
713 #[serde(skip_serializing_if = "Option::is_none")]
714 pub send_logs_as: Option<String>,
715
716 /// Minimum log level for this node (error, warn, info, debug, trace, stdout).
717 ///
718 /// Logs below this level are suppressed from file output, coordinator
719 /// forwarding, and `send_logs_as` routing.
720 ///
721 /// ## Example
722 ///
723 /// ```yaml
724 /// nodes:
725 /// - id: noisy_sensor
726 /// path: ./sensor
727 /// min_log_level: info
728 /// ```
729 #[serde(skip_serializing_if = "Option::is_none")]
730 pub min_log_level: Option<String>,
731
732 /// Maximum log file size before rotation (e.g. "50MB", "1GB").
733 ///
734 /// When the JSONL log file exceeds this size, it is rotated. Old files
735 /// are renamed with numeric suffixes (`.1.jsonl`, `.2.jsonl`, etc.) and
736 /// the oldest are deleted once 5 rotated files exist.
737 ///
738 /// ## Example
739 ///
740 /// ```yaml
741 /// nodes:
742 /// - id: sensor
743 /// path: ./sensor
744 /// max_log_size: "100MB"
745 /// ```
746 #[serde(skip_serializing_if = "Option::is_none")]
747 pub max_log_size: Option<String>,
748 /// Maximum number of rotated log files to keep (default: 5, range: 0-100)
749 ///
750 /// `0` keeps the active log only, rotating the previous one away.
751 #[serde(default, skip_serializing_if = "Option::is_none")]
752 #[schemars(range(max = 100))]
753 pub max_rotated_files: Option<u32>,
754
755 /// Build commands executed during `dora build`. Each line runs separately.
756 ///
757 /// The `build` key specifies the command that should be invoked for building the node.
758 /// The key expects a single- or multi-line string.
759 ///
760 /// Each line is run as a separate command.
761 /// Spaces are used to separate arguments.
762 ///
763 /// Note that all the environment variables specified in the [`env`](Self::env) field are also
764 /// applied to the build commands.
765 ///
766 /// ## Special treatment of `pip`
767 ///
768 /// Build lines that start with `pip` or `pip3` are treated in a special way:
769 /// If the `--uv` argument is passed to the `dora build` command, all `pip`/`pip3` commands are
770 /// run through the [`uv` package manager](https://docs.astral.sh/uv/).
771 ///
772 /// ## Example
773 ///
774 /// ```yaml
775 /// nodes:
776 /// - id: build-example
777 /// build: cargo build -p receive_data --release
778 /// path: target/release/receive_data
779 /// - id: multi-line-example
780 /// build: |
781 /// pip install requirements.txt
782 /// pip install -e some/local/package
783 /// path: package
784 /// ```
785 ///
786 /// In the above example, the `pip` commands will be replaced by `uv pip` when run through
787 /// `dora build --uv`.
788 #[serde(default, skip_serializing_if = "Option::is_none")]
789 pub build: Option<String>,
790
791 /// Git repository URL for downloading nodes.
792 ///
793 /// The `git` key allows downloading nodes (i.e. their source code) from git repositories.
794 /// This can be especially useful for distributed dataflows.
795 ///
796 /// When a `git` key is specified, `dora build` automatically clones the specified repository
797 /// (or reuse an existing clone).
798 /// Then it checks out the specified [`branch`](Self::branch), [`tag`](Self::tag), or
799 /// [`rev`](Self::rev), or the default branch if none of them are specified.
800 /// Afterwards it runs the [`build`](Self::build) command if specified.
801 ///
802 /// Note that the git clone directory is set as working directory for both the
803 /// [`build`](Self::build) command and the specified [`path`](Self::path).
804 ///
805 /// ## Example
806 ///
807 /// ```yaml
808 /// nodes:
809 /// - id: rust-node
810 /// git: https://github.com/dora-rs/dora.git
811 /// build: cargo build -p rust-dataflow-example-node
812 /// path: target/debug/rust-dataflow-example-node
813 /// ```
814 ///
815 /// In the above example, `dora build` will first clone the specified `git` repository and then
816 /// run the specified `build` inside the local clone directory.
817 /// When `dora run` or `dora start` is invoked, the working directory will be the git clone
818 /// directory too. So a relative `path` will start from the clone directory.
819 #[serde(default, skip_serializing_if = "Option::is_none")]
820 pub git: Option<String>,
821
822 /// Hub package reference.
823 ///
824 /// **Outside the 1.0 stability guarantee.** This field, the way it is
825 /// resolved, and the `HubProvenance` recorded in the lockfile may change
826 /// or be removed in a minor release. `dora build` and `dora validate`
827 /// print a warning whenever a dataflow uses it.
828 ///
829 /// The reason is readiness rather than scope: stabilizing `hub:` would
830 /// promise a typed-contract guarantee that no package in the catalog
831 /// currently delivers. The path to stabilization is the node-typing
832 /// workstream, not more code here — see `docs/plan-node-hub.md` §14 (P3.5).
833 ///
834 /// References a node published in the Dora Hub index:
835 /// `[<namespace>/]<name>@<semver-requirement>`. A bare name is shorthand
836 /// for the official `dora-rs/` namespace.
837 ///
838 /// `dora build` resolves the reference against the index to a pinned
839 /// commit and the node is fetched/built through the same machinery as a
840 /// [`git`](Self::git) node; the package manifest supplies the
841 /// entrypoint, build command, and typed contracts. Mutually exclusive
842 /// with `path`, `git`, and `build`.
843 ///
844 /// ## Example
845 ///
846 /// ```yaml
847 /// nodes:
848 /// - id: detector
849 /// hub: dora-yolo@^0.5
850 /// inputs:
851 /// image: camera/image
852 /// outputs:
853 /// - bbox
854 /// ```
855 #[serde(default, skip_serializing_if = "Option::is_none")]
856 pub hub: Option<String>,
857
858 /// Git branch to checkout after cloning.
859 ///
860 /// The `branch` field is only allowed in combination with the [`git`](#git) field.
861 /// It specifies the branch that should be checked out after cloning.
862 /// Only one of `branch`, `tag`, or `rev` can be specified.
863 ///
864 /// ## Example
865 ///
866 /// ```yaml
867 /// nodes:
868 /// - id: rust-node
869 /// git: https://github.com/dora-rs/dora.git
870 /// branch: some-branch-name
871 /// ```
872 #[serde(default, skip_serializing_if = "Option::is_none")]
873 pub branch: Option<String>,
874
875 /// Git tag to checkout after cloning.
876 ///
877 /// The `tag` field is only allowed in combination with the [`git`](#git) field.
878 /// It specifies the git tag that should be checked out after cloning.
879 /// Only one of `branch`, `tag`, or `rev` can be specified.
880 ///
881 /// ## Example
882 ///
883 /// ```yaml
884 /// nodes:
885 /// - id: rust-node
886 /// git: https://github.com/dora-rs/dora.git
887 /// tag: v0.1.0
888 /// ```
889 #[serde(default, skip_serializing_if = "Option::is_none")]
890 pub tag: Option<String>,
891
892 /// Git revision (e.g. commit hash) to checkout after cloning.
893 ///
894 /// The `rev` field is only allowed in combination with the [`git`](#git) field.
895 /// It specifies the git revision (e.g. a commit hash) that should be checked out after cloning.
896 /// Only one of `branch`, `tag`, or `rev` can be specified.
897 ///
898 /// ## Example
899 ///
900 /// ```yaml
901 /// nodes:
902 /// - id: rust-node
903 /// git: https://github.com/dora-rs/dora.git
904 /// rev: 64ab0d7c
905 /// ```
906 #[serde(default, skip_serializing_if = "Option::is_none")]
907 pub rev: Option<String>,
908
909 /// Whether this node should be restarted on exit or error.
910 ///
911 /// Defaults to `RestartPolicy::Never`.
912 #[serde(default)]
913 pub restart_policy: RestartPolicy,
914
915 /// Size of the zenoh shared memory pool for zero-copy output publishing.
916 ///
917 /// Accepts an integer (raw bytes) or a string with a unit suffix
918 /// (`KB`, `MB`, `GB`, case-insensitive). If unset, the
919 /// `DORA_NODE_SHM_POOL_SIZE` env var is used, falling back to a
920 /// built-in default.
921 ///
922 /// ## Example
923 ///
924 /// ```yaml
925 /// nodes:
926 /// - id: camera-node
927 /// shared_memory_pool_size: 128MB
928 /// ```
929 #[serde(default, skip_serializing_if = "Option::is_none")]
930 pub shared_memory_pool_size: Option<ByteSize>,
931
932 /// Maximum number of restart attempts. 0 means unlimited.
933 ///
934 /// When combined with `restart_window`, this limits restarts within the window period.
935 /// For example, `max_restarts: 5` with `restart_window: 300` means "5 restarts per 5 minutes".
936 #[serde(default)]
937 pub max_restarts: u32,
938
939 /// Initial delay in seconds before restarting. Doubles each attempt (exponential backoff).
940 ///
941 /// For example, with `restart_delay: 1.0`, delays will be 1s, 2s, 4s, 8s, ...
942 /// Use `max_restart_delay` to cap the backoff.
943 #[serde(default, skip_serializing_if = "Option::is_none")]
944 pub restart_delay: Option<f64>,
945
946 /// Maximum delay in seconds for exponential backoff.
947 ///
948 /// Caps the exponentially growing `restart_delay`. For example, with
949 /// `restart_delay: 1.0` and `max_restart_delay: 30.0`, delays grow as
950 /// 1s, 2s, 4s, 8s, 16s, 30s, 30s, ...
951 #[serde(default, skip_serializing_if = "Option::is_none")]
952 pub max_restart_delay: Option<f64>,
953
954 /// Time window in seconds for counting restarts.
955 ///
956 /// When set, the restart counter resets after this period of time elapses since the
957 /// first restart in the current window. This enables "N restarts within M seconds" semantics.
958 #[serde(default, skip_serializing_if = "Option::is_none")]
959 pub restart_window: Option<f64>,
960
961 /// Health check timeout in seconds.
962 ///
963 /// When set, the daemon monitors this node for activity **once it has
964 /// connected** (i.e. subscribed to events during `Node::init`). If the
965 /// connected node then does not communicate with the daemon within this
966 /// timeout, it is killed and the restart policy is evaluated.
967 ///
968 /// This bounds post-connection liveness only, not startup time: a node
969 /// still in a slow cold start has not connected yet and is never killed by
970 /// this watchdog. A node that hangs before it ever subscribes is therefore
971 /// not reaped here either.
972 #[serde(default, skip_serializing_if = "Option::is_none")]
973 pub health_check_timeout: Option<f64>,
974
975 /// Per-node finish-drain grace period in seconds.
976 ///
977 /// Overrides the global `DORA_FINISH_DRAIN_GRACE_SECS` for this node only.
978 /// When all other nodes in a dataflow have finished, the daemon waits this
979 /// long after the node's last input closes before force-stopping it.
980 ///
981 /// Set to a large value (e.g. `3600.0`) for nodes that need significant
982 /// post-input compute time (ML training, large-batch inference, checkpoint
983 /// writes) to prevent premature SIGKILL while the computation is in progress.
984 ///
985 /// When unset, the global grace period applies (default 120s, controlled
986 /// by `DORA_FINISH_DRAIN_GRACE_SECS`).
987 #[serde(default, skip_serializing_if = "Option::is_none")]
988 pub finish_grace_secs: Option<f64>,
989
990 /// Path to a module definition file (e.g. `nav_module.yml`).
991 ///
992 /// A module is a reusable sub-dataflow: a group of nodes with declared
993 /// inputs and outputs. At build time the module is expanded inline —
994 /// internal node IDs are prefixed with `{module_id}.` and all wiring is
995 /// rewritten so the runtime sees only flat nodes.
996 ///
997 /// A module node has no source or per-node runtime configuration of its own,
998 /// so only `module`, `inputs`, `params`, `env`, `build`, and `deploy` are
999 /// meaningful on it. Every other node field is rejected at expansion time
1000 /// rather than silently discarded -- both the source/kind fields (`path`,
1001 /// `args`, `path_sha256`, `git`, `hub`, `branch`, `tag`, `rev`, `operators`,
1002 /// `operator`, `ros2`) and per-node runtime fields (`outputs`,
1003 /// `output_types`, `cpu_affinity`, `restart_policy`, ...). The same rule
1004 /// applies at every nesting level.
1005 ///
1006 /// `env`, `build`, `deploy`, and `params` *are* accepted: they propagate
1007 /// into the module's inner nodes.
1008 ///
1009 /// ## Example
1010 ///
1011 /// ```yaml
1012 /// nodes:
1013 /// - id: nav_stack
1014 /// module: modules/navigation_module.yml
1015 /// inputs:
1016 /// goal_pose: localization/goal
1017 /// ```
1018 #[serde(default, skip_serializing_if = "Option::is_none")]
1019 pub module: Option<String>,
1020
1021 /// Parameters passed to a module for compile-time substitution.
1022 ///
1023 /// Only meaningful when `module` is set. Values are substituted into
1024 /// inner node `args` fields (using `${_param.name}` syntax) and can be
1025 /// injected into inner node `env` maps.
1026 ///
1027 /// ## Example
1028 ///
1029 /// ```yaml
1030 /// nodes:
1031 /// - id: nav_stack
1032 /// module: modules/navigation_module.yml
1033 /// params:
1034 /// speed: "2.0"
1035 /// mode: turbo
1036 /// ```
1037 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1038 // An empty key is YAML `null`, which deserializes to the default.
1039 #[schemars(with = "Option<BTreeMap<String, String>>")]
1040 pub params: BTreeMap<String, String>,
1041
1042 /// CPU cores to pin this node's process to (Linux only, ignored on other platforms).
1043 ///
1044 /// ## Example
1045 ///
1046 /// ```yaml
1047 /// nodes:
1048 /// - id: fast_node
1049 /// path: ./fast_node
1050 /// cpu_affinity: [0, 1]
1051 /// ```
1052 #[serde(default, skip_serializing_if = "Option::is_none")]
1053 pub cpu_affinity: Option<Vec<usize>>,
1054
1055 /// Machine deployment configuration.
1056 pub deploy: Option<Deploy>,
1057
1058 /// Startup connection deadline in seconds.
1059 ///
1060 /// If the node process fails to connect (subscribe to events) within this
1061 /// many seconds after process spawn, the daemon kills the process and
1062 /// evaluates the `restart_policy`.
1063 ///
1064 /// Evaluated on each `health_check_interval` tick (default 5s).
1065 #[serde(default, skip_serializing_if = "Option::is_none")]
1066 pub startup_timeout: Option<f64>,
1067
1068 /// What to run when nothing exists at `path`, looked up like a top-level
1069 /// `path` (working directory, uv environment, then `$PATH`; variables
1070 /// are not expanded). Internal: module expansion sets it when a module
1071 /// node's `path` is a single name without an extension, such as
1072 /// `dora-echo`: `path` points next to the module file, and this keeps
1073 /// the name as written. One written in a dataflow, module or node file is
1074 /// rejected, so it is not part of the YAML schema.
1075 // Appended last so existing fields keep their wire-format order.
1076 #[serde(default, skip_serializing_if = "Option::is_none")]
1077 #[schemars(skip)]
1078 #[doc(hidden)]
1079 pub path_fallback: Option<String>,
1080}
1081
1082impl Node {
1083 /// A node with the given ID and every other field left at its descriptor
1084 /// default (the state a YAML node with only an `id:` key deserializes to).
1085 ///
1086 /// `Node` is `#[non_exhaustive]`, so other crates cannot build one with a
1087 /// struct literal. Start here and assign the fields you need — they are all
1088 /// still `pub`:
1089 ///
1090 /// ```
1091 /// use dora_message::descriptor::Node;
1092 ///
1093 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1094 /// let mut node = Node::new("camera".parse()?);
1095 /// node.path = Some("./camera".to_owned());
1096 /// # Ok(())
1097 /// # }
1098 /// ```
1099 pub fn new(id: NodeId) -> Self {
1100 Self {
1101 id,
1102 name: None,
1103 description: None,
1104 path: None,
1105 path_sha256: None,
1106 args: None,
1107 env: None,
1108 operators: None,
1109 operator: None,
1110 ros2: None,
1111 outputs: Default::default(),
1112 output_types: Default::default(),
1113 output_framing: Default::default(),
1114 inputs: Default::default(),
1115 input_types: Default::default(),
1116 shared_memory_pool_size: None,
1117 output_metadata: Default::default(),
1118 pattern: None,
1119 send_stdout_as: None,
1120 send_logs_as: None,
1121 min_log_level: None,
1122 max_log_size: None,
1123 max_rotated_files: None,
1124 build: None,
1125 git: None,
1126 hub: None,
1127 branch: None,
1128 tag: None,
1129 rev: None,
1130 restart_policy: Default::default(),
1131 max_restarts: 0,
1132 restart_delay: None,
1133 max_restart_delay: None,
1134 restart_window: None,
1135 health_check_timeout: None,
1136 finish_grace_secs: None,
1137 module: None,
1138 params: Default::default(),
1139 cpu_affinity: None,
1140 deploy: None,
1141 startup_timeout: None,
1142 path_fallback: None,
1143 }
1144 }
1145}
1146
1147/// A [`Node`] after alias resolution and defaulting, as the daemon runs it.
1148#[allow(missing_docs)]
1149#[derive(Debug, Clone, Serialize, Deserialize)]
1150// Same rationale as `Node`: keeps a new per-node key a minor release. This is
1151// where keys that are not custom-node-specific land — `cpu_affinity` and
1152// `deploy` are threaded `Node` -> `ResolvedNode` without passing through
1153// `CustomNode`. Construct with `ResolvedNode::new`; the fields remain `pub`.
1154// Resolution itself goes through `ResolvedNode::from_node`, the in-crate
1155// literal that keeps a new field a compile error.
1156#[non_exhaustive]
1157pub struct ResolvedNode {
1158 pub id: NodeId,
1159 pub name: Option<String>,
1160 pub description: Option<String>,
1161 pub env: Option<BTreeMap<String, EnvValue>>,
1162
1163 #[serde(default)]
1164 pub cpu_affinity: Option<Vec<usize>>,
1165
1166 #[serde(default)]
1167 pub deploy: Option<Deploy>,
1168
1169 #[serde(flatten)]
1170 pub kind: CoreNodeKind,
1171}
1172
1173#[allow(missing_docs)]
1174impl ResolvedNode {
1175 /// A resolved node with the given ID and kind, and every other field left
1176 /// at its default.
1177 ///
1178 /// `ResolvedNode` is `#[non_exhaustive]`, so other crates cannot build one
1179 /// with a struct literal. Start here and assign the fields you need — they
1180 /// are all still `pub`.
1181 pub fn new(id: NodeId, kind: CoreNodeKind) -> Self {
1182 Self {
1183 id,
1184 name: None,
1185 description: None,
1186 env: None,
1187 cpu_affinity: None,
1188 deploy: None,
1189 kind,
1190 }
1191 }
1192
1193 /// The resolved node for `node`'s node-level keys — `id`, `name`,
1194 /// `description`, `env`, `cpu_affinity`, `deploy` — around an already
1195 /// resolved `kind`. `env` is carried as declared; merging the
1196 /// dataflow-level `env` into it is the caller's job.
1197 ///
1198 /// The kind-level keys are dropped: for a custom node
1199 /// [`CustomNode::from_node`] has already moved them out, and a runtime
1200 /// node's live in its `operators`.
1201 ///
1202 /// This is a struct literal on purpose. `ResolvedNode` is
1203 /// `#[non_exhaustive]`, so a literal only compiles here, inside the
1204 /// defining crate — exactly where the compiler still insists that every
1205 /// field is accounted for. A field added to `ResolvedNode` is a build
1206 /// error on this line, not a key that resolution silently leaves at its
1207 /// default.
1208 pub fn from_node(node: Node, kind: CoreNodeKind) -> Self {
1209 Self {
1210 id: node.id,
1211 name: node.name,
1212 description: node.description,
1213 env: node.env,
1214 cpu_affinity: node.cpu_affinity,
1215 deploy: node.deploy,
1216 kind,
1217 }
1218 }
1219
1220 pub fn has_git_source(&self) -> bool {
1221 self.kind
1222 .as_custom()
1223 .map(|n| n.source.is_git())
1224 .unwrap_or_default()
1225 }
1226}
1227
1228#[allow(missing_docs)]
1229#[derive(Debug, Clone, Serialize, Deserialize)]
1230#[serde(rename_all = "lowercase")]
1231#[allow(clippy::large_enum_variant)]
1232pub enum CoreNodeKind {
1233 /// Dora runtime node
1234 #[serde(rename = "operators")]
1235 Runtime(RuntimeNode),
1236 Custom(CustomNode),
1237}
1238
1239#[allow(missing_docs)]
1240impl CoreNodeKind {
1241 pub fn as_custom(&self) -> Option<&CustomNode> {
1242 match self {
1243 CoreNodeKind::Runtime(_) => None,
1244 CoreNodeKind::Custom(custom_node) => Some(custom_node),
1245 }
1246 }
1247}
1248
1249#[allow(missing_docs)]
1250#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1251#[serde(transparent)]
1252pub struct RuntimeNode {
1253 /// List of operators running in this runtime
1254 pub operators: Vec<OperatorDefinition>,
1255}
1256
1257#[allow(missing_docs)]
1258#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
1259pub struct OperatorDefinition {
1260 /// Unique operator identifier within the runtime
1261 pub id: OperatorId,
1262 #[serde(flatten)]
1263 pub config: OperatorConfig,
1264}
1265
1266#[allow(missing_docs)]
1267#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
1268// Same rationale as `Node`: keeps a new operator-level descriptor key a minor
1269// release. No constructor yet because nothing constructs one outside this crate
1270// — every instance comes from deserialization. Adding a constructor later is
1271// itself a minor change, so only the `#[non_exhaustive]` half is time-critical;
1272// open an issue if you need to build one programmatically.
1273#[non_exhaustive]
1274pub struct SingleOperatorDefinition {
1275 /// Operator identifier (optional for single operators)
1276 pub id: Option<OperatorId>,
1277 #[serde(flatten)]
1278 pub config: OperatorConfig,
1279}
1280
1281#[allow(missing_docs)]
1282#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
1283// Same rationale as `Node`: keeps a new operator-level descriptor key a minor
1284// release. No constructor yet because nothing constructs one outside this crate
1285// — every instance comes from deserialization. Adding a constructor later is
1286// itself a minor change, so only the `#[non_exhaustive]` half is time-critical;
1287// open an issue if you need to build one programmatically.
1288//
1289// Kept as a `//` comment deliberately: a `///` doc here is `#[serde(flatten)]`ed
1290// by schemars onto `OperatorDefinition`'s entry in `dora-schema.json`, which
1291// YAML editors show to dataflow authors.
1292#[non_exhaustive]
1293pub struct OperatorConfig {
1294 /// Human-readable operator name
1295 pub name: Option<String>,
1296 /// Detailed description of the operator
1297 pub description: Option<String>,
1298
1299 /// Input data connections
1300 // Unlike on `Node`, an empty key here is rejected: `OperatorConfig` is
1301 // `#[serde(flatten)]`ed, and flattened fields don't turn `null` into an
1302 // empty collection. So the schema keeps requiring an object/array.
1303 #[serde(default)]
1304 pub inputs: BTreeMap<DataId, Input>,
1305 /// Output data identifiers
1306 #[serde(default)]
1307 pub outputs: BTreeSet<DataId>,
1308 /// Optional type annotations for outputs
1309 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1310 pub output_types: BTreeMap<DataId, String>,
1311
1312 /// Per-output framing overrides. Ignored: every output is encoded as
1313 /// Arrow IPC (see [`OutputFraming`]).
1314 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1315 pub output_framing: BTreeMap<DataId, OutputFraming>,
1316
1317 /// Optional type annotations for inputs
1318 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1319 pub input_types: BTreeMap<DataId, String>,
1320
1321 /// Required metadata keys per output
1322 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1323 pub output_metadata: BTreeMap<DataId, Vec<String>>,
1324
1325 /// Communication pattern shorthand (e.g. `service-server`)
1326 #[serde(default, skip_serializing_if = "Option::is_none")]
1327 pub pattern: Option<String>,
1328
1329 /// Operator source configuration (Python, shared library, etc.)
1330 #[serde(flatten)]
1331 pub source: OperatorSource,
1332
1333 /// Build commands for this operator
1334 #[serde(default, skip_serializing_if = "Option::is_none")]
1335 pub build: Option<String>,
1336 /// Redirect stdout to data output
1337 #[serde(skip_serializing_if = "Option::is_none")]
1338 pub send_stdout_as: Option<String>,
1339 /// Redirect structured log entries to a data output as JSON strings
1340 #[serde(skip_serializing_if = "Option::is_none")]
1341 pub send_logs_as: Option<String>,
1342 /// Minimum log level for this operator
1343 #[serde(skip_serializing_if = "Option::is_none")]
1344 pub min_log_level: Option<String>,
1345 /// Maximum log file size before rotation (e.g. "50MB", "1GB")
1346 #[serde(skip_serializing_if = "Option::is_none")]
1347 pub max_log_size: Option<String>,
1348 /// Maximum number of rotated log files to keep (default: 5, range: 0-100)
1349 ///
1350 /// `0` keeps the active log only, rotating the previous one away.
1351 #[serde(default, skip_serializing_if = "Option::is_none")]
1352 #[schemars(range(max = 100))]
1353 pub max_rotated_files: Option<u32>,
1354}
1355
1356#[allow(missing_docs)]
1357#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
1358#[serde(rename_all = "kebab-case")]
1359pub enum OperatorSource {
1360 SharedLibrary(String),
1361 Python(PythonSource),
1362 #[schemars(skip)]
1363 Wasm(String),
1364}
1365#[allow(missing_docs)]
1366#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1367#[serde(from = "PythonSourceDef", into = "PythonSourceDef")]
1368pub struct PythonSource {
1369 pub source: String,
1370 pub conda_env: Option<String>,
1371}
1372
1373#[allow(missing_docs)]
1374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1375#[serde(untagged)]
1376pub enum PythonSourceDef {
1377 SourceOnly(String),
1378 WithOptions {
1379 source: String,
1380 conda_env: Option<String>,
1381 },
1382}
1383
1384impl From<PythonSource> for PythonSourceDef {
1385 fn from(input: PythonSource) -> Self {
1386 match input {
1387 PythonSource {
1388 source,
1389 conda_env: None,
1390 } => Self::SourceOnly(source),
1391 PythonSource { source, conda_env } => Self::WithOptions { source, conda_env },
1392 }
1393 }
1394}
1395
1396impl From<PythonSourceDef> for PythonSource {
1397 fn from(value: PythonSourceDef) -> Self {
1398 match value {
1399 PythonSourceDef::SourceOnly(source) => Self {
1400 source,
1401 conda_env: None,
1402 },
1403 PythonSourceDef::WithOptions { source, conda_env } => Self { source, conda_env },
1404 }
1405 }
1406}
1407
1408/// Built-in runtime name for shared-library operators.
1409pub const RUNTIME_SHARED_LIBRARY: &str = "shared-library";
1410/// Built-in runtime name for Python operators.
1411pub const RUNTIME_PYTHON: &str = "python";
1412/// Built-in runtime name for WebAssembly operators.
1413pub const RUNTIME_WASM: &str = "wasm";
1414
1415impl OperatorSource {
1416 /// The name of the runtime that hosts operators declared with this source.
1417 ///
1418 /// This mapping is the single source of truth for "which runtime hosts this
1419 /// operator": the daemon's spawn logic and the CLI's build hashing key on
1420 /// the name rather than matching each variant.
1421 pub fn runtime_name(&self) -> &'static str {
1422 match self {
1423 OperatorSource::SharedLibrary(_) => RUNTIME_SHARED_LIBRARY,
1424 OperatorSource::Python(_) => RUNTIME_PYTHON,
1425 OperatorSource::Wasm(_) => RUNTIME_WASM,
1426 }
1427 }
1428}
1429
1430#[allow(missing_docs)]
1431#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1432// See the note on `Node`: keeps a new resolved-node field a minor release.
1433// Construct with `CustomNode::new`; the fields remain `pub`. Resolution goes
1434// through `CustomNode::from_node`, the in-crate literal that keeps a new field
1435// a compile error rather than a silently dropped descriptor key.
1436#[non_exhaustive]
1437pub struct CustomNode {
1438 /// Path of the source code
1439 ///
1440 /// If you want to use a specific `conda` environment.
1441 /// Provide the python path within the source.
1442 ///
1443 /// source: /home/peter/miniconda3/bin/python
1444 ///
1445 /// args: some_node.py
1446 ///
1447 /// Source can match any executable in PATH.
1448 pub path: String,
1449 pub source: NodeSource,
1450 /// SHA-256 the `path` download must match (set for hub binary artifacts,
1451 /// spec §8.2). When present the daemon fetches `path` as a verified URL
1452 /// download regardless of confinement — the checksum is the trust anchor.
1453 #[serde(default, skip_serializing_if = "Option::is_none")]
1454 pub path_sha256: Option<String>,
1455 /// Args for the executable.
1456 #[serde(default, skip_serializing_if = "Option::is_none")]
1457 pub args: Option<String>,
1458 /// Environment variables injected during resolution.
1459 ///
1460 /// Not user-writable: [`Node::env`] is the YAML surface. Resolution folds
1461 /// it into this field, and the ROS2 bridge desugaring uses it to pass
1462 /// `DORA_ROS2_BRIDGE_CONFIG` to the spawned bridge binary.
1463 pub envs: Option<BTreeMap<String, EnvValue>>,
1464 #[serde(default, skip_serializing_if = "Option::is_none")]
1465 pub build: Option<String>,
1466 /// Send stdout and stderr to another node
1467 #[serde(skip_serializing_if = "Option::is_none")]
1468 pub send_stdout_as: Option<String>,
1469 /// Redirect structured log entries to a data output as JSON strings
1470 #[serde(skip_serializing_if = "Option::is_none")]
1471 pub send_logs_as: Option<String>,
1472 /// Minimum log level for this node
1473 #[serde(skip_serializing_if = "Option::is_none")]
1474 pub min_log_level: Option<String>,
1475 /// Maximum log file size before rotation (e.g. "50MB", "1GB")
1476 #[serde(skip_serializing_if = "Option::is_none")]
1477 pub max_log_size: Option<String>,
1478 /// Maximum number of rotated log files to keep (default: 5, range: 0-100)
1479 ///
1480 /// `0` keeps the active log only, rotating the previous one away.
1481 #[serde(default, skip_serializing_if = "Option::is_none")]
1482 #[schemars(range(max = 100))]
1483 pub max_rotated_files: Option<u32>,
1484
1485 #[serde(default)]
1486 pub restart_policy: RestartPolicy,
1487
1488 /// Maximum number of restart attempts. 0 means unlimited.
1489 #[serde(default)]
1490 pub max_restarts: u32,
1491
1492 /// Initial delay in seconds before restarting (exponential backoff).
1493 #[serde(default, skip_serializing_if = "Option::is_none")]
1494 pub restart_delay: Option<f64>,
1495
1496 /// Maximum delay in seconds for exponential backoff.
1497 #[serde(default, skip_serializing_if = "Option::is_none")]
1498 pub max_restart_delay: Option<f64>,
1499
1500 /// Time window in seconds for counting restarts.
1501 #[serde(default, skip_serializing_if = "Option::is_none")]
1502 pub restart_window: Option<f64>,
1503
1504 /// Health check timeout in seconds.
1505 ///
1506 /// When set, the daemon monitors this node for activity **once it has
1507 /// connected** (i.e. subscribed to events during `Node::init`). If the
1508 /// connected node then does not communicate with the daemon within this
1509 /// timeout, it is killed and the restart policy is evaluated.
1510 ///
1511 /// This bounds post-connection liveness only, not startup time: a node
1512 /// still in a slow cold start has not connected yet and is never killed by
1513 /// this watchdog. A node that hangs before it ever subscribes is therefore
1514 /// not reaped here either.
1515 #[serde(default, skip_serializing_if = "Option::is_none")]
1516 pub health_check_timeout: Option<f64>,
1517
1518 /// Per-node finish-drain grace period in seconds.
1519 ///
1520 /// Overrides the global `DORA_FINISH_DRAIN_GRACE_SECS` for this node only.
1521 #[serde(default, skip_serializing_if = "Option::is_none")]
1522 pub finish_grace_secs: Option<f64>,
1523
1524 #[serde(flatten)]
1525 pub run_config: NodeRunConfig,
1526
1527 /// Startup connection deadline in seconds.
1528 ///
1529 /// If the node process fails to connect (subscribe to events) within this
1530 /// many seconds after process spawn, the daemon kills the process and
1531 /// evaluates the `restart_policy`.
1532 ///
1533 /// Evaluated on each `health_check_interval` tick (default 5s).
1534 // Appended last so existing fields keep their wire-format order.
1535 #[serde(default, skip_serializing_if = "Option::is_none")]
1536 pub startup_timeout: Option<f64>,
1537 /// What to run when nothing exists at `path`, resolved like a top-level
1538 /// `path` (the name a module node's `path:` was written as).
1539 // Appended last so existing fields keep their wire-format order.
1540 #[serde(default, skip_serializing_if = "Option::is_none")]
1541 pub path_fallback: Option<String>,
1542}
1543
1544impl CustomNode {
1545 /// A local-source node at `path` with every other field left at its
1546 /// default.
1547 ///
1548 /// `CustomNode` is `#[non_exhaustive]`, so other crates cannot build one
1549 /// with a struct literal. Start here and assign the fields you need — they
1550 /// are all still `pub`.
1551 pub fn new(path: String) -> Self {
1552 Self {
1553 path,
1554 source: NodeSource::Local,
1555 path_sha256: None,
1556 args: None,
1557 envs: None,
1558 build: None,
1559 send_stdout_as: None,
1560 send_logs_as: None,
1561 min_log_level: None,
1562 max_log_size: None,
1563 max_rotated_files: None,
1564 restart_policy: Default::default(),
1565 max_restarts: 0,
1566 restart_delay: None,
1567 max_restart_delay: None,
1568 restart_window: None,
1569 health_check_timeout: None,
1570 finish_grace_secs: None,
1571 run_config: NodeRunConfig::default(),
1572 startup_timeout: None,
1573 path_fallback: None,
1574 }
1575 }
1576
1577 /// Move the custom-node keys out of `node` into a `CustomNode` at `path`.
1578 ///
1579 /// Every key that all custom-node kinds resolve identically is taken from
1580 /// `node`, leaving its `Option`s empty and its collections cleared. What
1581 /// stays behind are the node-level keys — `id`, `name`, `description`,
1582 /// `env`, `cpu_affinity`, `deploy` — for [`ResolvedNode::from_node`] to
1583 /// consume next, plus the kind-selection keys (`git`, `hub`, `operators`,
1584 /// `ros2`, …) that classification has already read.
1585 ///
1586 /// `source` and `envs` stay at their defaults: they are the two keys whose
1587 /// value depends on the node kind, so the caller sets them — `source` from
1588 /// classification for a `path:` node, `envs` for the ROS2 bridge, whose
1589 /// `path` is its fixed binary.
1590 ///
1591 /// This is a struct literal on purpose. `CustomNode` and `NodeRunConfig`
1592 /// are `#[non_exhaustive]`, so a literal only compiles here, inside the
1593 /// defining crate — exactly where the compiler still insists that every
1594 /// field is accounted for. A key added to either struct is a build error
1595 /// on this line, not a descriptor key that parses and is then silently
1596 /// dropped. `dora-core`'s `every_custom_node_field_is_carried_through`
1597 /// checks the values on top.
1598 pub fn from_node(node: &mut Node, path: String) -> Self {
1599 Self {
1600 path,
1601 source: NodeSource::Local,
1602 path_sha256: node.path_sha256.take(),
1603 args: node.args.take(),
1604 envs: None,
1605 build: node.build.take(),
1606 send_stdout_as: node.send_stdout_as.take(),
1607 send_logs_as: node.send_logs_as.take(),
1608 min_log_level: node.min_log_level.take(),
1609 max_log_size: node.max_log_size.take(),
1610 max_rotated_files: node.max_rotated_files.take(),
1611 restart_policy: node.restart_policy,
1612 max_restarts: node.max_restarts,
1613 restart_delay: node.restart_delay.take(),
1614 max_restart_delay: node.max_restart_delay.take(),
1615 restart_window: node.restart_window.take(),
1616 health_check_timeout: node.health_check_timeout.take(),
1617 finish_grace_secs: node.finish_grace_secs.take(),
1618 run_config: NodeRunConfig {
1619 inputs: std::mem::take(&mut node.inputs),
1620 outputs: std::mem::take(&mut node.outputs),
1621 output_types: std::mem::take(&mut node.output_types),
1622 output_framing: std::mem::take(&mut node.output_framing),
1623 input_types: std::mem::take(&mut node.input_types),
1624 shared_memory_pool_size: node.shared_memory_pool_size.take(),
1625 },
1626 startup_timeout: node.startup_timeout.take(),
1627 path_fallback: node.path_fallback.take(),
1628 }
1629 }
1630}
1631
1632#[allow(missing_docs)]
1633#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1634pub enum NodeSource {
1635 Local,
1636 GitBranch {
1637 repo: String,
1638 rev: Option<GitRepoRev>,
1639 },
1640}
1641
1642#[allow(missing_docs)]
1643impl NodeSource {
1644 pub fn is_git(&self) -> bool {
1645 matches!(self, Self::GitBranch { .. })
1646 }
1647}
1648
1649#[allow(missing_docs)]
1650#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1651pub enum GitRepoRev {
1652 Branch(String),
1653 Tag(String),
1654 Rev(String),
1655}
1656
1657// The value of an `env:` entry. (A plain comment, not a doc comment:
1658// schemars would publish a doc comment as the `EnvValue` description in
1659// `dora-schema.json`.)
1660//
1661// A native YAML/JSON bool or number keeps its type, except an integer
1662// in `i64::MAX + 1 ..= u64::MAX`, which keeps its exact digits as a string.
1663// An integer outside `i64::MIN ..= u64::MAX` is a parse error in YAML, but
1664// serde_json hands it over as an `f64`, so a JSON descriptor still rounds it
1665// (the CLI -> coordinator -> daemon hops are unaffected: by then such a value
1666// is already a string). Quote it to keep it exact. A string has its
1667// `$VAR` / `${VAR}` references expanded and is then typed as a bool or
1668// number only when that is lossless, i.e. when the typed value prints
1669// back as exactly the same text. `"8080"` and `${PORT}` (= 8080) still
1670// become `Integer(8080)`, as in every 1.x release, but `"1.10"`, `"007"`
1671// and `"1e3"` stay strings instead of reaching the node as `1.1`, `7` and
1672// `1000`.
1673//
1674// The expansion happens on every decode, and the descriptor is decoded
1675// once per hop (CLI -> coordinator -> daemon -> node, the coordinator's
1676// persisted store, the CLI's hub session file, and any future one). So a
1677// string is serialized with each `$` written as `$$`, which the next decode
1678// turns back into `$`: the value the CLI expanded reaches the node verbatim
1679// instead of being expanded again against the receiving host's environment
1680// (#3947). Released 1.x peers decode that the same way.
1681//
1682// Escaping here, unconditionally, rather than only at the specific places
1683// that happen to send a `Descriptor` across a hop today, is deliberate:
1684// every encode is then safe by construction, and a new hop added later does
1685// not need to remember to opt in. The cost is that the three places that
1686// serialize an already-decoded `Descriptor` straight to user code and never
1687// decode it back — the Python node's `dataflow_descriptor()`, a Python
1688// operator's `self.dataflow_descriptor`, the C++ `dataflow_descriptor_json`
1689// — see the escaped form too. Each of those undoes it with
1690// `descriptor_for_display` below rather than this type gaining an unescaped
1691// mode (#4067).
1692#[allow(missing_docs)]
1693#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
1694#[serde(untagged)]
1695pub enum EnvValue {
1696 Bool(bool),
1697 Integer(i64),
1698 Float(f64),
1699 #[serde(serialize_with = "serialize_escaping_dollars")]
1700 String(String),
1701}
1702
1703/// `s` with each `$` written as `$$`, which is what `$` expands from, so the
1704/// next decode restores `s`.
1705fn serialize_escaping_dollars<S: serde::Serializer>(
1706 s: &str,
1707 serializer: S,
1708) -> Result<S::Ok, S::Error> {
1709 if s.contains('$') {
1710 serializer.serialize_str(&s.replace('$', "$$"))
1711 } else {
1712 serializer.serialize_str(s)
1713 }
1714}
1715
1716/// `descriptor` as the three introspection points hand it to user code:
1717/// `Node.dataflow_descriptor()` (Python), a Python operator's
1718/// `self.dataflow_descriptor`, and the C++ `dataflow_descriptor_json`.
1719///
1720/// Serializing a `Descriptor` directly always escapes `$` as `$$` in every
1721/// `env` string (see the comment on `EnvValue`), because the same
1722/// `Serialize` impl is also how a `Descriptor` crosses a dora-to-dora wire
1723/// hop. These three callers serialize the same, already-decoded
1724/// `Descriptor` with no decode step after to undo that, so without this
1725/// they would show the wire form instead of the real value (#4067). This
1726/// walks only the two places `env` actually appears — `descriptor.env` and
1727/// each node's `env` — rather than unescaping the whole serialized tree,
1728/// so an unrelated string that happens to contain `$$` (a `build:` command,
1729/// a description, ...) is left alone.
1730///
1731/// Returns the serialize error rather than unwrapping it: these callers run
1732/// at an FFI boundary (the C++ `dataflow_descriptor_json`, pyo3), where a
1733/// panic is undefined behaviour, and the originals already returned a
1734/// fallible result here.
1735pub fn descriptor_for_display(
1736 descriptor: &Descriptor,
1737) -> Result<serde_json::Value, serde_json::Error> {
1738 let mut value = serde_json::to_value(descriptor)?;
1739 if let Some(env) = value.get_mut("env") {
1740 unescape_json_env_map(env);
1741 }
1742 if let Some(nodes) = value
1743 .get_mut("nodes")
1744 .and_then(|nodes| nodes.as_array_mut())
1745 {
1746 for node in nodes {
1747 if let Some(env) = node.get_mut("env") {
1748 unescape_json_env_map(env);
1749 }
1750 }
1751 }
1752 Ok(value)
1753}
1754
1755/// Undoes [`serialize_escaping_dollars`] on every string value of a JSON
1756/// object already known to be one `env:` map, in place.
1757fn unescape_json_env_map(env: &mut serde_json::Value) {
1758 if let Some(map) = env.as_object_mut() {
1759 for value in map.values_mut() {
1760 if let serde_json::Value::String(s) = value {
1761 *s = s.replace("$$", "$");
1762 }
1763 }
1764 }
1765}
1766
1767thread_local! {
1768 static MODULE_DIR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
1769}
1770
1771/// Decode a module from the original YAML, resolving `$MODULE_DIR` in its
1772/// environment strings alongside ordinary host variables.
1773#[doc(hidden)]
1774pub fn deserialize_module_yaml<'de, T: Deserialize<'de>>(
1775 yaml: &'de [u8],
1776 module_dir: &str,
1777) -> Result<T, serde_yaml::Error> {
1778 // Serde's nested EnvValue visitor has no context parameter. Confine the
1779 // override to this synchronous decode, including nesting and unwinding.
1780 struct Restore(Option<String>);
1781 impl Drop for Restore {
1782 fn drop(&mut self) {
1783 MODULE_DIR.replace(self.0.take());
1784 }
1785 }
1786 let _restore = Restore(MODULE_DIR.replace(Some(module_dir.to_owned())));
1787 serde_yaml::from_slice(yaml)
1788}
1789
1790fn expand_env_value<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
1791 let raw = String::deserialize(de)?;
1792 MODULE_DIR.with_borrow(|dir| {
1793 shellexpand::env_with_context(&raw, |name| {
1794 if name == "MODULE_DIR"
1795 && let Some(dir) = dir
1796 {
1797 return Ok(Some(dir.clone()));
1798 }
1799 std::env::var(name).map(Some)
1800 })
1801 .map(|value| value.into_owned())
1802 .map_err(serde::de::Error::custom)
1803 })
1804}
1805
1806impl<'de> Deserialize<'de> for EnvValue {
1807 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1808 #[derive(Deserialize)]
1809 #[serde(untagged)]
1810 enum Raw {
1811 Bool(bool),
1812 Integer(i64),
1813 // Before `Float`, which would round it to the nearest `f64`.
1814 Unsigned(u64),
1815 Float(f64),
1816 #[serde(deserialize_with = "expand_env_value")]
1817 String(String),
1818 }
1819 Ok(match Raw::deserialize(deserializer)? {
1820 Raw::Bool(b) => EnvValue::Bool(b),
1821 Raw::Integer(i) => EnvValue::Integer(i),
1822 // Above `i64::MAX`, so `Integer` cannot hold it: keep its digits.
1823 Raw::Unsigned(u) => EnvValue::String(u.to_string()),
1824 Raw::Float(f) if f.is_finite() => EnvValue::Float(f),
1825 // A non-finite native float (`.inf`, `.nan`, or a literal such as
1826 // `1e400` that overflows): JSON has no encoding for it (serde_json
1827 // writes `null`), so a `Float` would not survive the CLI ->
1828 // coordinator hop. Keep the text that `Float` prints as (`inf`,
1829 // `-inf`, `NaN`), i.e. what the node's env var would have held.
1830 Raw::Float(f) => EnvValue::String(f.to_string()),
1831 Raw::String(s) => EnvValue::from_string_lossless(s),
1832 })
1833 }
1834}
1835
1836impl EnvValue {
1837 /// Type `s` as a bool or number if that prints back as exactly `s`,
1838 /// and keep it a string otherwise. `inf` and `NaN` stay strings: JSON
1839 /// has no encoding for a non-finite float (serde_json writes `null`),
1840 /// so the descriptor would not survive the coordinator -> daemon hop.
1841 fn from_string_lossless(s: String) -> Self {
1842 let typed = if let Ok(b) = s.parse() {
1843 EnvValue::Bool(b)
1844 } else if let Ok(i) = s.parse() {
1845 EnvValue::Integer(i)
1846 } else if let Ok(f) = s.parse::<f64>()
1847 && f.is_finite()
1848 {
1849 EnvValue::Float(f)
1850 } else {
1851 return EnvValue::String(s);
1852 };
1853 if typed.to_string() == s {
1854 typed
1855 } else {
1856 EnvValue::String(s)
1857 }
1858 }
1859}
1860
1861impl fmt::Display for EnvValue {
1862 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1863 match self {
1864 EnvValue::Bool(bool) => fmt.write_str(&bool.to_string()),
1865 EnvValue::Integer(i64) => fmt.write_str(&i64.to_string()),
1866 EnvValue::Float(f64) => fmt.write_str(&f64.to_string()),
1867 EnvValue::String(str) => fmt.write_str(str),
1868 }
1869 }
1870}
1871
1872/// ROS2 bridge configuration for declarative ROS2 bridging.
1873///
1874/// This allows nodes to interact with ROS2 topics, services, and actions
1875/// without writing any custom code. The framework spawns a bridge binary that
1876/// handles the ROS2 DDS communication and Arrow data conversion.
1877///
1878/// Exactly one of `topic`, `topics`, `service`, or `action` must be set.
1879#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1880#[serde(deny_unknown_fields)]
1881pub struct Ros2BridgeConfig {
1882 /// Native transport used to communicate with the ROS2 graph.
1883 ///
1884 /// Defaults to the existing DDS implementation.
1885 #[serde(default)]
1886 pub transport: Ros2TransportConfig,
1887
1888 /// ROS2 topic name (e.g. "/camera/image_raw").
1889 /// Mutually exclusive with `topics`, `service`, `action`.
1890 #[serde(default, skip_serializing_if = "Option::is_none")]
1891 pub topic: Option<String>,
1892
1893 /// ROS2 message type (e.g. "sensor_msgs/Image").
1894 /// Required when `topic` is set.
1895 #[serde(default, skip_serializing_if = "Option::is_none")]
1896 pub message_type: Option<String>,
1897
1898 /// Direction: subscribe (ROS2 -> Dora) or publish (Dora -> ROS2).
1899 /// Defaults to subscribe. Only used with `topic`/`topics`.
1900 #[serde(default)]
1901 pub direction: Ros2Direction,
1902
1903 /// Multiple topics on a single ROS2 node context.
1904 /// Mutually exclusive with `topic`, `service`, `action`.
1905 #[serde(default, skip_serializing_if = "Option::is_none")]
1906 pub topics: Option<Vec<Ros2TopicConfig>>,
1907
1908 /// ROS2 service name (e.g. "/add_two_ints").
1909 /// Mutually exclusive with `topic`, `topics`, `action`.
1910 #[serde(default, skip_serializing_if = "Option::is_none")]
1911 pub service: Option<String>,
1912
1913 /// ROS2 service type (e.g. "example_interfaces/AddTwoInts").
1914 /// Required when `service` is set.
1915 #[serde(default, skip_serializing_if = "Option::is_none")]
1916 pub service_type: Option<String>,
1917
1918 /// ROS2 action name (e.g. "/navigate").
1919 /// Mutually exclusive with `topic`, `topics`, `service`.
1920 #[serde(default, skip_serializing_if = "Option::is_none")]
1921 pub action: Option<String>,
1922
1923 /// ROS2 action type (e.g. "nav2_msgs/NavigateToPose").
1924 /// Required when `action` is set.
1925 #[serde(default, skip_serializing_if = "Option::is_none")]
1926 pub action_type: Option<String>,
1927
1928 /// Role: client or server. Required for `service` and `action`.
1929 #[serde(default, skip_serializing_if = "Option::is_none")]
1930 pub role: Option<Ros2Role>,
1931
1932 /// QoS policies applied to all topics (can be overridden per-topic).
1933 #[serde(default)]
1934 // An empty key is YAML `null`, which deserializes to the default.
1935 #[schemars(with = "Option<Ros2QosConfig>")]
1936 pub qos: Ros2QosConfig,
1937
1938 /// ROS2 namespace (default: "/").
1939 #[serde(default = "default_ros2_namespace")]
1940 pub namespace: String,
1941
1942 /// ROS2 node name. Defaults to the dora node id.
1943 #[serde(default, skip_serializing_if = "Option::is_none")]
1944 pub node_name: Option<String>,
1945}
1946
1947impl Default for Ros2BridgeConfig {
1948 fn default() -> Self {
1949 Self {
1950 transport: Ros2TransportConfig::default(),
1951 topic: None,
1952 message_type: None,
1953 direction: Ros2Direction::default(),
1954 topics: None,
1955 service: None,
1956 service_type: None,
1957 action: None,
1958 action_type: None,
1959 role: None,
1960 qos: Ros2QosConfig::default(),
1961 namespace: default_ros2_namespace(),
1962 node_name: None,
1963 }
1964 }
1965}
1966
1967/// Native transport used by a ROS2 bridge context.
1968#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
1969#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1970pub enum Ros2TransportConfig {
1971 /// The existing `ros2-client` and RustDDS transport.
1972 #[default]
1973 Dds,
1974 /// Direct interoperability with `rmw_zenoh_cpp` peers.
1975 Zenoh {
1976 /// Wire-compatibility profile used by the target ROS2 distribution.
1977 compatibility: RmwZenohCompatibility,
1978 /// Optional Zenoh session configuration path.
1979 #[serde(default, skip_serializing_if = "Option::is_none")]
1980 config_uri: Option<PathBuf>,
1981 },
1982}
1983
1984/// Wire-compatibility profile for the `rmw_zenoh_cpp` protocol.
1985#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1986#[serde(rename_all = "snake_case")]
1987pub enum RmwZenohCompatibility {
1988 /// ROS2 Humble, whose endpoint identity uses `TypeHashNotSupported`.
1989 Humble,
1990 /// ROS2 distributions whose endpoint identity uses REP-2016 type hashes.
1991 Rep2016,
1992}
1993
1994/// Role of a ROS2 service or action bridge node.
1995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1996#[serde(rename_all = "snake_case")]
1997pub enum Ros2Role {
1998 /// Client: sends requests/goals, receives responses/results.
1999 Client,
2000 /// Server: receives requests, sends responses.
2001 Server,
2002}
2003
2004fn default_ros2_namespace() -> String {
2005 "/".to_string()
2006}
2007
2008/// Configuration for a single ROS2 topic in multi-topic mode.
2009#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
2010#[serde(deny_unknown_fields)]
2011pub struct Ros2TopicConfig {
2012 /// ROS2 topic name.
2013 pub topic: String,
2014
2015 /// ROS2 message type (e.g. "geometry_msgs/Twist").
2016 pub message_type: String,
2017
2018 /// Direction: subscribe or publish.
2019 #[serde(default)]
2020 pub direction: Ros2Direction,
2021
2022 /// Maps to an dora output id (for subscribe direction).
2023 #[serde(default, skip_serializing_if = "Option::is_none")]
2024 pub output: Option<String>,
2025
2026 /// Maps to an dora input id (for publish direction).
2027 #[serde(default, skip_serializing_if = "Option::is_none")]
2028 pub input: Option<String>,
2029
2030 /// Per-topic QoS override.
2031 #[serde(default, skip_serializing_if = "Option::is_none")]
2032 pub qos: Option<Ros2QosConfig>,
2033}
2034
2035/// Strip the leading `/` of a ROS2 topic name, then map any remaining `/` to
2036/// `_` (e.g. `/robot/scan` -> `robot_scan`).
2037///
2038/// ```
2039/// use dora_message::descriptor::derive_port_id;
2040///
2041/// assert_eq!(derive_port_id("/robot/scan"), "robot_scan");
2042/// assert_eq!(derive_port_id("scan"), "scan");
2043/// ```
2044pub fn derive_port_id(topic: &str) -> String {
2045 topic.trim_start_matches('/').replace('/', "_")
2046}
2047
2048impl Ros2TopicConfig {
2049 /// The dora output a `subscribe` topic feeds: the explicit `output:`
2050 /// mapping, or the topic-derived id when that is unset.
2051 ///
2052 /// Both the descriptor validator (`dora-core`) and the ros2 bridge node
2053 /// depend on producing the *same* id — the validator rejects configs whose
2054 /// port is not declared precisely because the bridge would otherwise
2055 /// silently drop the data — so the rule lives here in the shared message
2056 /// crate rather than being duplicated at each call site.
2057 pub fn output_port_id(&self) -> String {
2058 self.output
2059 .clone()
2060 .unwrap_or_else(|| derive_port_id(&self.topic))
2061 }
2062
2063 /// The dora input a `publish` topic consumes; the counterpart of
2064 /// [`Self::output_port_id`].
2065 pub fn input_port_id(&self) -> String {
2066 self.input
2067 .clone()
2068 .unwrap_or_else(|| derive_port_id(&self.topic))
2069 }
2070}
2071
2072/// The dora port a **single-topic** (`topic:`) ros2 bridge binds to, or `None`
2073/// when `declared_ports` leaves the choice ambiguous.
2074///
2075/// Single-topic mode has no explicit `output:`/`input:` field, so the port comes
2076/// from the node's declaration — `docs/ros2-bridge.md`: "In single-topic mode,
2077/// the node's declared `outputs` or `inputs` are used directly". Preferring the
2078/// topic-derived id when it *is* declared keeps a node that declares an extra
2079/// port (a `send_stdout_as` output, say) resolvable instead of ambiguous.
2080///
2081/// Both the descriptor resolver, which bakes the resolved id into the bridge
2082/// config, and the validator, which rejects the ambiguous case, call this — a
2083/// wrong choice here binds the bridge to a port nothing is wired to and drops
2084/// every message silently.
2085///
2086/// ```
2087/// use dora_message::descriptor::single_topic_port_id;
2088///
2089/// // The topic-derived id is preferred when the node declares it...
2090/// assert_eq!(
2091/// single_topic_port_id("/robot/scan", &["robot_scan", "status"]),
2092/// Some("robot_scan".to_string()),
2093/// );
2094/// // ...otherwise a node that declares a single port resolves to that port...
2095/// assert_eq!(
2096/// single_topic_port_id("/robot/scan", &["lidar"]),
2097/// Some("lidar".to_string()),
2098/// );
2099/// // ...but several non-matching ports leave the choice ambiguous.
2100/// assert_eq!(single_topic_port_id("/robot/scan", &["a", "b"]), None);
2101/// ```
2102pub fn single_topic_port_id(topic: &str, declared_ports: &[&str]) -> Option<String> {
2103 let derived = derive_port_id(topic);
2104 if declared_ports.contains(&derived.as_str()) {
2105 return Some(derived);
2106 }
2107 match declared_ports {
2108 [sole_port] => Some((*sole_port).to_owned()),
2109 _ => None,
2110 }
2111}
2112
2113/// Direction of ROS2 bridge communication.
2114#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
2115#[serde(rename_all = "snake_case")]
2116pub enum Ros2Direction {
2117 /// Subscribe: receive from ROS2, forward to dora outputs.
2118 #[default]
2119 Subscribe,
2120 /// Publish: receive from dora inputs, publish to ROS2.
2121 Publish,
2122}
2123
2124/// ROS2 Quality of Service configuration.
2125#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
2126#[serde(deny_unknown_fields)]
2127pub struct Ros2QosConfig {
2128 /// Use reliable transport (default: false = best effort).
2129 #[serde(default)]
2130 pub reliable: bool,
2131
2132 /// Durability: "volatile" (default), "transient_local".
2133 #[serde(default, skip_serializing_if = "Option::is_none")]
2134 pub durability: Option<String>,
2135
2136 /// Liveliness: "automatic" (default), "manual_by_participant", "manual_by_topic".
2137 #[serde(default, skip_serializing_if = "Option::is_none")]
2138 pub liveliness: Option<String>,
2139
2140 /// Lease duration in seconds (default: infinity).
2141 #[serde(default, skip_serializing_if = "Option::is_none")]
2142 pub lease_duration: Option<f64>,
2143
2144 /// Max blocking time in seconds for reliable transport.
2145 #[serde(default, skip_serializing_if = "Option::is_none")]
2146 pub max_blocking_time: Option<f64>,
2147
2148 /// History depth for KeepLast policy (default: 1).
2149 #[serde(default, skip_serializing_if = "Option::is_none")]
2150 pub keep_last: Option<i32>,
2151
2152 /// Use KeepAll history policy instead of KeepLast.
2153 #[serde(default)]
2154 pub keep_all: bool,
2155}
2156
2157#[cfg(test)]
2158mod tests {
2159 use super::*;
2160
2161 /// A quoted `env:` value must reach the node verbatim. The derived
2162 /// untagged enum parsed strings into the first matching variant, so
2163 /// `"1.10"` became `1.1` and `"007"` became `7`.
2164 #[test]
2165 fn env_value_keeps_quoted_strings_verbatim() {
2166 for quoted in [
2167 "1.10",
2168 "007",
2169 "+5",
2170 "1e3",
2171 "1.0",
2172 "12345678901234567890",
2173 "inf",
2174 "-inf",
2175 "NaN",
2176 ] {
2177 let yaml = format!("\"{quoted}\"");
2178 let value: EnvValue = serde_yaml::from_str(&yaml).unwrap();
2179 assert_eq!(value, EnvValue::String(quoted.into()), "yaml {yaml}");
2180
2181 // ...and survives the JSON hops CLI -> coordinator -> daemon.
2182 let json = serde_json::to_string(&value).unwrap();
2183 let value: EnvValue = serde_json::from_str(&json).unwrap();
2184 assert_eq!(value.to_string(), quoted, "json {json}");
2185 }
2186 }
2187
2188 /// Strings that type losslessly keep the bool/number type every 1.x
2189 /// release gave them, so `dataflow_descriptor()` consumers see no change.
2190 #[test]
2191 fn env_value_types_lossless_strings() {
2192 let parse = |yaml: &str| serde_yaml::from_str::<EnvValue>(yaml).unwrap();
2193 assert_eq!(parse("\"true\""), EnvValue::Bool(true));
2194 assert_eq!(parse("\"8080\""), EnvValue::Integer(8080));
2195 assert_eq!(parse("\"-3\""), EnvValue::Integer(-3));
2196 assert_eq!(parse("\"1.5\""), EnvValue::Float(1.5));
2197 }
2198
2199 #[test]
2200 fn env_value_keeps_native_types() {
2201 let parse = |yaml: &str| serde_yaml::from_str::<EnvValue>(yaml).unwrap();
2202 assert_eq!(parse("true"), EnvValue::Bool(true));
2203 assert_eq!(parse("8080"), EnvValue::Integer(8080));
2204 assert_eq!(parse("-3"), EnvValue::Integer(-3));
2205 assert_eq!(parse("1.5"), EnvValue::Float(1.5));
2206 assert_eq!(parse("hello"), EnvValue::String("hello".into()));
2207 }
2208
2209 /// A native YAML `.inf` / `.nan` has no JSON encoding (serde_json
2210 /// writes `null`), so as a `Float` it made the coordinator reject the
2211 /// whole `dora start`. It must stay the string the node would have seen
2212 /// and survive the JSON hops CLI -> coordinator -> daemon.
2213 #[test]
2214 fn env_value_keeps_non_finite_native_floats_as_strings() {
2215 for (yaml, text) in [(".inf", "inf"), ("-.inf", "-inf"), (".nan", "NaN")] {
2216 let value: EnvValue = serde_yaml::from_str(yaml).unwrap();
2217 assert_eq!(value, EnvValue::String(text.into()), "yaml {yaml}");
2218
2219 let json = serde_json::to_string(&value).unwrap();
2220 let value: EnvValue = serde_json::from_str(&json).unwrap();
2221 assert_eq!(value.to_string(), text, "json {json}");
2222 }
2223 }
2224
2225 /// A native integer above `i64::MAX` reaches the node with its exact
2226 /// digits, not rounded through `f64` (`12345678901234567890` used to
2227 /// arrive as `12345678901234567000`).
2228 #[test]
2229 fn env_value_keeps_large_native_integers_exact() {
2230 for text in [
2231 "9223372036854775808",
2232 "12345678901234567890",
2233 "18446744073709551615",
2234 ] {
2235 let value: EnvValue = serde_yaml::from_str(text).unwrap();
2236 assert_eq!(value.to_string(), text, "yaml {text}");
2237
2238 let json = serde_json::to_string(&value).unwrap();
2239 let value: EnvValue = serde_json::from_str(&json).unwrap();
2240 assert_eq!(value.to_string(), text, "json {json}");
2241 }
2242 }
2243
2244 /// Strings still expand `$VAR` references, quoted or not, and the result
2245 /// is typed by the same lossless rule.
2246 #[test]
2247 fn env_value_expands_variables_in_strings() {
2248 let parse = |yaml: &str| serde_yaml::from_str::<EnvValue>(yaml).unwrap();
2249 for unquoted in [false, true] {
2250 let q = if unquoted { "" } else { "\"" };
2251 let parse_ref = |default: &str| {
2252 parse(&format!(
2253 "{q}${{DORA_TEST_ENV_VALUE_UNSET_VAR:-{default}}}{q}"
2254 ))
2255 };
2256 assert_eq!(parse_ref("1.10"), EnvValue::String("1.10".into()));
2257 assert_eq!(parse_ref("8080"), EnvValue::Integer(8080));
2258 assert_eq!(parse_ref("true"), EnvValue::Bool(true));
2259 }
2260 assert_eq!(
2261 parse("\"v${DORA_TEST_ENV_VALUE_UNSET_VAR:-2}\""),
2262 EnvValue::String("v2".into())
2263 );
2264 assert!(serde_yaml::from_str::<EnvValue>("\"$DORA_TEST_ENV_VALUE_UNSET_VAR\"").is_err());
2265 }
2266
2267 /// A string whose expansion contains `$` must not be expanded again by
2268 /// the next decode, which runs in the coordinator, the daemon and the
2269 /// node against *their* environments (#3947). `$${...}` is how a value
2270 /// containing `${...}` gets into memory without a CLI-side variable;
2271 /// `DORA_TEST_ENV_VALUE_UNSET_VAR` is unset, so a second expansion would
2272 /// fail the decode instead of passing by accident.
2273 #[test]
2274 fn env_value_is_not_expanded_again_after_a_round_trip() {
2275 let yaml = "env:\n X: $${DORA_TEST_ENV_VALUE_UNSET_VAR}\n \
2276 PW: p$$ssw0rd\n TAIL: cost$$\nnodes: []\n";
2277 let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
2278 let expected = BTreeMap::from([
2279 (
2280 "X".to_string(),
2281 EnvValue::String("${DORA_TEST_ENV_VALUE_UNSET_VAR}".into()),
2282 ),
2283 ("PW".to_string(), EnvValue::String("p$ssw0rd".into())),
2284 ("TAIL".to_string(), EnvValue::String("cost$".into())),
2285 ]);
2286 assert_eq!(descriptor.env.as_ref(), Some(&expected));
2287
2288 // Every hop: CLI -> coordinator -> daemon -> node over JSON.
2289 let mut current = descriptor;
2290 for hop in 0..3 {
2291 let json = serde_json::to_string(¤t).unwrap();
2292 current = serde_json::from_str(&json)
2293 .unwrap_or_else(|e| panic!("JSON hop {hop} failed: {e}\n{json}"));
2294 assert_eq!(current.env.as_ref(), Some(&expected), "JSON hop {hop}");
2295 }
2296 // The YAML session file the CLI writes and rereads for `hub:` dataflows.
2297 let yaml = serde_yaml::to_string(¤t).unwrap();
2298 let reread: Descriptor = serde_yaml::from_str(&yaml).unwrap();
2299 assert_eq!(reread.env.as_ref(), Some(&expected), "YAML\n{yaml}");
2300 }
2301
2302 /// Strings without `$` and typed values keep the plain encoding, so the
2303 /// common case stays byte-identical to what 1.x peers send.
2304 #[test]
2305 fn env_value_serializes_without_dollar_unchanged() {
2306 let json = |v: EnvValue| serde_json::to_string(&v).unwrap();
2307 assert_eq!(json(EnvValue::String("hello".into())), "\"hello\"");
2308 assert_eq!(json(EnvValue::String("1.10".into())), "\"1.10\"");
2309 assert_eq!(json(EnvValue::Integer(8080)), "8080");
2310 assert_eq!(json(EnvValue::Float(1.5)), "1.5");
2311 assert_eq!(json(EnvValue::Bool(true)), "true");
2312 assert_eq!(json(EnvValue::String("a$b".into())), "\"a$$b\"");
2313 }
2314
2315 /// `Node.dataflow_descriptor()` (Python), a Python operator's
2316 /// `self.dataflow_descriptor`, and the C++ `dataflow_descriptor_json`
2317 /// all serialize an already-decoded `Descriptor` directly, with no
2318 /// further decode step to undo the wire escape — `descriptor_for_display`
2319 /// is what each of them must go through instead of a bare
2320 /// `serde_json::to_value`/`pythonize` call (#4067).
2321 #[test]
2322 fn descriptor_for_display_shows_the_raw_value() {
2323 let mut node = Node::new("n".parse().unwrap());
2324 node.env = Some(BTreeMap::from([(
2325 "K".to_string(),
2326 EnvValue::String("a$b".into()),
2327 )]));
2328 let mut descriptor = Descriptor::new(vec![node]);
2329 descriptor.env = Some(BTreeMap::from([(
2330 "PRICE".to_string(),
2331 EnvValue::String("50$ off".into()),
2332 )]));
2333
2334 // A bare serialize still shows the wire-escaped form.
2335 let wire = serde_json::to_value(&descriptor).unwrap();
2336 assert_eq!(wire["env"]["PRICE"], "50$$ off");
2337 assert_eq!(wire["nodes"][0]["env"]["K"], "a$$b");
2338
2339 // `descriptor_for_display` undoes it, at both `env` locations.
2340 let display = descriptor_for_display(&descriptor).unwrap();
2341 assert_eq!(display["env"]["PRICE"], "50$ off");
2342 assert_eq!(display["nodes"][0]["env"]["K"], "a$b");
2343 }
2344
2345 /// `descriptor_for_display` targets only `env`/`nodes[].env`, so a `$$`
2346 /// elsewhere in the descriptor (a path, a description, ...) that has
2347 /// nothing to do with the escape must survive unchanged.
2348 #[test]
2349 fn descriptor_for_display_leaves_unrelated_dollar_signs_alone() {
2350 let mut node = Node::new("n".parse().unwrap());
2351 node.path = Some("echo $$ not an env escape".into());
2352 let descriptor = Descriptor::new(vec![node]);
2353 let display = descriptor_for_display(&descriptor).unwrap();
2354 assert_eq!(display["nodes"][0]["path"], "echo $$ not an env escape");
2355 }
2356
2357 /// Assert that `constructed` serializes to exactly what `yaml`
2358 /// deserializes to — that a hand-written constructor agrees with the
2359 /// per-field `#[serde(default)]`s.
2360 ///
2361 /// The two are independent sources of the same defaults, and both are
2362 /// used in production: the daemon builds dynamically registered nodes
2363 /// through `Node::new` (`Daemon::handle_add_node`) and declared nodes
2364 /// through serde, so a divergence — say a field that later grows a
2365 /// `#[serde(default = "…")]` custom default — would silently give the two
2366 /// kinds different configuration.
2367 fn assert_matches_yaml_defaults<T: Serialize + serde::de::DeserializeOwned>(
2368 yaml: &str,
2369 constructed: T,
2370 what: &str,
2371 ) {
2372 let from_yaml: T = serde_yaml::from_str(yaml).unwrap();
2373 assert_eq!(
2374 serde_yaml::to_value(&from_yaml).unwrap(),
2375 serde_yaml::to_value(&constructed).unwrap(),
2376 "`{what}` drifted from the defaults serde applies"
2377 );
2378 }
2379
2380 /// `Node::new` must agree with what serde produces for a YAML node that
2381 /// sets nothing but `id`.
2382 #[test]
2383 fn node_new_matches_yaml_defaults() {
2384 assert_matches_yaml_defaults(
2385 "id: some-node\n",
2386 Node::new("some-node".to_owned().into()),
2387 "Node::new",
2388 );
2389 }
2390
2391 /// The same contract for the other constructors this crate hands out.
2392 ///
2393 /// `Descriptor::new` is what the coordinator's `AddNode` resolution and the
2394 /// daemon's bench support build from; `Deploy::default()` and
2395 /// `Debug::default()` are the documented entry points for `deploy:` and
2396 /// `debug:`; `NodeRunConfig::default()` is the runtime node's I/O config in
2397 /// the daemon while custom nodes deserialize theirs.
2398 ///
2399 /// `CustomNode::new` is not covered here: `source` and `envs` have no serde
2400 /// default, so there is no "nothing set" YAML for it. Its guard is
2401 /// `CustomNode::from_node` — a struct literal in this crate, so a new field
2402 /// is a compile error — plus
2403 /// `dora_core::descriptor::tests::every_custom_node_field_is_carried_through`
2404 /// for the values.
2405 #[test]
2406 fn constructors_match_yaml_defaults() {
2407 assert_matches_yaml_defaults(
2408 "nodes: []\n",
2409 Descriptor::new(Vec::new()),
2410 "Descriptor::new",
2411 );
2412 assert_matches_yaml_defaults("{}\n", Deploy::default(), "Deploy::default");
2413 assert_matches_yaml_defaults("{}\n", Debug::default(), "Debug::default");
2414 assert_matches_yaml_defaults("{}\n", NodeRunConfig::default(), "NodeRunConfig::default");
2415 assert_matches_yaml_defaults(
2416 "from: a\nto: b\n",
2417 TypeRuleDef::new("a".to_owned(), "b".to_owned()),
2418 "TypeRuleDef::new",
2419 );
2420 }
2421
2422 #[test]
2423 fn ros2_transport_defaults_to_dds() {
2424 let config: Ros2BridgeConfig =
2425 serde_yaml::from_str("topic: /chatter\nmessage_type: std_msgs/String\n").unwrap();
2426 assert!(matches!(config.transport, Ros2TransportConfig::Dds));
2427 }
2428
2429 #[test]
2430 fn ros2_transport_parses_humble_zenoh() {
2431 let config: Ros2BridgeConfig = serde_yaml::from_str(
2432 "transport:\n kind: zenoh\n compatibility: humble\n config_uri: /tmp/rmw.json5\n\
2433 topic: /chatter\nmessage_type: std_msgs/String\n",
2434 )
2435 .unwrap();
2436 assert_eq!(
2437 config.transport,
2438 Ros2TransportConfig::Zenoh {
2439 compatibility: RmwZenohCompatibility::Humble,
2440 config_uri: Some("/tmp/rmw.json5".into()),
2441 }
2442 );
2443 }
2444
2445 #[test]
2446 fn ros2_transport_rejects_unknown_zenoh_compatibility() {
2447 let error = serde_yaml::from_str::<Ros2BridgeConfig>(
2448 "transport:\n kind: zenoh\n compatibility: automatic\n\
2449 topic: /chatter\nmessage_type: std_msgs/String\n",
2450 )
2451 .unwrap_err();
2452 assert!(error.to_string().contains("unknown variant `automatic`"));
2453 }
2454
2455 #[test]
2456 fn single_topic_port_uses_the_sole_declared_port() {
2457 // `docs/ros2-bridge.md`: single-topic mode uses the declared port
2458 // directly, so `/turtle1/pose` binds to `pose` and not to the
2459 // topic-derived `turtle1_pose`.
2460 assert_eq!(
2461 single_topic_port_id("/turtle1/pose", &["pose"]),
2462 Some("pose".to_owned())
2463 );
2464 }
2465
2466 #[test]
2467 fn single_topic_port_prefers_a_declared_topic_derived_id() {
2468 // A second declared port (here a `send_stdout_as` output) would make the
2469 // choice ambiguous, but the topic-derived id is itself declared.
2470 assert_eq!(
2471 single_topic_port_id("/turtle1/pose", &["log", "turtle1_pose"]),
2472 Some("turtle1_pose".to_owned())
2473 );
2474 }
2475
2476 #[test]
2477 fn single_topic_port_is_ambiguous_with_several_unrelated_ports() {
2478 assert_eq!(
2479 single_topic_port_id("/turtle1/pose", &["pose", "log"]),
2480 None
2481 );
2482 }
2483
2484 #[test]
2485 fn single_topic_port_needs_a_declared_port() {
2486 assert_eq!(single_topic_port_id("/turtle1/pose", &[]), None);
2487 }
2488
2489 #[test]
2490 fn output_framing_defaults_to_raw() {
2491 let yaml = r#"
2492nodes:
2493 - id: test
2494 path: test.py
2495 outputs:
2496 - data
2497"#;
2498 let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
2499 assert!(desc.nodes[0].output_framing.is_empty());
2500 }
2501
2502 #[test]
2503 fn output_framing_parses_arrow_ipc() {
2504 let yaml = r#"
2505nodes:
2506 - id: test
2507 path: test.py
2508 outputs:
2509 - data
2510 output_framing:
2511 data: arrow-ipc
2512"#;
2513 let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
2514 assert_eq!(
2515 desc.nodes[0].output_framing.get::<DataId>(&"data".into()),
2516 Some(&OutputFraming::ArrowIpc)
2517 );
2518 }
2519
2520 #[test]
2521 fn cpu_affinity_parses() {
2522 let yaml = r#"
2523nodes:
2524 - id: test
2525 path: test.py
2526 cpu_affinity: [0, 2, 4]
2527"#;
2528 let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
2529 assert_eq!(desc.nodes[0].cpu_affinity, Some(vec![0, 2, 4]));
2530 }
2531
2532 #[test]
2533 fn cpu_affinity_defaults_to_none() {
2534 let yaml = r#"
2535nodes:
2536 - id: test
2537 path: test.py
2538"#;
2539 let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
2540 assert_eq!(desc.nodes[0].cpu_affinity, None);
2541 }
2542
2543 #[test]
2544 fn debug_flag_accepts_new_name() {
2545 let yaml = r#"
2546nodes:
2547 - id: test
2548 path: test.py
2549debug:
2550 enable_debug_inspection: true
2551"#;
2552 let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
2553 assert!(desc.debug.enable_debug_inspection);
2554 }
2555
2556 #[test]
2557 fn removed_unstable_key_prefix_is_rejected_not_ignored() {
2558 // `_unstable_deploy` / `_unstable_debug` lost their prefix for 1.0.
2559 // Both must *error*, never deserialize to the default: a dataflow that
2560 // still says `_unstable_deploy` would otherwise run every node on the
2561 // local daemon while looking like it pinned them to machines, and a
2562 // stale `_unstable_debug` would leave `dora topic echo` silently
2563 // empty. `deny_unknown_fields` on `Descriptor` is what makes these
2564 // diagnosable, so this test guards that attribute as much as the
2565 // rename.
2566 for (key, block) in [
2567 ("_unstable_deploy", "_unstable_deploy:\n machine: m1\n"),
2568 (
2569 "_unstable_debug",
2570 "_unstable_debug:\n enable_debug_inspection: true\n",
2571 ),
2572 ] {
2573 let yaml = format!("nodes:\n - id: test\n path: test.py\n{block}");
2574 let err = serde_yaml::from_str::<Descriptor>(&yaml)
2575 .expect_err("the pre-1.0 `_unstable_` key must be rejected");
2576 assert!(
2577 err.to_string().contains(key),
2578 "error should name `{key}`, got: {err}"
2579 );
2580 }
2581 }
2582
2583 #[test]
2584 fn debug_flag_rejects_the_removed_legacy_alias() {
2585 // The `publish_all_messages_to_zenoh` alias was removed for 1.0. It
2586 // must *error* rather than deserialize to the default: silently
2587 // ignoring it would leave debug inspection off while the dataflow
2588 // looks like it enabled it, and `dora topic echo` would return
2589 // nothing with no explanation. `deny_unknown_fields` on `Debug` is
2590 // what turns that into a diagnosable failure.
2591 let yaml = r#"
2592nodes:
2593 - id: test
2594 path: test.py
2595debug:
2596 publish_all_messages_to_zenoh: true
2597"#;
2598 let err = serde_yaml::from_str::<Descriptor>(yaml)
2599 .expect_err("removed alias must be rejected, not silently ignored");
2600 assert!(
2601 err.to_string().contains("publish_all_messages_to_zenoh"),
2602 "error should name the offending field, got: {err}"
2603 );
2604 }
2605
2606 #[test]
2607 fn operator_source_shared_library_names_its_runtime() {
2608 let cfg: OperatorConfig = serde_yaml::from_str("shared-library: build/op").unwrap();
2609 assert!(matches!(&cfg.source, OperatorSource::SharedLibrary(s) if s == "build/op"));
2610 assert_eq!(cfg.source.runtime_name(), RUNTIME_SHARED_LIBRARY);
2611 assert_eq!(cfg.source.runtime_name(), "shared-library");
2612 }
2613
2614 #[test]
2615 fn operator_source_python_source_only_names_its_runtime() {
2616 let cfg: OperatorConfig = serde_yaml::from_str("python: op.py").unwrap();
2617 assert!(matches!(&cfg.source, OperatorSource::Python(py) if py.source == "op.py"));
2618 assert_eq!(cfg.source.runtime_name(), RUNTIME_PYTHON);
2619 }
2620
2621 #[test]
2622 fn operator_source_python_with_conda_env_names_its_runtime() {
2623 let cfg: OperatorConfig =
2624 serde_yaml::from_str("python:\n source: op.py\n conda_env: my-env").unwrap();
2625 match &cfg.source {
2626 OperatorSource::Python(py) => {
2627 assert_eq!(py.source, "op.py");
2628 assert_eq!(py.conda_env.as_deref(), Some("my-env"));
2629 }
2630 other => panic!("expected python source, got {other:?}"),
2631 }
2632 assert_eq!(cfg.source.runtime_name(), RUNTIME_PYTHON);
2633 }
2634
2635 #[test]
2636 fn operator_source_wasm_names_its_runtime() {
2637 let cfg: OperatorConfig = serde_yaml::from_str("wasm: op.wasm").unwrap();
2638 assert!(matches!(&cfg.source, OperatorSource::Wasm(s) if s == "op.wasm"));
2639 assert_eq!(cfg.source.runtime_name(), RUNTIME_WASM);
2640 }
2641
2642 /// The runtime a node is spawned with must survive a descriptor round-trip:
2643 /// the daemon re-parses the serialized descriptor before spawning.
2644 #[test]
2645 fn operator_source_runtime_survives_a_serde_roundtrip() {
2646 for yaml in ["shared-library: build/op", "python: op.py", "wasm: op.wasm"] {
2647 let cfg: OperatorConfig = serde_yaml::from_str(yaml).unwrap();
2648 let serialized = serde_yaml::to_string(&cfg).unwrap();
2649 let reparsed: OperatorConfig = serde_yaml::from_str(&serialized).unwrap();
2650 assert_eq!(cfg.source.runtime_name(), reparsed.source.runtime_name());
2651 }
2652 }
2653
2654 /// The schema must agree with the parser on every empty key. An empty
2655 /// key is YAML `null`, which serde maps to the field's default wherever
2656 /// the field has one, so the schema has to accept `null` exactly there.
2657 ///
2658 /// Every property of every struct a dataflow spells out as a YAML mapping
2659 /// is checked at a real location. A struct definition this test doesn't
2660 /// know about fails it, so a new field or struct cannot drift unseen.
2661 #[test]
2662 fn empty_keys_schema_matches_parser() {
2663 fn schema_accepts_null(property: &serde_json::Value) -> bool {
2664 property["type"]
2665 .as_array()
2666 .is_some_and(|t| t.contains(&"null".into()))
2667 || property["anyOf"]
2668 .as_array()
2669 .is_some_and(|v| v.iter().any(|s| s["type"] == "null"))
2670 }
2671 /// The properties of a definition, including those of its variants.
2672 fn properties(
2673 definition: &serde_json::Value,
2674 ) -> serde_json::Map<String, serde_json::Value> {
2675 let mut properties = serde_json::Map::new();
2676 let variants = ["oneOf", "anyOf"]
2677 .iter()
2678 .filter_map(|k| definition[k].as_array())
2679 .flatten();
2680 for variant in std::iter::once(definition).chain(variants) {
2681 if let Some(p) = variant["properties"].as_object() {
2682 properties.extend(p.clone());
2683 }
2684 }
2685 properties
2686 }
2687
2688 let schema = serde_json::to_value(schemars::schema_for!(Descriptor)).unwrap();
2689 let node = "nodes:\n - id: a\n path: x\n";
2690 let ros2 =
2691 "nodes:\n - id: a\n ros2:\n topic: /x\n message_type: std_msgs/String\n";
2692 // (definition, a dataflow with `{key}` where the empty key goes, keys
2693 // that dataflow already sets). `""` is the dataflow itself.
2694 let locations: &[(&str, String, &[&str])] = &[
2695 ("", format!("{node}{{key}}:\n"), &["nodes"]),
2696 ("Node", format!("{node} {{key}}:\n"), &["id", "path"]),
2697 ("Debug", format!("{node}debug:\n {{key}}:\n"), &[]),
2698 ("Deploy", format!("{node} deploy:\n {{key}}:\n"), &[]),
2699 (
2700 "Input",
2701 format!("{node} inputs:\n i:\n source: b/o\n {{key}}:\n"),
2702 &["source"],
2703 ),
2704 (
2705 "PythonSource",
2706 "nodes:\n - id: a\n operator:\n python:\n source: x.py\n {key}:\n"
2707 .to_owned(),
2708 &["source"],
2709 ),
2710 (
2711 "Ros2BridgeConfig",
2712 format!("{ros2} {{key}}:\n"),
2713 &["topic", "message_type"],
2714 ),
2715 ("Ros2QosConfig", format!("{ros2} qos:\n {{key}}:\n"), &[]),
2716 (
2717 "Ros2TopicConfig",
2718 "nodes:\n - id: a\n ros2:\n topics:\n - topic: /x\n message_type: std_msgs/String\n {key}:\n"
2719 .to_owned(),
2720 &["topic", "message_type"],
2721 ),
2722 (
2723 "Ros2TransportConfig",
2724 format!("{ros2} transport:\n kind: zenoh\n compatibility: humble\n {{key}}:\n"),
2725 &["kind", "compatibility"],
2726 ),
2727 ];
2728 // serde_yaml reads `null` into a plain `String` as "", not as the
2729 // field's default (`namespace` would be "" instead of "/"), so the
2730 // schema rejects an empty key there on purpose.
2731 let null_is_not_the_default = [("Ros2BridgeConfig", "namespace")];
2732
2733 for (definition, template, preset) in locations {
2734 let def = if definition.is_empty() {
2735 &schema
2736 } else {
2737 &schema["$defs"][definition]
2738 };
2739 let without_key: String = template
2740 .lines()
2741 .filter(|l| !l.contains("{key}"))
2742 .map(|l| format!("{l}\n"))
2743 .collect();
2744 serde_yaml::from_str::<Descriptor>(&without_key)
2745 .unwrap_or_else(|e| panic!("template for `{definition}` must parse: {e}"));
2746 for (key, property) in properties(def) {
2747 if preset.contains(&key.as_str()) {
2748 continue;
2749 }
2750 let yaml = template.replace("{key}", &key);
2751 let parses = serde_yaml::from_str::<Descriptor>(&yaml).is_ok();
2752 let expected = parses && !null_is_not_the_default.contains(&(definition, &key));
2753 assert_eq!(schema_accepts_null(&property), expected, "{yaml}{property}");
2754 }
2755 }
2756
2757 // Not written as YAML mappings, so there is no empty key to check:
2758 // input mappings and their parts are strings (`node/output`,
2759 // `dora/timer/millis/100`, `dora/logs/...`).
2760 // `TypeRuleDef`: both fields are required strings, and an empty one
2761 // reads as "" (like `namespace`), so the schema rejects it on purpose.
2762 // Operators are checked below.
2763 let not_walked = [
2764 "InputMapping",
2765 "UserInputMapping",
2766 "LogSubscriptionFilter",
2767 "Duration",
2768 "TypeRuleDef",
2769 "OperatorDefinition",
2770 "SingleOperatorDefinition",
2771 ];
2772 for (name, def) in schema["$defs"].as_object().unwrap() {
2773 if properties(def).is_empty() || not_walked.contains(&name.as_str()) {
2774 continue;
2775 }
2776 assert!(
2777 locations.iter().any(|(d, ..)| d == name),
2778 "new struct `{name}` in the schema: add a location for it to this test"
2779 );
2780 }
2781
2782 // Operators are `#[serde(flatten)]`ed, and flattened fields don't
2783 // map `null` to a default, so there the schema must reject it.
2784 let operators = "nodes:\n - id: a\n operators:\n - id: op\n python: x.py\n inputs:\n";
2785 let operator = "nodes:\n - id: a\n operator:\n python: x.py\n outputs:\n";
2786 for yaml in [operators, operator] {
2787 assert!(serde_yaml::from_str::<Descriptor>(yaml).is_err(), "{yaml}");
2788 }
2789 for definition in ["OperatorDefinition", "SingleOperatorDefinition"] {
2790 for key in ["inputs", "outputs", "input_types", "output_types"] {
2791 let property = &schema["$defs"][definition]["properties"][key];
2792 assert!(
2793 !schema_accepts_null(property),
2794 "{definition}.{key}: {property}"
2795 );
2796 }
2797 }
2798 }
2799}