ic-query-cli 0.97.0

Command-line wrapper for read-only Internet Computer metadata queries
Documentation
//! Module: cloud_engine
//!
//! Responsibility: parse and dispatch public CloudEngine metadata reports.
//! Does not own: native transport, report construction, or text rendering.
//! Boundary: exposes mainnet-only CloudEngine inventory and bounded public reports at the CLI root.

use crate::cli::clap::{parsed_options, with_options, with_source_options};
use ic_query::report::CollectionSourceRequest;
mod node;
mod provider;

use crate::{
    cli::common::{
        COLLECTION_MODE_LIVE, CurrentUnixSecsError, collection_help, current_unix_secs,
        output_format, write_text_or_json,
    },
    progress::StderrQueryProgress,
    storage::{CacheRootError, cache_root},
};
use clap::{ArgMatches, Command as ClapCommand};
use ic_query::cloud_engine::CloudEngineHostError;
use ic_query::cloud_engine::DEFAULT_CLOUD_ENGINE_SOURCE_ENDPOINT;
use ic_query::cloud_engine::build_cloud_engine_list_report_with_sources_and_progress;
use ic_query::cloud_engine::build_cloud_engine_operator_report;
use ic_query::cloud_engine::build_cloud_engine_prices_report;
use ic_query::ic::IcHostError;
use ic_query::subnet_catalog::DEFAULT_STALE_AFTER_SECONDS;
use ic_query::subnet_catalog::DEFAULT_SUBNET_CATALOG_SOURCE_ENDPOINT;
use ic_query::subnet_catalog::SubnetCatalogCacheRequest;
use ic_query::subnet_catalog::SubnetCatalogListRequest;
use ic_query_text::cloud_engine::cloud_engine_list_report_text;
use ic_query_text::cloud_engine::cloud_engine_operator_report_text;
use ic_query_text::cloud_engine::cloud_engine_prices_report_text;
use std::io;
use thiserror::Error as ThisError;

const SOURCE_ENDPOINT_HELP: &str = "IC API endpoint used for native CloudEngine queries";

const INFO_HELP_AFTER: &str = "\
Examples:
  icq cloud-engine info 2nl67-oqoc5-cmocj-otlhq-kr2kr-53hov-drrds-7ihcs-fhomv-2eyvu-6qe
  icq cloud-engine info 2nl67-oqoc5-cmocj-otlhq-kr2kr-53hov-drrds-7ihcs-fhomv-2eyvu-6qe --json

This command makes one control-plane query to resolve the Subnet and four
public operator queries when an operator is registered. The responses are not
certified and the sequential calls are not an exact point-in-time snapshot.";
const LIST_COLLECTION_MODE: &str = "Cache-backed Registry inventory; refreshes missing or recoverably invalid catalog content, then makes one live operator-binding query per returned Subnet.";
const LIST_HELP_AFTER: &str = "\
Examples:
  icq cloud-engine list
  icq cloud-engine list --json

The Registry supplies the complete CloudEngine Subnet inventory. The command
then makes one exact public control-plane operator-binding query per returned
Subnet, up to 100. Registry and control-plane provenance remain separate, and
one failed binding lookup is reported on its row without discarding the
Registry snapshot.";
const PRICES_HELP_AFTER: &str = "\
Examples:
  icq cloud-engine prices
  icq cloud-engine prices --json

This command makes exactly two control-plane queries: one for the network fee
and one for at most 1,000 public marketplace rows. The responses are not
certified or presented as an exact point-in-time snapshot.";

///
/// CloudEngineCommandError
///
/// Errors surfaced while parsing or running a CloudEngine command.
///

#[derive(Debug, ThisError)]
pub enum CloudEngineCommandError {
    /// Native CloudEngine collection or evidence validation failed.
    #[error(transparent)]
    Host(#[from] CloudEngineHostError),
    /// Official Dashboard collection or evidence validation failed.
    #[error(transparent)]
    Dashboard(#[from] IcHostError),
    /// The CLI cache root could not be resolved.
    #[error(transparent)]
    CacheRoot(#[from] CacheRootError),
    /// The process clock could not supply a Unix collection timestamp.
    #[error(transparent)]
    Clock(#[from] CurrentUnixSecsError),
    /// Writing the selected report output failed.
    #[error(transparent)]
    Io(#[from] io::Error),
    /// JSON serialization failed.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
}

pub async fn run_matches(
    matches: &ArgMatches,
    network: &str,
) -> Result<(), CloudEngineCommandError> {
    match matches.subcommand() {
        Some(("info", matches)) => run_info(matches, network).await,
        Some(("list", matches)) => run_list(matches, network).await,
        Some(("node", matches)) => node::run_matches(matches, network).await,
        Some(("prices", matches)) => run_prices(matches, network).await,
        Some(("provider", matches)) => provider::run_matches(matches, network).await,
        _ => unreachable!("clap requires a known cloud-engine subcommand"),
    }
}

async fn run_list(matches: &ArgMatches, network: &str) -> Result<(), CloudEngineCommandError> {
    let options: OperatorListOptions = parsed_options(matches);
    let now_unix_secs = current_unix_secs()?;
    let registry_source_endpoint = options.registry_source_endpoint;
    let cache = SubnetCatalogCacheRequest::new(cache_root()?, network);
    let catalog_request = SubnetCatalogListRequest::new(
        cache,
        registry_source_endpoint,
        now_unix_secs,
        DEFAULT_STALE_AFTER_SECONDS,
    );
    let control_plane_request = source_request_at(matches, network, now_unix_secs);
    let report = build_cloud_engine_list_report_with_sources_and_progress(
        &catalog_request,
        &control_plane_request,
        &ic_query::nns::LiveNnsSource::default(),
        &ic_query::cloud_engine::LiveCloudEngineSource::default(),
        &mut StderrQueryProgress::new(),
    )
    .await?;
    write_text_or_json(
        output_format(matches),
        &report,
        cloud_engine_list_report_text,
    )
}

async fn run_info(matches: &ArgMatches, network: &str) -> Result<(), CloudEngineCommandError> {
    let options: OperatorInfoOptions = parsed_options(matches);
    let request = source_request(matches, network)?;
    let report = build_cloud_engine_operator_report(&request, &options.subnet_id).await?;
    write_text_or_json(
        output_format(matches),
        &report,
        cloud_engine_operator_report_text,
    )
}

async fn run_prices(matches: &ArgMatches, network: &str) -> Result<(), CloudEngineCommandError> {
    let request = source_request(matches, network)?;
    let report = build_cloud_engine_prices_report(&request).await?;
    write_text_or_json(
        output_format(matches),
        &report,
        cloud_engine_prices_report_text,
    )
}

fn source_request(
    matches: &ArgMatches,
    network: &str,
) -> Result<CollectionSourceRequest, CurrentUnixSecsError> {
    Ok(source_request_at(matches, network, current_unix_secs()?))
}

fn source_request_at(
    matches: &ArgMatches,
    network: &str,
    fetched_at_unix_secs: u64,
) -> CollectionSourceRequest {
    let source = crate::cli::common::SourceOutputOptions::from_matches(matches);
    CollectionSourceRequest::from_unix_secs(
        network,
        source.source_endpoint,
        fetched_at_unix_secs,
        "ic-query",
    )
}

pub fn command() -> ClapCommand {
    ClapCommand::new("cloud-engine")

        .about("Inspect public CloudEngine metadata")
        .subcommand(info_command())
        .subcommand(list_command())
        .subcommand(node::command())
        .subcommand(prices_command())
        .subcommand(provider::command())
        .after_help(
            "Examples:\n  icq cloud-engine list\n  icq cloud-engine info <subnet-id>\n  icq cloud-engine node list\n  icq cloud-engine prices\n  icq cloud-engine provider list",
        )
}

///
/// OperatorListOptions
///
/// Typed arguments for the list_command operation.
///

#[derive(clap::Args)]
#[group(skip)]
struct OperatorListOptions {
    #[arg(id = REGISTRY_SOURCE_ENDPOINT_ARG, long = REGISTRY_SOURCE_ENDPOINT_ARG, value_name = "url", default_value = DEFAULT_SUBNET_CATALOG_SOURCE_ENDPOINT, help = "IC API endpoint used to refresh the Registry Subnet Catalog")]
    registry_source_endpoint: String,
}

fn list_command() -> ClapCommand {
    report_args(
        with_options::<OperatorListOptions>(
            ClapCommand::new("list")
                .about("List Registry CloudEngine Subnets and public operator bindings"),
        ),
        DEFAULT_CLOUD_ENGINE_SOURCE_ENDPOINT,
        SOURCE_ENDPOINT_HELP,
    )
    .after_help(collection_help(LIST_COLLECTION_MODE, LIST_HELP_AFTER))
}

///
/// OperatorInfoOptions
///
/// Typed arguments for the info_command operation.
///

#[derive(clap::Args)]
#[group(skip)]
struct OperatorInfoOptions {
    #[arg(
        id = "subnet-id",
        value_name = "subnet-id",
        help = "CloudEngine Subnet principal to resolve"
    )]
    subnet_id: String,
}

fn info_command() -> ClapCommand {
    with_options::<OperatorInfoOptions>(
        report_args(
            ClapCommand::new("info")
                .about("Show the operator binding and public settings for one CloudEngine Subnet"),
            DEFAULT_CLOUD_ENGINE_SOURCE_ENDPOINT,
            SOURCE_ENDPOINT_HELP,
        )
        .after_help(collection_help(COLLECTION_MODE_LIVE, INFO_HELP_AFTER)),
    )
}

fn prices_command() -> ClapCommand {
    report_args(
        ClapCommand::new("prices")
            .about("Show the public CloudEngine network fee and marketplace prices"),
        DEFAULT_CLOUD_ENGINE_SOURCE_ENDPOINT,
        SOURCE_ENDPOINT_HELP,
    )
    .after_help(collection_help(COLLECTION_MODE_LIVE, PRICES_HELP_AFTER))
}

fn report_args(
    command: ClapCommand,
    endpoint: &'static str,
    source_help: &'static str,
) -> ClapCommand {
    with_source_options::<crate::cli::common::SourceOutputOptions>(command, endpoint, source_help)
}

const REGISTRY_SOURCE_ENDPOINT_ARG: &str = "registry-source-endpoint";

#[cfg(test)]
mod tests;