Skip to main content

astrs_cli/command/
param.rs

1//! `astrs param get/set/list/delete` (blueprint §17's Graph-ops row).
2//!
3//! ```text
4//!   astrs param set <ref> <key> 30     ─► SetParam{scope,key,Integer(30)} ─► Ok
5//!   astrs param get <ref> <key>        ─► GetParam{scope,key,inherited}   ─► ParamValue
6//!   astrs param list <ref> [--node n]  ─► GetParams{scope,prefix}         ─► ParamList
7//!   astrs param delete <ref> <key>     ─► DeleteParam{scope,key}          ─► Ok
8//! ```
9//!
10//! # Three scopes, one positional word
11//!
12//! [`astrs_wire::ParamScope`] has three levels — global, one dataflow, one
13//! node — and the CLI spells all three with the argument a user already
14//! types: the dataflow reference, plus an optional `--node`. The literal
15//! word `global` in the dataflow position selects
16//! [`astrs_wire::ParamScope::Global`], which is how a cluster-wide default
17//! is written without inventing a flag for it.
18//!
19//! # Values are plain JSON, not the wire's tagged form
20//!
21//! [`astrs_wire::Parameter`] serializes as an externally tagged enum
22//! (`{"integer": 30}`), which is the right thing on the wire and the wrong
23//! thing to make a human type. `astrs param set flow camera.fps 30` takes
24//! plain JSON — `30`, `1.5`, `true`, `"left"`, `[1,2,3]` — and infers the
25//! variant, exactly as a user expects. The tagged spelling is still
26//! accepted for the one case inference cannot serve: pinning a whole number
27//! as a float (`'{"float": 30}'`).
28
29use std::io::Write;
30use std::time::Duration;
31
32use astrs_wire::{ControlReply, ControlRequest, NodeId, ParamKey, ParamScope, Parameter};
33
34use crate::command::client::{Client, DataflowRef, Endpoint, reply_name, runtime};
35use crate::command::signals::Signals;
36use crate::error::CliError;
37
38/// The word that selects [`ParamScope::Global`] in the dataflow position.
39pub const GLOBAL_SCOPE_WORD: &str = "global";
40
41/// Where a parameter lives, before the dataflow reference is resolved.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum ScopeRef {
44    /// Cluster-wide defaults.
45    Global,
46    /// One dataflow's parameters.
47    Dataflow(DataflowRef),
48    /// One node's parameters.
49    Node(DataflowRef, NodeId),
50}
51
52impl ScopeRef {
53    /// Classifies the `<dataflow> [--node <id>]` pair a user typed.
54    ///
55    /// # Errors
56    ///
57    /// [`CliError::BadArgument`] if `--node` is not a usable node id, or if
58    /// a node scope was asked for inside the global scope (there is no such
59    /// thing: a node belongs to a dataflow).
60    pub fn parse(dataflow: &str, node: Option<&str>) -> Result<Self, CliError> {
61        let node = match node {
62            Some(text) => Some(NodeId::new(text).map_err(|error| CliError::BadArgument {
63                flag: "node",
64                value: text.to_owned(),
65                reason: error.to_string(),
66            })?),
67            None => None,
68        };
69        if dataflow.trim().eq_ignore_ascii_case(GLOBAL_SCOPE_WORD) {
70            return match node {
71                None => Ok(Self::Global),
72                Some(node) => Err(CliError::BadArgument {
73                    flag: "node",
74                    value: node.as_str().to_owned(),
75                    reason: "the global scope has no nodes; name a dataflow instead".to_owned(),
76                }),
77            };
78        }
79        let reference = DataflowRef::parse(dataflow);
80        Ok(match node {
81            Some(node) => Self::Node(reference, node),
82            None => Self::Dataflow(reference),
83        })
84    }
85
86    /// Resolves this scope against a connected coordinator.
87    ///
88    /// # Errors
89    ///
90    /// As [`Client::resolve`].
91    pub async fn resolve(&self, client: &mut Client) -> Result<ParamScope, CliError> {
92        Ok(match self {
93            Self::Global => ParamScope::Global,
94            Self::Dataflow(reference) => ParamScope::Dataflow {
95                dataflow: client.resolve(reference).await?,
96            },
97            Self::Node(reference, node) => ParamScope::Node {
98                dataflow: client.resolve(reference).await?,
99                node: node.clone(),
100            },
101        })
102    }
103}
104
105/// A human name for a resolved scope, for output.
106#[must_use]
107pub fn scope_name(scope: &ParamScope) -> String {
108    match scope {
109        ParamScope::Global => GLOBAL_SCOPE_WORD.to_owned(),
110        ParamScope::Dataflow { dataflow } => dataflow.to_string(),
111        ParamScope::Node { dataflow, node } => format!("{dataflow}/{}", node.as_str()),
112        // `ParamScope` is `#[non_exhaustive]`: a scope added at the tail
113        // still has to be nameable.
114        _ => "an unknown scope".to_owned(),
115    }
116}
117
118/// Arguments shared by every parameter verb.
119#[derive(Debug, Clone)]
120pub struct ScopeArgs {
121    /// The dataflow (or the word `global`).
122    pub dataflow: String,
123    /// The node, for a node-scoped parameter.
124    pub node: Option<String>,
125    /// Emit JSON rather than a human line.
126    pub json: bool,
127}
128
129/// Reads one parameter.
130///
131/// Inherited by default: a node that does not set `camera.fps` should see
132/// its dataflow's value, and a dataflow that does not set it should see the
133/// cluster's — which is the whole point of having three scopes. `--exact`
134/// turns the fallback off for the one caller that must know *where* a value
135/// lives rather than what it is.
136///
137/// # Errors
138///
139/// - [`CliError::BadArgument`] if the key or `--node` is unusable.
140/// - [`CliError::UnknownDataflow`] if the reference resolves to nothing.
141/// - As [`Client::request`] otherwise.
142pub fn get(
143    out: &mut dyn Write,
144    endpoint: &Endpoint,
145    args: &ScopeArgs,
146    key: &str,
147    inherited: bool,
148) -> Result<Option<Parameter>, CliError> {
149    let scope_ref = ScopeRef::parse(&args.dataflow, args.node.as_deref())?;
150    let key = parse_key(key)?;
151    let runtime = runtime()?;
152    let (value, scope) = runtime.block_on(async {
153        let mut client = Client::connect(endpoint).await?;
154        let scope = scope_ref.resolve(&mut client).await?;
155        match client
156            .request(
157                "param get",
158                &ControlRequest::GetParam {
159                    scope: scope.clone(),
160                    key: key.clone(),
161                    inherited,
162                },
163            )
164            .await?
165        {
166            ControlReply::ParamValue { value, scope, .. } => Ok((value, scope)),
167            other => Err(CliError::UnexpectedReply {
168                request: "param get",
169                reply: reply_name(&other),
170            }),
171        }
172    })?;
173
174    if args.json {
175        emit_json(
176            out,
177            &serde_json::json!({
178                "key": key.as_str(),
179                "scope": scope_name(&scope),
180                "found": value.is_some(),
181                "value": value.as_ref().map(to_plain_json),
182                "type": value.as_ref().map(|value| value.type_name()),
183            }),
184        );
185    } else {
186        match &value {
187            Some(value) => {
188                let _ = writeln!(out, "{value}");
189            }
190            None => {
191                let _ = writeln!(out, "{} is not set in {}", key.as_str(), scope_name(&scope));
192            }
193        }
194        let _ = out.flush();
195    }
196    Ok(value)
197}
198
199/// How often `watch` polls [`ControlRequest::GetParam`].
200///
201/// There is no `ParamSubscribe` verb (§7.3's frozen family has `Log`/`Topic`
202/// subscriptions, not a third one for parameters) — see this crate's final
203/// report — so `--watch` polls rather than opens a push subscription like
204/// `astrs logs -f`/`astrs topic echo` do. Every transition is still seen;
205/// what polling gives up is *when within a poll interval* it was written,
206/// and a revision that lands and is immediately overwritten between two
207/// polls, neither of which this flag's own `--help` overstates.
208pub const WATCH_POLL_INTERVAL: Duration = Duration::from_millis(500);
209
210/// Watches one parameter, printing every value it transitions to.
211///
212/// Prints the value already set (if any) once at the start, then again
213/// only when a poll observes a different value than the last one printed
214/// — two consecutive polls seeing the same value print nothing, which is
215/// what makes this a *change* feed rather than a heartbeat. Runs until
216/// `count` distinct values have been observed (the initial read counts as
217/// one), or, when `count` is `None`, until interrupted (`Ctrl-C`/`SIGTERM`).
218///
219/// `count` is what makes this function callable from a test: unbounded,
220/// the only way to end it is a signal, which a deadline-polled assertion
221/// cannot wait on without racing the harness's own signal handling. A
222/// caller that wants the production "stream forever" behaviour passes
223/// `None`, exactly as `--watch` does without `--count`.
224///
225/// # Errors
226///
227/// As [`get`] for the first read; a transport failure on a later poll ends
228/// the watch with that error rather than retrying forever, so a coordinator
229/// that goes away is visible rather than silently watched forever.
230pub fn watch(
231    out: &mut dyn Write,
232    endpoint: &Endpoint,
233    args: &ScopeArgs,
234    key: &str,
235    inherited: bool,
236    count: Option<u32>,
237) -> Result<Vec<Option<Parameter>>, CliError> {
238    let scope_ref = ScopeRef::parse(&args.dataflow, args.node.as_deref())?;
239    let key = parse_key(key)?;
240    let runtime = runtime()?;
241    runtime.block_on(async move {
242        let mut client = Client::connect(endpoint).await?;
243        let scope = scope_ref.resolve(&mut client).await?;
244        let mut last: Option<Option<Parameter>> = None;
245        let mut seen = Vec::new();
246        let mut signals = Signals::install();
247        loop {
248            let value = match client
249                .request(
250                    "param watch",
251                    &ControlRequest::GetParam {
252                        scope: scope.clone(),
253                        key: key.clone(),
254                        inherited,
255                    },
256                )
257                .await?
258            {
259                ControlReply::ParamValue { value, .. } => value,
260                other => {
261                    return Err(CliError::UnexpectedReply {
262                        request: "param watch",
263                        reply: reply_name(&other),
264                    });
265                }
266            };
267            if last.as_ref() != Some(&value) {
268                print_watch_line(out, &key, &scope, &value, args.json);
269                seen.push(value.clone());
270                last = Some(value);
271                if count.is_some_and(|limit| seen.len() >= limit as usize) {
272                    break;
273                }
274            }
275            tokio::select! {
276                () = tokio::time::sleep(WATCH_POLL_INTERVAL) => {}
277                () = signals.next() => break,
278            }
279        }
280        Ok(seen)
281    })
282}
283
284/// Prints one `--watch` transition.
285fn print_watch_line(
286    out: &mut dyn Write,
287    key: &ParamKey,
288    scope: &ParamScope,
289    value: &Option<Parameter>,
290    json: bool,
291) {
292    if json {
293        let _ = writeln!(
294            out,
295            "{}",
296            serde_json::json!({
297                "key": key.as_str(),
298                "scope": scope_name(scope),
299                "value": value.as_ref().map(to_plain_json),
300                "type": value.as_ref().map(Parameter::type_name),
301            })
302        );
303    } else {
304        match value {
305            Some(value) => {
306                let _ = writeln!(out, "{} = {value} ({})", key.as_str(), value.type_name());
307            }
308            None => {
309                let _ = writeln!(out, "{} is unset", key.as_str());
310            }
311        }
312    }
313    let _ = out.flush();
314}
315
316/// Writes one parameter.
317///
318/// # Errors
319///
320/// - [`CliError::BadArgument`] if the key, `--node` or the value is
321///   unusable.
322/// - [`CliError::Refused`] if `--create-only` was given and the key exists.
323/// - As [`Client::request`] otherwise.
324pub fn set(
325    out: &mut dyn Write,
326    endpoint: &Endpoint,
327    args: &ScopeArgs,
328    key: &str,
329    value: &str,
330    create_only: bool,
331) -> Result<Parameter, CliError> {
332    let scope_ref = ScopeRef::parse(&args.dataflow, args.node.as_deref())?;
333    let key = parse_key(key)?;
334    let parameter = parse_value(value)?;
335    let runtime = runtime()?;
336    let scope = runtime.block_on(async {
337        let mut client = Client::connect(endpoint).await?;
338        let scope = scope_ref.resolve(&mut client).await?;
339        client
340            .request_ok(
341                "param set",
342                &ControlRequest::SetParam {
343                    scope: scope.clone(),
344                    key: key.clone(),
345                    value: parameter.clone(),
346                    create_only,
347                },
348            )
349            .await?;
350        Ok::<ParamScope, CliError>(scope)
351    })?;
352
353    if args.json {
354        emit_json(
355            out,
356            &serde_json::json!({
357                "key": key.as_str(),
358                "scope": scope_name(&scope),
359                "value": to_plain_json(&parameter),
360                "type": parameter.type_name(),
361            }),
362        );
363    } else {
364        let _ = writeln!(
365            out,
366            "{} = {parameter} ({}) in {}",
367            key.as_str(),
368            parameter.type_name(),
369            scope_name(&scope)
370        );
371        let _ = out.flush();
372    }
373    Ok(parameter)
374}
375
376/// Lists a scope's parameters.
377///
378/// # Errors
379///
380/// As [`get`], plus [`CliError::UnexpectedReply`] for a non-`ParamList`
381/// answer.
382pub fn list(
383    out: &mut dyn Write,
384    endpoint: &Endpoint,
385    args: &ScopeArgs,
386    prefix: Option<&str>,
387    inherited: bool,
388) -> Result<Vec<(ParamKey, Parameter)>, CliError> {
389    let scope_ref = ScopeRef::parse(&args.dataflow, args.node.as_deref())?;
390    let runtime = runtime()?;
391    let (params, scope) = runtime.block_on(async {
392        let mut client = Client::connect(endpoint).await?;
393        let scope = scope_ref.resolve(&mut client).await?;
394        match client
395            .request(
396                "param list",
397                &ControlRequest::GetParams {
398                    scope: scope.clone(),
399                    prefix: prefix.map(ToOwned::to_owned),
400                    inherited,
401                },
402            )
403            .await?
404        {
405            ControlReply::ParamList { params, scope } => Ok((params, scope)),
406            other => Err(CliError::UnexpectedReply {
407                request: "param list",
408                reply: reply_name(&other),
409            }),
410        }
411    })?;
412
413    if args.json {
414        emit_json(
415            out,
416            &serde_json::json!({
417                "scope": scope_name(&scope),
418                "count": params.len(),
419                "params": params
420                    .iter()
421                    .map(|(key, value)| serde_json::json!({
422                        "key": key.as_str(),
423                        "value": to_plain_json(value),
424                        "type": value.type_name(),
425                    }))
426                    .collect::<Vec<_>>(),
427            }),
428        );
429    } else {
430        if params.is_empty() {
431            let _ = writeln!(out, "no parameters in {}", scope_name(&scope));
432        }
433        for (key, value) in &params {
434            let _ = writeln!(out, "{:<32} {value}", key.as_str());
435        }
436        let _ = out.flush();
437    }
438    Ok(params)
439}
440
441/// Deletes one parameter.
442///
443/// # Errors
444///
445/// As [`get`].
446pub fn delete(
447    out: &mut dyn Write,
448    endpoint: &Endpoint,
449    args: &ScopeArgs,
450    key: &str,
451) -> Result<(), CliError> {
452    let scope_ref = ScopeRef::parse(&args.dataflow, args.node.as_deref())?;
453    let key = parse_key(key)?;
454    let runtime = runtime()?;
455    let scope = runtime.block_on(async {
456        let mut client = Client::connect(endpoint).await?;
457        let scope = scope_ref.resolve(&mut client).await?;
458        client
459            .request_ok(
460                "param delete",
461                &ControlRequest::DeleteParam {
462                    scope: scope.clone(),
463                    key: key.clone(),
464                },
465            )
466            .await?;
467        Ok::<ParamScope, CliError>(scope)
468    })?;
469
470    if args.json {
471        emit_json(
472            out,
473            &serde_json::json!({
474                "key": key.as_str(),
475                "scope": scope_name(&scope),
476                "deleted": true,
477            }),
478        );
479    } else {
480        let _ = writeln!(out, "deleted {} from {}", key.as_str(), scope_name(&scope));
481        let _ = out.flush();
482    }
483    Ok(())
484}
485
486/// Validates a parameter key.
487///
488/// # Errors
489///
490/// [`CliError::BadArgument`] naming what a key may contain.
491fn parse_key(key: &str) -> Result<ParamKey, CliError> {
492    ParamKey::new(key).map_err(|error| CliError::BadArgument {
493        flag: "key",
494        value: key.to_owned(),
495        reason: error.to_string(),
496    })
497}
498
499/// Turns the JSON a user typed into a [`Parameter`].
500///
501/// # Errors
502///
503/// [`CliError::BadArgument`] when the text is not JSON at all, is a shape
504/// the protocol has no variant for (`null`, a nested object), or is a
505/// mixed-type array.
506pub fn parse_value(text: &str) -> Result<Parameter, CliError> {
507    let refuse = |reason: String| CliError::BadArgument {
508        flag: "value",
509        value: text.to_owned(),
510        reason,
511    };
512    let value: serde_json::Value = serde_json::from_str(text.trim()).map_err(|error| {
513        refuse(format!(
514            "expected JSON (a number, `true`, a quoted string, or an array): {error}"
515        ))
516    })?;
517    from_plain_json(&value).ok_or_else(|| {
518        // The tagged spelling is the escape hatch for the one thing
519        // inference cannot do: `{"float": 30}` for a whole number that must
520        // stay a float.
521        if value.is_object()
522            && let Ok(parameter) = serde_json::from_value::<Parameter>(value.clone())
523        {
524            return CliError::BadArgument {
525                flag: "value",
526                value: text.to_owned(),
527                reason: format!("(unreachable: {parameter} decoded)"),
528            };
529        }
530        refuse(
531            "no parameter type matches that value: use a number, a boolean, a string, a \
532             same-typed array, or the tagged form like `{\"float\": 30}`"
533                .to_owned(),
534        )
535    })
536}
537
538/// The inference [`parse_value`] documents, without the error wrapping.
539fn from_plain_json(value: &serde_json::Value) -> Option<Parameter> {
540    match value {
541        serde_json::Value::Bool(flag) => Some(Parameter::Bool(*flag)),
542        serde_json::Value::Number(number) => number.as_i64().map_or_else(
543            || number.as_f64().map(Parameter::Float),
544            |integer| Some(Parameter::Integer(integer)),
545        ),
546        serde_json::Value::String(text) => Some(Parameter::String(text.clone())),
547        serde_json::Value::Array(items) => from_array(items),
548        // An object may still be the tagged wire form.
549        serde_json::Value::Object(_) => serde_json::from_value::<Parameter>(value.clone()).ok(),
550        serde_json::Value::Null => None,
551    }
552}
553
554/// A JSON array as one of the three list parameters, or `None` when its
555/// elements do not share a type the protocol has a list for.
556///
557/// An *empty* array is a `list_string`: some variant has to be chosen, and
558/// a list of strings is the one that can later hold anything a user meant.
559fn from_array(items: &[serde_json::Value]) -> Option<Parameter> {
560    if items.is_empty() {
561        return Some(Parameter::ListString(Vec::new()));
562    }
563    if items.iter().all(|item| item.is_i64()) {
564        return Some(Parameter::ListInt(
565            items.iter().filter_map(serde_json::Value::as_i64).collect(),
566        ));
567    }
568    if items.iter().all(serde_json::Value::is_number) {
569        return Some(Parameter::ListFloat(
570            items.iter().filter_map(serde_json::Value::as_f64).collect(),
571        ));
572    }
573    if items.iter().all(serde_json::Value::is_string) {
574        return Some(Parameter::ListString(
575            items
576                .iter()
577                .filter_map(|item| item.as_str().map(ToOwned::to_owned))
578                .collect(),
579        ));
580    }
581    None
582}
583
584/// A [`Parameter`] as the plain JSON [`parse_value`] accepts, so
585/// `astrs param get --json | astrs param set` round-trips.
586#[must_use]
587pub fn to_plain_json(value: &Parameter) -> serde_json::Value {
588    match value {
589        Parameter::Bool(flag) => serde_json::json!(flag),
590        Parameter::Integer(integer) => serde_json::json!(integer),
591        Parameter::Float(float) => serde_json::json!(float),
592        Parameter::String(text) => serde_json::json!(text),
593        Parameter::ListInt(items) => serde_json::json!(items),
594        Parameter::ListFloat(items) => serde_json::json!(items),
595        Parameter::ListString(items) => serde_json::json!(items),
596        Parameter::Timestamp(stamp) => serde_json::json!(stamp.to_string()),
597        // A tail-appended variant (§3) has no plain spelling yet; the
598        // tagged form is always correct, so fall back to it rather than
599        // guessing.
600        other => serde_json::to_value(other).unwrap_or(serde_json::Value::Null),
601    }
602}
603
604/// Writes one JSON object.
605fn emit_json(out: &mut dyn Write, value: &serde_json::Value) {
606    let _ = writeln!(
607        out,
608        "{}",
609        serde_json::to_string_pretty(value).unwrap_or_else(|_| "{}".to_owned())
610    );
611    let _ = out.flush();
612}
613
614#[cfg(test)]
615mod tests {
616    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
617
618    use super::*;
619    use astrs_wire::{AuthToken, DataflowId};
620
621    fn endpoint() -> Endpoint {
622        Endpoint::new(
623            std::net::SocketAddr::from(([127, 0, 0, 1], 1)),
624            AuthToken::ZERO,
625        )
626    }
627
628    fn args(dataflow: &str, node: Option<&str>) -> ScopeArgs {
629        ScopeArgs {
630            dataflow: dataflow.to_owned(),
631            node: node.map(ToOwned::to_owned),
632            json: false,
633        }
634    }
635
636    #[test]
637    fn the_word_global_selects_the_global_scope() {
638        assert_eq!(ScopeRef::parse("global", None).unwrap(), ScopeRef::Global);
639        assert_eq!(ScopeRef::parse("GLOBAL", None).unwrap(), ScopeRef::Global);
640    }
641
642    #[test]
643    fn a_node_inside_the_global_scope_is_refused() {
644        let error = ScopeRef::parse("global", Some("cam")).unwrap_err();
645        match error {
646            CliError::BadArgument { flag, reason, .. } => {
647                assert_eq!(flag, "node");
648                assert!(reason.contains("no nodes"), "{reason}");
649            }
650            other => panic!("expected BadArgument, got {other}"),
651        }
652    }
653
654    #[test]
655    fn a_dataflow_and_a_node_scope_are_told_apart() {
656        assert!(matches!(
657            ScopeRef::parse("perception", None).unwrap(),
658            ScopeRef::Dataflow(DataflowRef::Name(_))
659        ));
660        let id = DataflowId::generate();
661        assert!(matches!(
662            ScopeRef::parse(&id.to_string(), Some("cam")).unwrap(),
663            ScopeRef::Node(DataflowRef::Id(_), _)
664        ));
665    }
666
667    #[test]
668    fn an_unusable_node_id_is_refused_before_anything_is_dialled() {
669        let error = ScopeRef::parse("flow", Some("not a node")).unwrap_err();
670        assert!(matches!(error, CliError::BadArgument { .. }), "{error}");
671    }
672
673    #[test]
674    fn a_resolved_scope_has_a_readable_name() {
675        assert_eq!(scope_name(&ParamScope::Global), "global");
676        let id = DataflowId::from_u128(9);
677        assert_eq!(
678            scope_name(&ParamScope::Dataflow { dataflow: id }),
679            id.to_string()
680        );
681        assert_eq!(
682            scope_name(&ParamScope::node(id, NodeId::new("cam").unwrap())),
683            format!("{id}/cam")
684        );
685    }
686
687    #[test]
688    fn plain_json_scalars_infer_their_parameter_type() {
689        assert_eq!(parse_value("30").unwrap(), Parameter::Integer(30));
690        assert_eq!(parse_value("-1").unwrap(), Parameter::Integer(-1));
691        assert_eq!(parse_value("1.5").unwrap(), Parameter::Float(1.5));
692        assert_eq!(parse_value("true").unwrap(), Parameter::Bool(true));
693        assert_eq!(
694            parse_value("\"left\"").unwrap(),
695            Parameter::String("left".to_owned())
696        );
697    }
698
699    #[test]
700    fn arrays_infer_the_matching_list_type() {
701        assert_eq!(
702            parse_value("[1,2,3]").unwrap(),
703            Parameter::ListInt(vec![1, 2, 3])
704        );
705        assert_eq!(
706            parse_value("[1.5,2]").unwrap(),
707            Parameter::ListFloat(vec![1.5, 2.0])
708        );
709        assert_eq!(
710            parse_value("[\"a\",\"b\"]").unwrap(),
711            Parameter::ListString(vec!["a".to_owned(), "b".to_owned()])
712        );
713        assert_eq!(
714            parse_value("[]").unwrap(),
715            Parameter::ListString(Vec::new())
716        );
717    }
718
719    #[test]
720    fn the_tagged_wire_form_is_accepted_for_the_case_inference_cannot_serve() {
721        assert_eq!(
722            parse_value("{\"float\": 30}").unwrap(),
723            Parameter::Float(30.0)
724        );
725    }
726
727    #[test]
728    fn a_value_with_no_parameter_type_is_refused_with_the_text_that_was_typed() {
729        for text in ["null", "{\"nested\": {}}", "[1, \"two\"]", "not json"] {
730            let error = parse_value(text).unwrap_err();
731            match error {
732                CliError::BadArgument { flag, value, .. } => {
733                    assert_eq!(flag, "value");
734                    assert_eq!(value, text);
735                }
736                other => panic!("expected BadArgument for `{text}`, got {other}"),
737            }
738        }
739    }
740
741    #[test]
742    fn every_parameter_round_trips_through_its_plain_json_form() {
743        for parameter in [
744            Parameter::Bool(false),
745            Parameter::Integer(-7),
746            Parameter::Float(0.25),
747            Parameter::String("hi".to_owned()),
748            Parameter::ListInt(vec![1, 2]),
749            Parameter::ListFloat(vec![0.5, 1.5]),
750            Parameter::ListString(vec!["a".to_owned()]),
751        ] {
752            let text = to_plain_json(&parameter).to_string();
753            assert_eq!(parse_value(&text).unwrap(), parameter, "{text}");
754        }
755    }
756
757    #[test]
758    fn a_key_must_be_a_usable_parameter_key() {
759        assert_eq!(parse_key("camera.fps").unwrap().as_str(), "camera.fps");
760        let error = parse_key("not a key").unwrap_err();
761        match error {
762            CliError::BadArgument { flag, .. } => assert_eq!(flag, "key"),
763            other => panic!("expected BadArgument, got {other}"),
764        }
765    }
766
767    #[test]
768    fn every_param_verb_reports_a_dead_cluster_rather_than_hanging() {
769        let endpoint = endpoint();
770        let args = args("flow", None);
771        let get_error = get(&mut Vec::new(), &endpoint, &args, "k", true).unwrap_err();
772        assert!(
773            matches!(get_error, CliError::NoCluster { .. }),
774            "{get_error}"
775        );
776
777        let set_error = set(&mut Vec::new(), &endpoint, &args, "k", "1", false).unwrap_err();
778        assert!(
779            matches!(set_error, CliError::NoCluster { .. }),
780            "{set_error}"
781        );
782
783        let list_error = list(&mut Vec::new(), &endpoint, &args, None, false).unwrap_err();
784        assert!(
785            matches!(list_error, CliError::NoCluster { .. }),
786            "{list_error}"
787        );
788
789        let delete_error = delete(&mut Vec::new(), &endpoint, &args, "k").unwrap_err();
790        assert!(
791            matches!(delete_error, CliError::NoCluster { .. }),
792            "{delete_error}"
793        );
794
795        let watch_error = watch(&mut Vec::new(), &endpoint, &args, "k", true, None).unwrap_err();
796        assert!(
797            matches!(watch_error, CliError::NoCluster { .. }),
798            "{watch_error}"
799        );
800    }
801
802    #[test]
803    fn a_bad_value_is_refused_before_the_dial() {
804        let error = set(
805            &mut Vec::new(),
806            &endpoint(),
807            &args("flow", None),
808            "k",
809            "null",
810            false,
811        )
812        .unwrap_err();
813        assert!(matches!(error, CliError::BadArgument { .. }), "{error}");
814    }
815}