ic-query-cli 0.104.1

Command-line wrapper for read-only Internet Computer metadata queries
Documentation
//! Module: ic::node_status
//!
//! Responsibility: human-readable observed node, Subnet, provider, and refresh reports.
//! Does not own: source collection, cache policy, projection, or JSON output.
//! Boundary: keeps compact operational display separate from raw report fields.

use crate::presentation::text_value::field;
use crate::presentation::text_value::table;
use ic_host_text::escape::terminal_text;
use ic_host_text::table::Alignment;

use crate::presentation::text_value::yes_no;
use ic_query::ic::IcNodeAssignmentStatusCounts;
use ic_query::ic::IcNodeCountComparisonCounts;
use ic_query::ic::IcNodeProviderStatusReport;
use ic_query::ic::IcNodeStatusCounts;
use ic_query::ic::IcNodeStatusObservation;

use ic_query::ic::IcNodeStatusRefreshReport;
use ic_query::ic::IcNodeStatusReport;
use ic_query::ic::IcNodeStatusRow;
use ic_query::ic::IcSubnetStatusReport;

const COMPACT_PRINCIPAL_CHARS: usize = 8;

/// Render a human-readable node-level operational status report.
#[must_use]
pub fn ic_node_status_report_text(report: &IcNodeStatusReport) -> String {
    let mut sections = observation_lines(&report.observation);
    sections.push(counts_line("nodes", &report.counts.statuses));
    sections.push(assignment_status_line(&report.counts.assignment_statuses));
    crate::presentation::text_value::push_section(
        &mut sections,
        None,
        render_node_table(report.nodes.iter()),
    );
    sections.join("\n")
}

/// Render a human-readable Subnet operational status report.
#[must_use]
pub fn ic_subnet_status_report_text(report: &IcSubnetStatusReport) -> String {
    let mut sections = observation_lines(&report.observation);
    sections.push(format!(
        "subnets: total={} attention={} returned={} assigned_nodes={}",
        report.subnet_count,
        report.attention_subnet_count,
        report.subnets.len(),
        report.assigned_node_count
    ));
    let headers = [
        "SUBNET",
        "NODES",
        "UP",
        "DEGRADED",
        "DOWN",
        "DISABLED",
        "UNKNOWN",
        "F",
        "+DOWN >F",
        "+NON-UP >F",
    ];
    let rows = report
        .subnets
        .iter()
        .map(|row| {
            [
                compact(&row.subnet_id),
                row.statuses.total.to_string(),
                row.statuses.up.to_string(),
                row.statuses.degraded.to_string(),
                row.statuses.down.to_string(),
                row.statuses.disabled.to_string(),
                row.statuses.unknown.to_string(),
                row.fault_tolerance_node_count.to_string(),
                row.additional_down_nodes_to_exceed_fault_tolerance
                    .to_string(),
                row.additional_non_up_nodes_to_exceed_fault_tolerance
                    .to_string(),
            ]
        })
        .collect::<Vec<_>>();
    crate::presentation::text_value::push_section(
        &mut sections,
        None,
        table(
            &headers,
            &rows,
            &[
                Alignment::Left,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
            ],
        ),
    );
    let mut non_up = report
        .subnets
        .iter()
        .flat_map(|subnet| subnet.non_up_nodes.iter())
        .peekable();
    if non_up.peek().is_some() {
        sections.push(String::new());
        sections.push("non-up node evidence:".to_string());
        sections.push(render_node_table(non_up));
    }
    sections.join("\n")
}

/// Render a human-readable node-provider operational status report.
#[must_use]
pub fn ic_node_provider_status_report_text(report: &IcNodeProviderStatusReport) -> String {
    let mut sections = observation_lines(&report.observation);
    sections.push(format!(
        "node_providers: total={} attention={} returned={}",
        report.provider_count,
        report.attention_provider_count,
        report.providers.len()
    ));
    sections.push(format!(
        "unassigned_vs_assigned providers (less/equal/greater): up={} non_up={}",
        comparison_counts_text(&report.unassigned_up_vs_assigned_up_provider_counts),
        comparison_counts_text(&report.unassigned_non_up_vs_assigned_non_up_provider_counts),
    ));
    let headers = [
        "NODE PROVIDER",
        "NAME",
        "NODES",
        "UP",
        "DEGRADED",
        "DOWN",
        "DISABLED",
        "UNKNOWN",
        "ASSIGNED UP/NON-UP",
        "UNASSIGNED UP/NON-UP",
        "API BN UP/NON-UP",
        "UNKNOWN ASN UP/NON-UP",
        "UNASN VS ASN UP/NON-UP",
    ];
    let rows = report
        .providers
        .iter()
        .map(|row| {
            [
                compact(&row.node_provider_id),
                row.node_provider_name.clone(),
                row.counts.statuses.total.to_string(),
                row.counts.statuses.up.to_string(),
                row.counts.statuses.degraded.to_string(),
                row.counts.statuses.down.to_string(),
                row.counts.statuses.disabled.to_string(),
                row.counts.statuses.unknown.to_string(),
                up_non_up(&row.counts.assignment_statuses.assigned),
                up_non_up(&row.counts.assignment_statuses.unassigned),
                up_non_up(&row.counts.assignment_statuses.api_boundary),
                up_non_up(&row.counts.assignment_statuses.unknown),
                format!(
                    "{}/{}",
                    row.unassigned_up_vs_assigned_up.as_str(),
                    row.unassigned_non_up_vs_assigned_non_up.as_str()
                ),
            ]
        })
        .collect::<Vec<_>>();
    crate::presentation::text_value::push_section(
        &mut sections,
        None,
        table(
            &headers,
            &rows,
            &[
                Alignment::Left,
                Alignment::Left,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Right,
                Alignment::Left,
            ],
        ),
    );
    sections.join("\n")
}

/// Render a human-readable forced node-status cache refresh report.

#[must_use]
pub fn ic_node_status_refresh_report_text(report: &IcNodeStatusRefreshReport) -> String {
    [
        field("network", &report.network),
        field("fetched_at", &report.fetched_at),
        field("source_endpoint", &report.source_endpoint),
        counts_line("nodes", &report.counts.statuses),
        assignment_status_line(&report.counts.assignment_statuses),
        field(
            "replaced_existing_cache",
            &(yes_no(report.replaced_existing_cache)),
        ),
        field("cache_path", &report.cache_path),
        field("refresh_lock_path", &report.refresh_lock_path),
    ]
    .join("\n")
}

fn observation_lines(observation: &IcNodeStatusObservation) -> Vec<String> {
    let mut lines = vec![format!(
        "observed node status: network={} fetched_at={} source={} certified={} point_in_time={}",
        terminal_text(&observation.source.network),
        terminal_text(&observation.source.fetched_at),
        terminal_text(&observation.source.source_endpoint),
        yes_no(observation.source.certified),
        yes_no(observation.source.point_in_time_guaranteed)
    )];
    lines.push(format!(
        "scope: {} cloud_engine_nodes_included={}",
        observation.scope.as_str(),
        yes_no(observation.cloud_engine_nodes_included)
    ));
    if let Some(cache) = &observation.cache {
        lines.push(format!(
            "cache: fresh={} age={}s stale_after={}s path={}",
            yes_no(cache.cache_fresh),
            cache.age_seconds,
            cache.stale_after_seconds,
            terminal_text(&cache.cache_path)
        ));
    }
    lines
}

fn counts_line(label: &str, counts: &IcNodeStatusCounts) -> String {
    format!(
        "{label}: total={} up={} degraded={} down={} disabled={} unknown={} non_up={}",
        counts.total,
        counts.up,
        counts.degraded,
        counts.down,
        counts.disabled,
        counts.unknown,
        counts.non_up()
    )
}

fn assignment_status_line(counts: &IcNodeAssignmentStatusCounts) -> String {
    format!(
        "assignments (total/up/non_up): assigned={}/{}/{} unassigned={}/{}/{} api_boundary={}/{}/{} unknown={}/{}/{}",
        counts.assigned.total,
        counts.assigned.up,
        counts.assigned.non_up(),
        counts.unassigned.total,
        counts.unassigned.up,
        counts.unassigned.non_up(),
        counts.api_boundary.total,
        counts.api_boundary.up,
        counts.api_boundary.non_up(),
        counts.unknown.total,
        counts.unknown.up,
        counts.unknown.non_up()
    )
}

fn up_non_up(counts: &IcNodeStatusCounts) -> String {
    format!("{}/{}", counts.up, counts.non_up())
}

fn comparison_counts_text(counts: &IcNodeCountComparisonCounts) -> String {
    format!("{}/{}/{}", counts.less, counts.equal, counts.greater)
}

fn render_node_table<'a>(nodes: impl IntoIterator<Item = &'a IcNodeStatusRow>) -> String {
    let headers = ["NODE", "STATUS", "TYPE", "SUBNET", "PROVIDER", "ALERT"];
    let rows = nodes
        .into_iter()
        .map(|node| {
            [
                compact(&node.node_id),
                node.status.clone(),
                node.node_type.clone(),
                node.subnet_id
                    .as_deref()
                    .map_or_else(|| "-".to_string(), compact),
                compact(&node.node_provider_id),
                node.alert_name
                    .as_deref()
                    .map_or_else(|| "-".to_string(), str::to_string),
            ]
        })
        .collect::<Vec<_>>();
    table(&headers, &rows, &[Alignment::Left; 6])
}

fn compact(value: &str) -> String {
    crate::presentation::text_value::compact_text(value, COMPACT_PRINCIPAL_CHARS)
}