dora-cli 1.0.0

`dora` goal is to be a low latency, composable, and distributed data flow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::io::Write;

use clap::Args;
use colored::Colorize;
use serde::Serialize;
use tabwriter::TabWriter;

use crate::{
    command::{
        Executable, default_tracing,
        topic::selector::{node_topic_inputs, node_topic_outputs},
    },
    common::{
        CoordinatorOptions, expect_reply, resolve_dataflow_identifier_interactive,
        send_control_request,
    },
    formatting::OutputFormat,
    ws_client::WsSession,
};
use dora_core::config::InputMapping;
use dora_message::{
    cli_to_coordinator::ControlRequest, coordinator_to_cli::NodeInfo, descriptor::Descriptor,
    id::NodeId,
};

/// Show detailed information about a specific node.
///
/// Displays inputs, outputs, subscribers, restart policy, and runtime metrics.
///
/// Examples:
///
/// Show info for a node:
///   dora node info camera_node
///
/// Show info for a node in a specific dataflow:
///   dora node info camera_node --dataflow my-dataflow
///
/// Output as JSON:
///   dora node info camera_node --format json
#[derive(Debug, Args)]
#[clap(verbatim_doc_comment)]
pub struct Info {
    /// Node ID to inspect
    #[clap(value_name = "NODE")]
    pub node: String,

    /// Filter by dataflow name or UUID
    #[clap(long, short = 'd', value_name = "NAME_OR_UUID")]
    pub dataflow: Option<String>,

    /// Output format
    ///
    /// `json` emits a single pretty-printed JSON document.
    #[clap(long, short = 'f', value_name = "FORMAT", default_value_t = OutputFormat::Table)]
    pub format: OutputFormat,

    #[clap(flatten)]
    coordinator: CoordinatorOptions,
}

impl Executable for Info {
    fn execute(self) -> eyre::Result<()> {
        default_tracing()?;

        let session = self.coordinator.connect()?;
        info(&session, &self.node, self.dataflow.as_deref(), self.format)
    }
}

#[derive(Serialize)]
struct NodeInfoOutput {
    node_id: String,
    dataflow: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    outputs: Vec<OutputInfo>,
    inputs: Vec<InputInfo>,
    restart_policy: String,
    max_restarts: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    restart_delay: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    health_check_timeout: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    finish_grace_secs: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    metrics: Option<MetricsOutput>,
}

#[derive(Serialize)]
struct OutputInfo {
    id: String,
    subscribers: Vec<String>,
}

#[derive(Serialize)]
struct InputInfo {
    id: String,
    source: String,
}

#[derive(Serialize)]
struct MetricsOutput {
    status: String,
    pid: u32,
    cpu: String,
    memory: String,
    restart_count: u32,
    pending_messages: u64,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    broken_inputs: Vec<String>,
}

fn info(
    session: &WsSession,
    node_name: &str,
    dataflow_filter: Option<&str>,
    format: OutputFormat,
) -> eyre::Result<()> {
    let node_id: NodeId = node_name
        .parse::<NodeId>()
        .map_err(|e| eyre::eyre!("invalid node ID: {e}"))?;

    // Resolve the dataflow
    let dataflow_uuid = resolve_dataflow_identifier_interactive(session, dataflow_filter)?;

    // Get descriptor
    let reply = send_control_request(session, &ControlRequest::Info { dataflow_uuid })?;
    let (dataflow_name, descriptor) = expect_reply!(reply, DataflowInfo { name, descriptor })?;

    // Find the node in the descriptor
    let node_desc = descriptor
        .nodes
        .iter()
        .find(|n| n.id == node_id)
        .ok_or_else(|| {
            let available: Vec<_> = descriptor.nodes.iter().map(|n| n.id.to_string()).collect();
            eyre::eyre!(
                "node `{node_name}` not found in dataflow\n\n  \
                 hint: available nodes: {}",
                available.join(", ")
            )
        })?;

    // Get runtime metrics
    let metrics = fetch_node_metrics(session, dataflow_uuid, &node_id)?;

    // Build output info with subscribers
    let outputs = build_output_info(node_desc, &descriptor);
    let inputs = build_input_info(node_desc);

    let dataflow_display = dataflow_name
        .clone()
        .unwrap_or_else(|| dataflow_uuid.to_string());

    let output = NodeInfoOutput {
        node_id: node_name.to_string(),
        dataflow: dataflow_display.clone(),
        name: node_desc.name.clone(),
        description: node_desc.description.clone(),
        path: node_desc.path.clone(),
        outputs,
        inputs,
        restart_policy: format!("{:?}", node_desc.restart_policy),
        max_restarts: node_desc.max_restarts,
        restart_delay: node_desc.restart_delay,
        health_check_timeout: node_desc.health_check_timeout,
        finish_grace_secs: node_desc.finish_grace_secs,
        metrics: metrics.and_then(|m| m.metrics).map(|m| MetricsOutput {
            status: m.status.to_string(),
            pid: m.pid,
            cpu: format!("{:.1}%", m.cpu_usage),
            memory: format!("{:.0} MB", m.memory_mb),
            restart_count: m.restart_count,
            pending_messages: m.pending_messages,
            broken_inputs: m.broken_inputs,
        }),
    };

    match format {
        OutputFormat::Table => print_table(&output),
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
    }

    Ok(())
}

fn fetch_node_metrics(
    session: &WsSession,
    dataflow_uuid: uuid::Uuid,
    node_id: &NodeId,
) -> eyre::Result<Option<NodeInfo>> {
    let reply = send_control_request(session, &ControlRequest::GetNodeInfo)?;
    let node_infos = expect_reply!(reply, NodeInfoList(infos))?;

    Ok(node_infos
        .into_iter()
        .find(|n| n.dataflow_id == dataflow_uuid && n.node_id == *node_id))
}

fn build_output_info(
    node_desc: &dora_message::descriptor::Node,
    descriptor: &Descriptor,
) -> Vec<OutputInfo> {
    // Use `node_topic_outputs` / `node_topic_inputs` rather than the raw
    // `node.outputs` / `node.inputs` fields: those are empty for `operator:` and
    // `operators:` nodes, which declare their ports under `operator.config` /
    // `operators[].config` (dora-rs/dora#2893). Reading the raw fields makes
    // `dora node info` report no inputs/outputs for an operator-backed node, and
    // omits every operator-node consumer from an output's subscriber list.
    node_topic_outputs(node_desc)
        .iter()
        .map(|output_id| {
            let mut subscribers = Vec::new();
            for other_node in &descriptor.nodes {
                for (input_id, input) in node_topic_inputs(other_node) {
                    if let InputMapping::User(user) = &input.mapping
                        && user.source == node_desc.id
                        && user.output == *output_id
                    {
                        subscribers.push(format!("{}/{}", other_node.id, input_id));
                    }
                }
            }
            OutputInfo {
                id: output_id.to_string(),
                subscribers,
            }
        })
        .collect()
}

fn build_input_info(node_desc: &dora_message::descriptor::Node) -> Vec<InputInfo> {
    node_topic_inputs(node_desc)
        .into_iter()
        .map(|(input_id, input)| InputInfo {
            id: input_id.to_string(),
            // Use `InputMapping`'s canonical `Display` rather than re-deriving the
            // source string here. The previous hand-rolled
            // `dora/timer/millis/{interval.as_millis()}` truncated any
            // sub-millisecond timer (e.g. a `dora/timer/hz/2000` = 500µs input)
            // to `dora/timer/millis/0`, a nonsensical zero-interval source;
            // `Display` picks the coarsest exact unit and round-trips through the
            // descriptor parser.
            source: input.mapping.to_string(),
        })
        .collect()
}

fn print_table(output: &NodeInfoOutput) {
    println!("{}: {}", "Node".bold(), output.node_id);
    println!("{}: {}", "Dataflow".bold(), output.dataflow);
    if let Some(name) = &output.name {
        println!("{}: {}", "Name".bold(), name);
    }
    if let Some(desc) = &output.description {
        println!("{}: {}", "Description".bold(), desc);
    }
    if let Some(path) = &output.path {
        println!("{}: {}", "Path".bold(), path);
    }
    println!();

    // Restart policy
    println!("{}", "Restart Policy:".bold());
    println!("  Policy: {}", output.restart_policy);
    println!("  Max restarts: {}", output.max_restarts);
    if let Some(delay) = output.restart_delay {
        println!("  Restart delay: {delay}s");
    }
    if let Some(timeout) = output.health_check_timeout {
        println!("  Health check timeout: {timeout}s");
    }
    if let Some(grace) = output.finish_grace_secs {
        println!("  Finish grace: {grace}s");
    }
    println!();

    // Inputs
    println!("{}", "Inputs:".bold());
    if output.inputs.is_empty() {
        println!("  <none>");
    } else {
        let mut tw = TabWriter::new(std::io::stdout().lock());
        for input in &output.inputs {
            let _ = tw.write_all(format!("  {}\t<- {}\n", input.id, input.source).as_bytes());
        }
        let _ = tw.flush();
    }
    println!();

    // Outputs
    println!("{}", "Outputs:".bold());
    if output.outputs.is_empty() {
        println!("  <none>");
    } else {
        for out in &output.outputs {
            if out.subscribers.is_empty() {
                println!("  {} (no subscribers)", out.id);
            } else {
                println!("  {} -> {}", out.id, out.subscribers.join(", "));
            }
        }
    }
    println!();

    // Runtime metrics
    println!("{}", "Runtime Metrics:".bold());
    if let Some(metrics) = &output.metrics {
        let mut tw = TabWriter::new(std::io::stdout().lock());
        let _ = tw.write_all(format!("  Status:\t{}\n", metrics.status).as_bytes());
        let _ = tw.write_all(format!("  PID:\t{}\n", metrics.pid).as_bytes());
        let _ = tw.write_all(format!("  CPU:\t{}\n", metrics.cpu).as_bytes());
        let _ = tw.write_all(format!("  Memory:\t{}\n", metrics.memory).as_bytes());
        let _ = tw.write_all(format!("  Restarts:\t{}\n", metrics.restart_count).as_bytes());
        let _ = tw.write_all(format!("  Pending msgs:\t{}\n", metrics.pending_messages).as_bytes());
        if !metrics.broken_inputs.is_empty() {
            let _ = tw.write_all(
                format!("  Broken inputs:\t{}\n", metrics.broken_inputs.join(", ")).as_bytes(),
            );
        }
        let _ = tw.flush();
    } else {
        println!("  <not running or metrics unavailable>");
    }
}

#[cfg(test)]
mod tests {
    use super::{build_input_info, build_output_info};
    use dora_message::descriptor::{Descriptor, Node};

    fn descriptor() -> Descriptor {
        serde_yaml::from_str(
            "\
nodes:
  - id: camera
    path: camera
    outputs:
      - frame
  - id: detect
    operator:
      python: detect.py
      inputs:
        image: camera/frame
      outputs:
        - boxes
  - id: sink
    path: sink
    inputs:
      boxes: detect/boxes
",
        )
        .expect("parse descriptor")
    }

    fn node<'a>(descriptor: &'a Descriptor, id: &str) -> &'a Node {
        descriptor
            .nodes
            .iter()
            .find(|n| n.id.to_string() == id)
            .expect("node in fixture")
    }

    // Regression: `dora node info` read the raw `node.inputs`, which is empty
    // for `operator:` nodes (their ports live under `operator.config`), so it
    // reported no inputs for operator-backed nodes (dora-rs/dora#2893).
    #[test]
    fn operator_node_inputs_are_reported() {
        let d = descriptor();
        let ids: Vec<_> = build_input_info(node(&d, "detect"))
            .into_iter()
            .map(|i| i.id)
            .collect();
        assert!(
            ids.iter().any(|id| id == "image"),
            "operator input missing: {ids:?}"
        );
    }

    // The output listing and its subscriber scan must likewise see operator
    // ports: `detect/boxes` is produced by an operator and consumed by `sink`.
    #[test]
    fn operator_node_outputs_and_subscribers_are_reported() {
        let d = descriptor();
        let outputs = build_output_info(node(&d, "detect"), &d);
        let boxes = outputs
            .iter()
            .find(|o| o.id == "boxes")
            .expect("operator output `boxes` should be listed");
        assert!(
            boxes.subscribers.iter().any(|s| s == "sink/boxes"),
            "operator-node subscriber missing: {:?}",
            boxes.subscribers
        );
    }
}