Skip to main content

astrs_cli/command/
top.rs

1//! `astrs top` (blueprint §13, §17): the live TUI monitor, against a
2//! coordinator or (`--replay`) an `.arec` recording.
3//!
4//! This is the one verb in the CLI that hands control to
5//! [`astrs_tui::run`] rather than printing a report: there is no `--json`
6//! form, because there is no batch output to serialize — the whole point
7//! is the interactive view.
8
9use std::path::PathBuf;
10use std::time::Duration;
11
12use astrs_tui::{App, ClusterView, CoordinatorSource, ReplaySource};
13
14use crate::command::client::Endpoint;
15use crate::error::CliError;
16
17/// How often the render loop redraws and polls
18/// [`astrs_tui::ClusterView::refresh`] (blueprint: responsive resize, no
19/// busy-poll).
20const TICK_RATE: Duration = Duration::from_millis(250);
21
22/// `astrs top`'s arguments.
23#[derive(Debug, Clone, Default)]
24pub struct TopArgs {
25    /// Render this recording instead of dialling a coordinator.
26    pub replay: Option<PathBuf>,
27}
28
29/// Runs `astrs top`: opens the TUI against `endpoint`, or against
30/// `args.replay` when set — in which case `endpoint` is never dialled.
31///
32/// # Errors
33///
34/// - [`CliError::Replay`] if `--replay` names a file that cannot be
35///   opened as an `.arec` recording.
36/// - [`CliError::CoordinatorSource`] if the live connection cannot be
37///   established.
38/// - [`CliError::Tui`] if the terminal cannot be entered (not a TTY,
39///   raw-mode setup failed, …) or the render loop itself fails.
40pub fn run(endpoint: &Endpoint, args: &TopArgs) -> Result<(), CliError> {
41    let view: Box<dyn ClusterView> = match &args.replay {
42        Some(path) => Box::new(ReplaySource::open(path)?),
43        None => Box::new(CoordinatorSource::connect(
44            endpoint.addr,
45            endpoint.token.clone(),
46        )?),
47    };
48    let app = App::new(view);
49    astrs_tui::run(app, TICK_RATE)?;
50    Ok(())
51}
52
53#[cfg(test)]
54mod tests {
55    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
56
57    use astrs_wire::AuthToken;
58
59    use super::*;
60
61    fn endpoint() -> Endpoint {
62        // Port 1 on loopback: never bound by this suite, refused instantly.
63        Endpoint::new(
64            std::net::SocketAddr::from(([127, 0, 0, 1], 1)),
65            AuthToken::ZERO,
66        )
67    }
68
69    #[test]
70    fn a_dead_coordinator_is_reported_rather_than_entering_the_terminal() {
71        let args = TopArgs::default();
72        let error = run(&endpoint(), &args).unwrap_err();
73        assert!(matches!(error, CliError::CoordinatorSource(_)));
74    }
75
76    #[test]
77    fn a_missing_replay_file_is_reported_rather_than_entering_the_terminal() {
78        let args = TopArgs {
79            replay: Some(std::env::temp_dir().join(format!(
80                "astrs-cli-top-test-does-not-exist-{}.arec",
81                std::process::id()
82            ))),
83        };
84        let error = run(&endpoint(), &args).unwrap_err();
85        assert!(matches!(error, CliError::Replay(_)));
86    }
87}