canic-cli 0.112.0

Operator CLI for Canic fleet setup, builds, evidence, catalog, backup, and restore workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use super::ListCommandError;
use crate::support::registry_tree::{RegistryRow, visible_rows};
use canic_host::registry::RegistryEntry;
use ic_host_text::{
    escape::terminal_text,
    table::{self, Alignment, Options},
};
use std::collections::{BTreeMap, BTreeSet};

const MODULE_PREFIX_CHARS: usize = 8;
const MODULE_VARIANT_COLOR: &str = "\x1b[38;5;179m";
const COLOR_RESET: &str = "\x1b[0m";

const ROLE_HEADER: &str = "ROLE";
const KIND_HEADER: &str = "KIND";
const CAPS_HEADER: &str = "CAPS";
const AUTO_HEADER: &str = "AUTO";
const TOPUP_HEADER: &str = "TOPUP";
const METRICS_HEADER: &str = "METRICS";
const CANISTER_HEADER: &str = "CANISTER_ID";
const MODULE_HEADER: &str = "MODULE";
const MODULE_HASH_HEADER: &str = "MODULE_HASH";
const READY_HEADER: &str = "READY";
const CANIC_HEADER: &str = "CANIC";
const WASM_HEADER: &str = "WASM";
const CYCLES_HEADER: &str = "CYCLES";
const CONFIG_HEADERS: [&str; 6] = [
    ROLE_HEADER,
    KIND_HEADER,
    AUTO_HEADER,
    CAPS_HEADER,
    METRICS_HEADER,
    TOPUP_HEADER,
];
const CONFIG_ALIGNMENTS: [Alignment; 6] = [Alignment::Left; 6];
const REGISTRY_HEADERS: [&str; 7] = [
    ROLE_HEADER,
    MODULE_HEADER,
    CANISTER_HEADER,
    READY_HEADER,
    CANIC_HEADER,
    WASM_HEADER,
    CYCLES_HEADER,
];
const REGISTRY_VERBOSE_HEADERS: [&str; 7] = [
    ROLE_HEADER,
    MODULE_HASH_HEADER,
    CANISTER_HEADER,
    READY_HEADER,
    CANIC_HEADER,
    WASM_HEADER,
    CYCLES_HEADER,
];
const REGISTRY_ALIGNMENTS: [Alignment; 7] = [
    Alignment::Left,
    Alignment::Left,
    Alignment::Left,
    Alignment::Left,
    Alignment::Left,
    Alignment::Right,
    Alignment::Right,
];

///
/// ListTitle
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct ListTitle {
    pub(super) source: ListTitleSource,
    pub(super) name: String,
    pub(super) environment: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum ListTitleSource {
    Fleet,
    App,
}

///
/// ReadyStatus
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum ReadyStatus {
    Ready,
    NotReady,
    Error,
}

impl ReadyStatus {
    const fn label(self) -> &'static str {
        match self {
            Self::Ready => "yes",
            Self::NotReady => "no",
            Self::Error => "error",
        }
    }
}

///
/// RegistryColumnData
///

pub(super) struct RegistryColumnData<'a> {
    pub(super) readiness: &'a BTreeMap<String, ReadyStatus>,
    pub(super) canic_versions: &'a BTreeMap<String, String>,
    pub(super) module_hashes: &'a BTreeMap<String, String>,
    pub(super) wasm_sizes: &'a BTreeMap<String, String>,
    pub(super) cycles: &'a BTreeMap<String, String>,
    pub(super) full_module_hashes: bool,
    pub(super) color_module_variants: bool,
}

/// Render all registry entries, or one selected subtree, as a whitespace table.
pub(super) fn render_registry_tree(
    registry: &[RegistryEntry],
    canister: Option<&str>,
    columns: &RegistryColumnData<'_>,
) -> Result<String, ListCommandError> {
    let rows = visible_rows(registry, canister)?;
    Ok(render_registry_table(&rows, columns))
}

/// Render a named list view with a Fleet/source title above the registry table.
pub(super) fn render_list_output(
    title: &ListTitle,
    registry: &[RegistryEntry],
    canister: Option<&str>,
    columns: &RegistryColumnData<'_>,
    missing_roles: &[String],
) -> Result<String, ListCommandError> {
    let mut output = format!(
        "{}\n\n{}",
        render_list_title(title),
        render_registry_tree(registry, canister, columns)?
    );
    if !missing_roles.is_empty() {
        output.push_str("\n\nMissing roles: ");
        output.push_str(&terminal_text(&missing_roles.join(", ")));
    }
    Ok(output)
}

/// Render config-defined roles for a selected App that has not been installed yet.
pub(super) fn render_config_output(
    title: &ListTitle,
    rows: &[ConfigRoleRow],
    verbose: bool,
) -> String {
    format!(
        "{}\n\n{}",
        render_list_title(title),
        render_config_table(rows, verbose)
    )
}

fn render_list_title(title: &ListTitle) -> String {
    let label = match title.source {
        ListTitleSource::Fleet => "Fleet",
        ListTitleSource::App => "App",
    };
    format!(
        "{label}: {} (environment {})",
        terminal_text(&title.name),
        terminal_text(&title.environment)
    )
}

///
/// ConfigRoleRow
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct ConfigRoleRow {
    pub(super) role: String,
    pub(super) kind: String,
    pub(super) capabilities: String,
    pub(super) auto_create: String,
    pub(super) topup: String,
    pub(super) metrics: String,
    pub(super) details: Vec<String>,
}

fn render_config_table(rows: &[ConfigRoleRow], verbose: bool) -> String {
    let table_rows = config_table_rows(rows);
    let rendered = table::render(
        &CONFIG_HEADERS,
        &table_rows,
        &CONFIG_ALIGNMENTS,
        Options {
            column_gap: 3,
            header_separator: true,
        },
    );
    let mut rendered_lines = rendered.lines();
    let mut lines = rendered_lines
        .by_ref()
        .take(2)
        .map(str::to_owned)
        .collect::<Vec<_>>();
    for (row, line) in rows.iter().zip(rendered_lines) {
        lines.push(line.to_owned());
        if verbose {
            lines.extend(row.details.iter().map(|detail| format!("  - {detail}")));
        }
    }
    lines.join("\n")
}

fn config_table_rows(rows: &[ConfigRoleRow]) -> Vec<[String; 6]> {
    rows.iter()
        .map(|row| {
            [
                row.role.clone(),
                row.kind.clone(),
                row.auto_create.clone(),
                row.capabilities.clone(),
                row.metrics.clone(),
                row.topup.clone(),
            ]
        })
        .collect()
}

fn render_registry_table(rows: &[RegistryRow<'_>], columns: &RegistryColumnData<'_>) -> String {
    let table_rows = registry_table_rows(rows, columns);
    let headers = if columns.full_module_hashes {
        &REGISTRY_VERBOSE_HEADERS
    } else {
        &REGISTRY_HEADERS
    };
    if !columns.color_module_variants {
        return table::render(
            headers,
            &table_rows,
            &REGISTRY_ALIGNMENTS,
            Options {
                column_gap: 3,
                header_separator: true,
            },
        );
    }

    let rendered = table::render(
        headers,
        &table_rows,
        &REGISTRY_ALIGNMENTS,
        Options {
            column_gap: 3,
            header_separator: true,
        },
    );
    let variants = module_variant_flags(rows, columns.module_hashes);
    let mut rendered_lines = rendered.lines();
    let mut lines = rendered_lines
        .by_ref()
        .take(2)
        .map(str::to_owned)
        .collect::<Vec<_>>();
    lines.extend(rendered_lines.zip(variants).map(|(line, variant)| {
        if variant {
            format!("{MODULE_VARIANT_COLOR}{line}{COLOR_RESET}")
        } else {
            line.to_owned()
        }
    }));
    lines.join("\n")
}

fn registry_table_rows(
    rows: &[RegistryRow<'_>],
    columns: &RegistryColumnData<'_>,
) -> Vec<[String; 7]> {
    let mut table_rows = Vec::with_capacity(rows.len());
    for row in rows {
        let ready = columns
            .readiness
            .get(&row.entry.pid)
            .map_or("unknown", |status| status.label());
        let canic_version = columns
            .canic_versions
            .get(&row.entry.pid)
            .cloned()
            .unwrap_or_else(|| "-".to_string());
        let wasm_size = row
            .entry
            .role
            .as_deref()
            .and_then(|role| columns.wasm_sizes.get(role))
            .cloned()
            .unwrap_or_else(|| "-".to_string());
        let cycle_balance = columns
            .cycles
            .get(&row.entry.pid)
            .cloned()
            .unwrap_or_else(|| "-".to_string());
        table_rows.push([
            role_label(row),
            module_hash_label(row, columns.module_hashes, columns.full_module_hashes),
            canister_label(row),
            ready.to_string(),
            canic_version,
            wasm_size,
            cycle_balance,
        ]);
    }
    table_rows
}

fn module_variant_flags(
    rows: &[RegistryRow<'_>],
    module_hashes: &BTreeMap<String, String>,
) -> Vec<bool> {
    let baselines = role_module_baselines(rows, module_hashes);
    let distinct = role_distinct_module_hashes(rows, module_hashes);
    rows.iter()
        .map(|row| {
            row_role(row)
                .and_then(|role| {
                    row_module_hash(row, module_hashes)
                        .zip(baselines.get(role).map(String::as_str))
                        .zip(distinct.get(role))
                })
                .is_some_and(|((hash, baseline), role_hashes)| {
                    role_hashes.len() > 1 && hash != baseline
                })
        })
        .collect()
}

fn role_module_baselines(
    rows: &[RegistryRow<'_>],
    module_hashes: &BTreeMap<String, String>,
) -> BTreeMap<String, String> {
    let mut baselines = BTreeMap::new();
    for row in rows {
        if let Some((role, hash)) = row_role(row).zip(row_module_hash(row, module_hashes)) {
            baselines
                .entry(role.to_string())
                .or_insert_with(|| hash.to_string());
        }
    }
    baselines
}

fn role_distinct_module_hashes(
    rows: &[RegistryRow<'_>],
    module_hashes: &BTreeMap<String, String>,
) -> BTreeMap<String, BTreeSet<String>> {
    let mut distinct = BTreeMap::<String, BTreeSet<String>>::new();
    for row in rows {
        if let Some((role, hash)) = row_role(row).zip(row_module_hash(row, module_hashes)) {
            distinct
                .entry(role.to_string())
                .or_default()
                .insert(hash.to_string());
        }
    }
    distinct
}

fn row_role<'a>(row: &RegistryRow<'a>) -> Option<&'a str> {
    row.entry.role.as_deref().filter(|role| !role.is_empty())
}

fn row_module_hash<'a>(
    row: &RegistryRow<'_>,
    module_hashes: &'a BTreeMap<String, String>,
) -> Option<&'a str> {
    module_hashes
        .get(&row.entry.pid)
        .map(String::as_str)
        .filter(|hash| !hash.is_empty())
}

fn canister_label(row: &RegistryRow<'_>) -> String {
    row.entry.pid.clone()
}

fn role_label(row: &RegistryRow<'_>) -> String {
    let role = row.entry.role.as_deref().filter(|role| !role.is_empty());
    let label = match role {
        Some(role) => role.to_string(),
        None => "unknown".to_string(),
    };
    format!("{}{}", row.tree_prefix, label)
}

fn module_hash_label(
    row: &RegistryRow<'_>,
    module_hashes: &BTreeMap<String, String>,
    full: bool,
) -> String {
    let Some(hash) = module_hashes
        .get(&row.entry.pid)
        .filter(|hash| !hash.is_empty())
    else {
        return "-".to_string();
    };
    if full {
        return hash.clone();
    }
    hash.chars().take(MODULE_PREFIX_CHARS).collect()
}