Skip to main content

ic_query/cloud_engine/
text.rs

1//! Module: cloud_engine::text
2//!
3//! Responsibility: render compact human-facing CloudEngine reports.
4//! Does not own: report construction, JSON output, live calls, or process output.
5//! Boundary: formats cycle amounts only for text while JSON retains raw decimal fields.
6
7use crate::text_value::REPORT_TABLE_OPTIONS;
8use ic_host_text::{
9    escape::terminal_text,
10    table::{Alignment, render},
11};
12
13#[cfg(all(feature = "cloud-engine-host", feature = "subnet-catalog-host"))]
14use super::CloudEngineListReport;
15use super::{CloudEngineOperatorReport, CloudEnginePricesReport, CloudEngineReportContext};
16use crate::{
17    human_quantity::decimal_cycle_count_text,
18    text_value::{optional_text, yes_no},
19};
20
21/// Render the Registry CloudEngine inventory and separate operator-binding observations.
22#[cfg(all(feature = "cloud-engine-host", feature = "subnet-catalog-host"))]
23#[must_use]
24pub fn cloud_engine_list_report_text(report: &CloudEngineListReport) -> String {
25    let mut lines = list_context_lines(report);
26    lines.push(String::new());
27    lines.push("CloudEngine subnets".to_string());
28    if report.cloud_engines.is_empty() {
29        lines.push("none".to_string());
30        return lines.join("\n");
31    }
32    lines.push(list_table(report));
33    append_lookup_failures(report, &mut lines);
34    lines.join("\n")
35}
36
37#[cfg(all(feature = "cloud-engine-host", feature = "subnet-catalog-host"))]
38fn list_context_lines(report: &CloudEngineListReport) -> Vec<String> {
39    vec![
40        format!("network: {}", terminal_text(&report.network)),
41        format!(
42            "registry_authority: {}",
43            terminal_text(&report.registry_authority)
44        ),
45        format!("registry_canister_id: {}", report.registry_canister_id),
46        format!("registry_version: {}", report.registry_version),
47        format!("registry_assurance: {}", report.registry_assurance.as_str()),
48        format!(
49            "registry_source_endpoints: {}",
50            report
51                .registry_source_endpoints
52                .iter()
53                .map(|endpoint| terminal_text(endpoint))
54                .collect::<Vec<_>>()
55                .join(", ")
56        ),
57        format!(
58            "catalog_fetched_at: {}",
59            terminal_text(&report.catalog_fetched_at)
60        ),
61        format!(
62            "catalog_cache_disposition: {}",
63            report.catalog_cache_disposition.as_str()
64        ),
65        format!("catalog_stale: {}", yes_no(report.catalog_stale)),
66        String::new(),
67        format!(
68            "control_plane_authority: {}",
69            terminal_text(&report.control_plane_authority)
70        ),
71        format!(
72            "control_plane_canister_id: {}",
73            report.control_plane_canister_id
74        ),
75        format!(
76            "control_plane_source_endpoint: {}",
77            terminal_text(&report.control_plane_source_endpoint)
78        ),
79        format!(
80            "control_plane_fetched_at: {}",
81            terminal_text(&report.control_plane_fetched_at)
82        ),
83        format!(
84            "control_plane_certified: {}",
85            yes_no(report.control_plane_certified)
86        ),
87        format!(
88            "control_plane_point_in_time_guaranteed: {}",
89            yes_no(report.control_plane_point_in_time_guaranteed)
90        ),
91        format!(
92            "control_plane_lookup_attempt_count: {}",
93            report.control_plane_lookup_attempt_count
94        ),
95        format!(
96            "operator_bindings: {} resolved, {} absent, {} failed",
97            report.operator_binding_count,
98            report.missing_operator_binding_count,
99            report.operator_lookup_failure_count
100        ),
101    ]
102}
103
104#[cfg(all(feature = "cloud-engine-host", feature = "subnet-catalog-host"))]
105fn list_table(report: &CloudEngineListReport) -> String {
106    let headers = ["Label", "Subnet", "Nodes", "Binding", "Operator"];
107    let alignments = [
108        Alignment::Left,
109        Alignment::Left,
110        Alignment::Right,
111        Alignment::Left,
112        Alignment::Left,
113    ];
114    let rows = report
115        .cloud_engines
116        .iter()
117        .map(|row| {
118            [
119                terminal_text(&row.subnet_label).into_owned(),
120                row.subnet_id.clone(),
121                row.node_count
122                    .map_or_else(|| "unknown".to_string(), |count| count.to_string()),
123                match &row.operator {
124                    Ok(Some(_)) => "resolved",
125                    Ok(None) => "absent",
126                    Err(_) => "failed",
127                }
128                .to_string(),
129                row.operator
130                    .as_ref()
131                    .ok()
132                    .and_then(Option::as_ref)
133                    .map_or_else(|| "-".to_string(), candid::Principal::to_text),
134            ]
135        })
136        .collect::<Vec<_>>();
137    render(&headers, &rows, &alignments, REPORT_TABLE_OPTIONS)
138}
139
140#[cfg(all(feature = "cloud-engine-host", feature = "subnet-catalog-host"))]
141fn append_lookup_failures(report: &CloudEngineListReport, lines: &mut Vec<String>) {
142    let failures = report
143        .cloud_engines
144        .iter()
145        .filter_map(|row| row.operator.as_ref().err().map(|error| (row, error)))
146        .collect::<Vec<_>>();
147    if !failures.is_empty() {
148        lines.push(String::new());
149        lines.push("Operator lookup failures".to_string());
150        lines.extend(
151            failures
152                .into_iter()
153                .map(|(row, error)| format!("  {}: {}", row.subnet_id, terminal_text(error))),
154        );
155    }
156}
157
158/// Render one CloudEngine Subnet-to-operator report.
159#[must_use]
160pub fn cloud_engine_operator_report_text(report: &CloudEngineOperatorReport) -> String {
161    let mut lines = context_lines(&report.context);
162    lines.extend([
163        format!("subnet_id: {}", report.subnet_id),
164        format!(
165            "operator_binding_present: {}",
166            yes_no(report.operator_binding_present)
167        ),
168        format!(
169            "operator_canister_id: {}",
170            optional_text(report.operator_canister_id.as_ref())
171        ),
172        format!(
173            "engine_owner: {}",
174            optional_text(report.engine_owner.as_ref())
175        ),
176        format!(
177            "platform_admin: {}",
178            optional_text(report.platform_admin.as_ref())
179        ),
180        format!(
181            "caffeine_enabled: {}",
182            report
183                .caffeine_enabled
184                .map_or_else(|| "-".to_string(), |enabled| yes_no(enabled).to_string())
185        ),
186        format!(
187            "claimed_domain_count: {}",
188            report
189                .claimed_domain_count
190                .map_or_else(|| "-".to_string(), |count| count.to_string())
191        ),
192    ]);
193
194    if let Some(domains) = report.claimed_domains.as_ref()
195        && !domains.is_empty()
196    {
197        lines.push(String::new());
198        lines.push("Claimed domains".to_string());
199        lines.extend(
200            domains
201                .iter()
202                .map(|domain| format!("  {}", terminal_text(domain))),
203        );
204    }
205    lines.join("\n")
206}
207
208/// Render one bounded CloudEngine marketplace price report.
209#[must_use]
210pub fn cloud_engine_prices_report_text(report: &CloudEnginePricesReport) -> String {
211    let mut lines = context_lines(&report.context);
212    lines.extend([
213        format!("network_fee: {}", report.network_fee),
214        format!("price_count: {}", report.price_count),
215    ]);
216
217    if !report.prices.is_empty() {
218        let headers = [
219            "Key",
220            "Node type",
221            "Data center",
222            "Provider",
223            "Net/month",
224            "Gross/month",
225            "Updated (ns)",
226        ];
227        let alignments = [
228            Alignment::Left,
229            Alignment::Left,
230            Alignment::Left,
231            Alignment::Left,
232            Alignment::Right,
233            Alignment::Right,
234            Alignment::Right,
235        ];
236        let rows = report
237            .prices
238            .iter()
239            .map(|row| {
240                [
241                    row.key.clone(),
242                    row.node_type.to_string(),
243                    row.data_center_id.as_deref().map_or_else(
244                        || "-".to_string(),
245                        |value| terminal_text(value).into_owned(),
246                    ),
247                    row.provider_id.clone().unwrap_or_else(|| "-".to_string()),
248                    decimal_cycle_count_text(&row.net_cycles_per_month),
249                    decimal_cycle_count_text(&row.gross_cycles_per_month),
250                    row.updated_at_unix_nanos.to_string(),
251                ]
252            })
253            .collect::<Vec<_>>();
254        lines.push(String::new());
255        lines.push("Marketplace prices".to_string());
256        lines.push(render(&headers, &rows, &alignments, REPORT_TABLE_OPTIONS));
257    }
258    lines.join("\n")
259}
260
261fn context_lines(context: &CloudEngineReportContext) -> Vec<String> {
262    vec![
263        format!("network: {}", terminal_text(&context.network)),
264        format!("authority: {}", terminal_text(&context.authority)),
265        format!("engine_canister_id: {}", context.engine_canister_id),
266        format!("fetched_at: {}", terminal_text(&context.fetched_at)),
267        format!(
268            "source_endpoint: {}",
269            terminal_text(&context.source_endpoint)
270        ),
271        format!("fetched_by: {}", terminal_text(&context.fetched_by)),
272        format!("certified: {}", yes_no(context.certified)),
273        format!(
274            "point_in_time_guaranteed: {}",
275            yes_no(context.point_in_time_guaranteed)
276        ),
277        format!("query_call_count: {}", context.query_call_count),
278    ]
279}