use crate::{
icp::{IcpCli, IcpCommandError, IcpJsonResponseError, decode_json_result_response},
icp_config::IcpConfigError,
protocol_binding::ResolvedProtocolBinding,
replica_query::{self, ReplicaQueryError},
};
use candid::{CandidType, Deserialize};
use canic_core::{dto::role::RoleOverviewResponse, protocol::CANIC_PUBLIC_STATUS};
use std::path::Path;
use thiserror::Error as ThisError;
const ICP_JSON_OUTPUT: &str = "json";
#[derive(CandidType, Deserialize)]
enum RoleStatusResponse {
Overview(RoleOverviewResponse),
}
#[derive(Debug, ThisError)]
pub enum CanisterReadyQueryError {
#[error(transparent)]
IcpConfig(#[from] IcpConfigError),
#[error(transparent)]
Icp(#[from] IcpCommandError),
#[error(transparent)]
Replica(#[from] ReplicaQueryError),
#[error(transparent)]
Response(#[from] IcpJsonResponseError),
}
pub fn query_canister_ready(
icp: &IcpCli,
canister_id: &str,
environment: &str,
icp_root: Option<&Path>,
binding: &ResolvedProtocolBinding,
) -> Result<bool, CanisterReadyQueryError> {
if replica_query::uses_local_replica_transport(Some(environment), icp_root)? {
return query_local_canister_ready(environment, canister_id, icp_root).map_err(Into::into);
}
query_canister_ready_with_icp(icp, canister_id, binding)
}
pub fn query_local_canister_ready(
environment: &str,
canister_id: &str,
icp_root: Option<&Path>,
) -> Result<bool, ReplicaQueryError> {
replica_query::query_ready(
Some(environment),
canister_id,
CANIC_PUBLIC_STATUS,
icp_root,
)
}
fn query_canister_ready_with_icp(
icp: &IcpCli,
canister_id: &str,
binding: &ResolvedProtocolBinding,
) -> Result<bool, CanisterReadyQueryError> {
let output = icp.canister_query_arg_output_with_candid(
canister_id,
CANIC_PUBLIC_STATUS,
"(variant { Overview })",
Some(ICP_JSON_OUTPUT),
Some(&binding.candid_path),
)?;
let response = decode_json_result_response::<RoleStatusResponse>(&output)?;
let RoleStatusResponse::Overview(response) = response;
Ok(response.bootstrap.ready)
}