Skip to main content

astrs_cli/command/
record.rs

1//! `astrs record start/stop` (blueprint §14, §17).
2//!
3//! ```text
4//!   astrs record start <flow> out.arec [--only n/o]* [--overwrite]
5//!       ─► RecordStart{dataflow, path, ports, overwrite} ─► Ok
6//!   astrs record stop <flow>
7//!       ─► RecordStop{dataflow}                          ─► Ok
8//! ```
9//!
10//! Both verbs are thin: `astrs-coordinator::handlers::misc` already does
11//! the real work (synthesizing a [`astrs_wire::NodeSource::Recorder`]
12//! node wired to the requested ports and dynamically spawning it, the
13//! same mechanism `astrs node add` uses). This module's job is only to
14//! turn CLI flags into the wire request and the reply into a line of
15//! output.
16
17use std::io::Write;
18
19use astrs_wire::{ControlRequest, PortRef};
20
21use crate::command::client::{Client, DataflowRef, Endpoint, runtime};
22use crate::error::CliError;
23
24/// `astrs record start` arguments, independent of `clap`.
25#[derive(Debug, Clone)]
26pub struct StartArgs {
27    /// The dataflow id (or name) to record.
28    pub dataflow: String,
29    /// The `.arec` file to write.
30    pub output: String,
31    /// `node/output` ports to restrict recording to; every declared
32    /// output of every node when empty (mirrors
33    /// [`astrs_wire::ControlRequest::RecordStart`]'s own "empty records
34    /// every port" contract).
35    pub only: Vec<String>,
36    /// Overwrite an already-recording session at the same path.
37    pub overwrite: bool,
38    /// Emit JSON rather than a human line.
39    pub json: bool,
40}
41
42/// Starts recording a dataflow.
43///
44/// # Errors
45///
46/// - [`CliError::BadArgument`] if an `--only` entry is not a well-formed
47///   `node/output` string.
48/// - [`CliError::UnknownDataflow`] if the dataflow reference resolves to
49///   nothing.
50/// - As [`Client::request_ok`] otherwise.
51pub fn start(out: &mut dyn Write, endpoint: &Endpoint, args: &StartArgs) -> Result<(), CliError> {
52    let ports = parse_ports(&args.only)?;
53    let reference = DataflowRef::parse(&args.dataflow);
54    let runtime = runtime()?;
55    let dataflow = runtime.block_on(async {
56        let mut client = Client::connect(endpoint).await?;
57        let dataflow = client.resolve(&reference).await?;
58        client
59            .request_ok(
60                "record start",
61                &ControlRequest::RecordStart {
62                    dataflow,
63                    path: args.output.clone(),
64                    ports: ports.clone(),
65                    overwrite: args.overwrite,
66                },
67            )
68            .await?;
69        Ok::<_, CliError>(dataflow)
70    })?;
71
72    if args.json {
73        emit_json(
74            out,
75            &serde_json::json!({
76                "dataflow": dataflow.to_string(),
77                "output": args.output,
78                "ports": ports.iter().map(ToString::to_string).collect::<Vec<_>>(),
79            }),
80        );
81    } else {
82        let _ = writeln!(out, "recording {dataflow} to {}", args.output);
83        let _ = out.flush();
84    }
85    Ok(())
86}
87
88/// `astrs record stop` arguments, independent of `clap`.
89#[derive(Debug, Clone)]
90pub struct StopArgs {
91    /// The dataflow id (or name) whose recording should stop.
92    pub dataflow: String,
93    /// Emit JSON rather than a human line.
94    pub json: bool,
95}
96
97/// Stops a dataflow's in-progress recording.
98///
99/// # Errors
100///
101/// - [`CliError::UnknownDataflow`] if the dataflow reference resolves to
102///   nothing.
103/// - [`CliError::Refused`] if the dataflow was not recording (the
104///   coordinator answers `RecordStop` for a non-recording dataflow with
105///   an error, not a silent no-op — see `handlers::misc::record_stop`).
106/// - As [`Client::request_ok`] otherwise.
107pub fn stop(out: &mut dyn Write, endpoint: &Endpoint, args: &StopArgs) -> Result<(), CliError> {
108    let reference = DataflowRef::parse(&args.dataflow);
109    let runtime = runtime()?;
110    let dataflow = runtime.block_on(async {
111        let mut client = Client::connect(endpoint).await?;
112        let dataflow = client.resolve(&reference).await?;
113        client
114            .request_ok("record stop", &ControlRequest::RecordStop { dataflow })
115            .await?;
116        Ok::<_, CliError>(dataflow)
117    })?;
118
119    if args.json {
120        emit_json(
121            out,
122            &serde_json::json!({ "dataflow": dataflow.to_string() }),
123        );
124    } else {
125        let _ = writeln!(out, "stopped recording {dataflow}");
126        let _ = out.flush();
127    }
128    Ok(())
129}
130
131/// Parses every `--only` entry into a [`PortRef`].
132///
133/// # Errors
134///
135/// [`CliError::BadArgument`] naming the first entry that does not parse.
136fn parse_ports(only: &[String]) -> Result<Vec<PortRef>, CliError> {
137    only.iter()
138        .map(|text| {
139            text.parse::<PortRef>()
140                .map_err(|error| CliError::BadArgument {
141                    flag: "only",
142                    value: text.clone(),
143                    reason: error.to_string(),
144                })
145        })
146        .collect()
147}
148
149/// Writes one JSON object.
150///
151/// Duplicated from `command::param`'s own copy rather than shared — see
152/// that module's docs on this crate's small-per-module-helper convention.
153fn emit_json(out: &mut dyn Write, value: &serde_json::Value) {
154    let _ = writeln!(
155        out,
156        "{}",
157        serde_json::to_string_pretty(value).unwrap_or_else(|_| "{}".to_owned())
158    );
159    let _ = out.flush();
160}
161
162#[cfg(test)]
163mod tests {
164    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
165    use super::*;
166
167    #[test]
168    fn parse_ports_accepts_well_formed_entries() {
169        let ports =
170            parse_ports(&["camera/frames".to_string(), "detector/boxes".to_string()]).unwrap();
171        assert_eq!(ports.len(), 2);
172        assert_eq!(ports[0].to_string(), "camera/frames");
173    }
174
175    #[test]
176    fn parse_ports_is_empty_for_an_empty_list() {
177        assert!(parse_ports(&[]).unwrap().is_empty());
178    }
179
180    #[test]
181    fn parse_ports_rejects_a_malformed_entry() {
182        let error = parse_ports(&["not a port".to_string()]).unwrap_err();
183        assert!(matches!(error, CliError::BadArgument { flag: "only", .. }));
184    }
185}