canic-cli 0.288.1

Canic command line deployment tool
//! Local declaration listings, independent of journals and live observations.
use crate::Output;
use canic_host::{FleetNetwork, Network, Result};
use ic_host_text::{Alignment, plain_table};
use std::path::Path;

pub(crate) fn app_canisters(path: &Path, app: Option<&str>, json: bool) -> Result<Output> {
    let config = canic_host::load_declarations(path)?;
    let (app, definition) = config.select_app(app)?;
    if json {
        return Ok(Output::Json(
            serde_json::json!({"scope":"local app definitions only", "config_path":path, "app":app, "canisters":definition.canisters}),
        ));
    }
    let table = app_canister_table(definition);
    Ok(Output::Text(format!("App: {app}\n\n{table}\n\n")))
}

fn app_canister_table(definition: &canic_host::AppConfig) -> String {
    let rows: Vec<_> = crate::topology::rows(
        definition
            .canisters
            .iter()
            .map(|(name, slot)| (name.as_str(), slot.parent.as_deref())),
    )
    .into_iter()
    .map(|(name, prefix)| {
        let item = &definition.canisters[name];
        [
            format!("{prefix}{name}"),
            crate::topology::role_label(item.role.as_deref().unwrap_or("—")).into(),
            item.wasm
                .as_ref()
                .map_or_else(|| "—".into(), |path| path.display().to_string()),
        ]
    })
    .collect();
    plain_table(
        &["CANISTER", "ROLE", "WASM INPUT"],
        &rows,
        &[Alignment::Left; 3],
    )
}

fn network_label(network: &FleetNetwork) -> String {
    match network {
        FleetNetwork::Bound(Network::Mainnet) => "ic / mainnet".into(),
        FleetNetwork::Unbound(_) => "local / unbound".into(),
        FleetNetwork::Bound(Network::Local { url, .. }) => format!("local / {url}"),
    }
}

pub(crate) fn app_show(path: &Path, app: Option<&str>, json: bool) -> Result<Output> {
    let config = canic_host::load_declarations(path)?;
    let (app, definition) = config.select_app(app)?;
    let fleets: Vec<_> = definition
        .fleets
        .iter()
        .map(|(name, fleet)| [name.clone(), network_label(&fleet.network)])
        .collect();
    if json {
        return Ok(Output::Json(serde_json::json!({
            "app": app, "config_path": path, "declared_canisters": definition.canisters.len(),
            "fleets": fleets.iter().map(|[name, network]| serde_json::json!({"fleet":name,"network":network})).collect::<Vec<_>>(),
            "canisters": definition.canisters,
        })));
    }
    let fleet_table = if fleets.is_empty() {
        "No fleets declared.".into()
    } else {
        plain_table(&["FLEET", "NETWORK"], &fleets, &[Alignment::Left; 2])
    };
    let canister_table = if definition.canisters.is_empty() {
        "No canister slots declared.".into()
    } else {
        app_canister_table(definition)
    };
    Ok(Output::Text(format!(
        "App: {app}\nConfig: {}\nFleets: {}  Slots: {}\n\n{fleet_table}\n\n{canister_table}\n",
        ic_host_text::escape(&path.to_string_lossy()),
        fleets.len(),
        definition.canisters.len()
    )))
}

pub(crate) fn canisters(
    path: &Path,
    app: Option<&str>,
    fleet: Option<&str>,
    json: bool,
) -> Result<Output> {
    let config = canic_host::load_declarations(path)?;
    let (app, definition) = config.select_app(app)?;
    let (fleet, declaration) = definition.fleet_declaration(fleet)?;
    let canisters = definition.resolve_slots(declaration)?;
    if json {
        let configuration = match declaration.network {
            FleetNetwork::Bound(_) => serde_json::json!(config.select(Some(app), Some(fleet))?),
            FleetNetwork::Unbound(_) => {
                let mut declared = serde_json::json!(declaration);
                declared["canisters"] = serde_json::json!(canisters);
                serde_json::json!({"app":app, "fleet":fleet, "config":declared})
            }
        };
        return Ok(Output::Json(serde_json::json!({
            "scope":"local configuration only", "config_path":path, "configuration":configuration,
        })));
    }
    let title = format!("App: {app} · Fleet: {fleet}");
    render_slots(&title, &canisters, declaration)
}

pub(crate) fn fleet_show(
    path: &Path,
    app: Option<&str>,
    fleet: Option<&str>,
    json: bool,
) -> Result<Output> {
    let config = canic_host::load_declarations(path)?;
    let (app, definition) = config.select_app(app)?;
    let (fleet, declaration) = definition.fleet_declaration(fleet)?;
    let slots = definition.resolve_slots(declaration)?;
    if json {
        let mut config = serde_json::json!(declaration);
        config["canisters"] = serde_json::json!(slots);
        return Ok(Output::Json(
            serde_json::json!({"app":app,"fleet":fleet,"config":config,"config_path":path}),
        ));
    }
    let frontend = declaration.local_frontend.as_ref().map_or_else(
        || "not configured".into(),
        |f| format!("http://localhost:{}/", f.port),
    );
    let standby = declaration.standby_pool.as_ref().map_or_else(
        || "not configured".into(),
        |p| {
            format!(
                "minimum {} spares · up to {} automatic creations · owner {} · expires at {} ns",
                p.min_available_spares, p.maximum_creations, p.root, p.expires_at_ns
            )
        },
    );
    let title = format!(
        "{app} / {fleet} · {}\nFrontend: {frontend}\nStandby pool: {standby}",
        network_label(&declaration.network)
    );
    render_slots(&title, &slots, declaration)
}

fn render_slots(
    title: &str,
    canisters: &std::collections::BTreeMap<String, canic_host::CanisterConfig>,
    declaration: &canic_host::FleetDeclaration,
) -> Result<Output> {
    if canisters.is_empty() {
        return Ok(Output::Text(format!(
            "{title}\n\nNo canisters defined.\n\n"
        )));
    }
    let rows: Vec<_> = crate::topology::rows(
        canisters
            .iter()
            .map(|(name, slot)| (name.as_str(), slot.parent.as_deref())),
    )
    .into_iter()
    .map(|(slot, prefix)| {
        let config = &canisters[slot];
        [
            format!("{prefix}{slot}"),
            crate::topology::role_label(config.role.as_deref().unwrap_or("—")).into(),
            config.id.clone().unwrap_or_else(|| "—".into()),
        ]
    })
    .collect();
    let table = plain_table(
        &["CANISTER", "ROLE", "PRINCIPAL"],
        &rows,
        &[Alignment::Left; 3],
    );
    let mut output = format!("{title}\n\n{table}\n\n");
    if !declaration.policy.top_up_children.is_empty() {
        let edges: Vec<_> = declaration
            .policy
            .top_up_children
            .iter()
            .map(|rule| {
                let child = rule.child.as_str();
                let parent = canisters[child]
                    .parent
                    .as_deref()
                    .expect("validated direct child");
                format!(
                    "{parent} → {child} (below {} cycles, add {})",
                    rule.below_cycles, rule.amount_cycles
                )
            })
            .collect();
        output.push_str(&format!(
            "Eligible for parent top-ups: {}\n",
            edges.join(", ")
        ));
    }
    Ok(Output::Text(output))
}

pub(crate) fn list(
    path: Option<&Path>,
    app: Option<&str>,
    apps_only: bool,
    json: bool,
) -> Result<Output> {
    let configs = if let Some(app) = app
        && path.is_none()
    {
        let path = canic_host::resolve_config_path(Path::new(""), None, Some(app))?;
        vec![canic_host::DiscoveredConfig {
            config: canic_host::load_declarations(&path)?,
            path,
        }]
    } else {
        canic_host::discover_configs(Path::new(""), path)?
    };
    if let Some(app) = app
        && !configs
            .iter()
            .any(|item| item.config.apps.contains_key(app))
    {
        let names = configs
            .iter()
            .flat_map(|item| item.config.apps.keys().cloned())
            .collect::<Vec<_>>()
            .join(", ");
        return Err(canic_host::Error::Invalid(format!(
            "unknown app {app}; select --app from: {names}"
        )));
    }
    let mut rows = Vec::new();
    let mut app_rows = Vec::new();
    let mut fleet_rows = Vec::new();
    for item in &configs {
        let config = &item.config;
        for (app_name, definition) in &config.apps {
            if app.is_some_and(|selected| selected != app_name) {
                continue;
            }
            let slots = definition.canisters.len();
            if apps_only {
                rows.push(serde_json::json!({"app":app_name, "fleets":definition.fleets.len(), "config_path":item.path}));
                app_rows.push([
                    app_name.clone(),
                    definition.fleets.len().to_string(),
                    slots.to_string(),
                    item.path.display().to_string(),
                ]);
            } else {
                for (fleet, definition) in &definition.fleets {
                    let binding = if matches!(definition.network, FleetNetwork::Unbound(_)) {
                        canic_host::local_fleet::running_network(&item.path, app_name, fleet)?
                            .map(FleetNetwork::Bound)
                    } else {
                        None
                    };
                    let network = binding.as_ref().unwrap_or(&definition.network);
                    let state = canic_host::local_fleet::status(&item.path, app_name, fleet)?
                        .or_else(|| {
                            (matches!(definition.network, FleetNetwork::Unbound(_))
                                && definition.lifetime.is_none())
                            .then_some("not started")
                        });
                    rows.push(serde_json::json!({"app":app_name, "fleet":fleet, "network":network, "local_state":state, "declared_canisters":slots, "config_path":item.path}));
                    fleet_rows.push([
                        app_name.clone(),
                        fleet.clone(),
                        slots.to_string(),
                        network_label(network),
                        state.unwrap_or("—").to_owned(),
                        item.path.display().to_string(),
                    ]);
                }
            }
        }
    }
    if json {
        let paths: Vec<_> = configs.iter().map(|item| &item.path).collect();
        let path = if paths.len() == 1 {
            Some(paths[0])
        } else {
            None
        };
        let mut value = serde_json::json!({"scope":"local configuration only", "config_path":path, "config_paths":paths});
        value[if apps_only { "apps" } else { "fleets" }] = serde_json::json!(rows);
        Ok(Output::Json(value))
    } else {
        let rendered = if apps_only {
            plain_table(
                &["APP", "FLEETS", "SLOTS", "CONFIG"],
                &app_rows,
                &[
                    Alignment::Left,
                    Alignment::Right,
                    Alignment::Right,
                    Alignment::Left,
                ],
            )
        } else {
            plain_table(
                &["APP", "FLEET", "SLOTS", "NETWORK", "STATE", "CONFIG"],
                &fleet_rows,
                &[
                    Alignment::Left,
                    Alignment::Left,
                    Alignment::Right,
                    Alignment::Left,
                    Alignment::Left,
                    Alignment::Left,
                ],
            )
        };
        Ok(Output::Text(format!("{rendered}\n")))
    }
}