#[cfg(test)]
mod tests;
mod inspect;
pub(crate) use inspect::inspect;
mod metrics;
mod roles;
mod stores;
mod terminal;
mod watch;
use canic_host::{Error, Fleet, Result};
use std::{fmt::Write as _, path::Path};
pub(crate) use terminal::render as terminal;
pub(crate) use watch::{collect, watch};
fn escape(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn frontend_state(snapshot: &Fleet) -> &'static str {
match snapshot.frontend_listening {
Some(true) => "port listening",
Some(false) => "port closed",
None => "listener unknown",
}
}
fn spare_summary(snapshot: &Fleet, configured: u8) -> String {
use canic_management_protocol::stored::RefillStatus;
if let Some(counts) = &snapshot.spare_counts {
let refill = match counts.refill {
RefillStatus::AtTarget => "target met",
RefillStatus::AwaitingCreation => "awaiting creation",
RefillStatus::AllowanceSpent => "creation allowance spent",
RefillStatus::SubnetFull => "subnet full",
RefillStatus::Expired => "approval expired",
RefillStatus::Occupied => "management busy",
RefillStatus::Underfunded => "more cycles required",
RefillStatus::Due => "refill due",
};
let mut line = format!(
"{} ready · target {} · {refill} · {}/{} automatic creations used",
counts.ready,
counts.min_available_spares,
counts.creations_used,
counts.maximum_creations
);
if configured != counts.min_available_spares {
write!(line, " · configured minimum {configured}").expect("String write");
}
line
} else {
format!("ready count unknown · configured minimum {configured}")
}
}
fn manager_kind(snapshot: &Fleet, manager: &canic_host::FleetManager) -> &'static str {
let planned_root = snapshot.operations.iter().any(|operation| {
operation.network_id == manager.network_id
&& operation.management_owner() == Some(manager.manager.as_str())
});
let declared_root = snapshot.configuration.as_ref().is_some_and(|config| {
config.config.network.binding_id().ok().as_deref() == Some(&manager.network_id)
&& config.config.canisters.iter().any(|(name, slot)| {
slot.role.as_deref() == Some("root")
&& slot_state(snapshot, name).identity() == Some(manager.manager.as_str())
})
});
if planned_root || declared_root {
"Root"
} else {
"Manager"
}
}
fn declared_routes(snapshot: &Fleet, links: &[crate::args::RouteLink]) -> Result<String> {
if links.is_empty() {
return Ok(String::new());
}
if links.len() > 32 {
return Err(Error::Invalid("at most 32 declared routes".into()));
}
let mut html = String::from(
"<h2>Declared application routes</h2><p>Operator-supplied topology, not an on-chain route or readiness observation. Each endpoint is in this inventory under the same network trust binding.</p><div class=grid>",
);
for link in links {
let (entry, worker) = (link.entry.as_str(), link.worker.as_str());
let candidates: Vec<_> = snapshot
.canisters
.iter()
.filter(|source| {
source.canister == entry
&& entry != worker
&& snapshot.canisters.iter().any(|target| {
target.canister == worker && target.network_id == source.network_id
})
})
.collect();
if candidates.len() != 1 {
return Err(Error::Invalid("declared route requires two distinct known targets on one unambiguous network; select a smaller state directory".into()));
}
write!(html, "<article><span class=badge>Declared · not verified</span><p>{}</p><div class=topology><span class=label>Source canister</span><code>{}</code><span class=arrow>↓ declared route</span><span class=label>Destination canister</span><code>{}</code></div></article>", escape(&candidates[0].network), escape(entry), escape(worker)).expect("writing to a String");
}
html.push_str("</div>");
Ok(html)
}
fn render(snapshot: &Fleet, routes: &str) -> String {
let mut html = include_str!("header.html").to_owned();
write!(html,
"<header><p class=eyebrow>CANIC / FLEET OBSERVATION</p><h1>Your deployment fleet</h1><p>Snapshot collected <time data-ns=\"{}\">{} Unix seconds</time>. Regenerate the report to refresh.</p></header><div class=summary><strong>{} canisters</strong><strong>{} operations</strong><strong>{} inventory issues</strong></div><p class=scope>Scope: local deployment journal and explicitly selected observations. Certified module and controller reads are sampled separately. Canister cycle balances and running/stopped status are not observed.</p>",
snapshot.finished_at_ns, snapshot.finished_at_ns / 1_000_000_000,
snapshot.canisters.len(), snapshot.operations.iter().map(|operation| &operation.operation).collect::<std::collections::BTreeSet<_>>().len(), snapshot.issues.len()
).expect("writing to a String");
if let Some(config) = &snapshot.configuration {
write!(html, "<h2>App: {}</h2><h3>Fleet: {}</h3><p>Local declarations; deployment evidence is shown separately.</p><p>Configured network: {}</p>", escape(&config.app), escape(&config.fleet), escape(&configured_network(config))).expect("writing to String");
if let Some(port) = config.frontend_port {
write!(html, "<p>Frontend: <a href=\"http://localhost:{port}/\">http://localhost:{port}/</a> · {}</p>", frontend_state(snapshot)).expect("String write");
} else {
html.push_str("<p>Frontend: not configured</p>");
}
write!(
html,
"<p>Standby pool: {}</p>",
config.config.standby_pool.as_ref().map_or_else(
|| "not configured".into(),
|policy| spare_summary(snapshot, policy.minimum_available)
)
)
.expect("String write");
if let Some(warning) = &snapshot.placement_warning {
write!(html, "<p>Placement: {}</p>", escape(warning)).expect("String write");
}
if config.config.canisters.is_empty() {
html.push_str(
"<p>No canisters declared yet. Add canister definitions to this app before planning.</p>",
);
}
html.push_str("<ul>");
for (slot, prefix) in crate::topology::rows(
config
.config
.canisters
.iter()
.map(|(name, slot)| (name.as_str(), slot.parent.as_deref())),
) {
write!(
html,
"<li><strong style=\"white-space:pre\">{}{}</strong> · role: {} · {}</li>",
escape(&prefix),
escape(slot),
escape(crate::topology::role_label(
config.config.canisters[slot].role.as_deref().unwrap_or("—")
)),
escape(&slot_status(snapshot, slot))
)
.expect("writing to String");
}
html.push_str("</ul>");
}
if let Some(wallet) = &snapshot.wallet {
write!(html, "<h2>Mainnet wallet</h2><article><span class=badge>Uncertified balance queries</span><span class=label>Owner principal · default subaccount</span><code>{}</code><span class=label>Receive ICP · Internet Computer mainnet</span><code>{}</code><p>Wallet balances exclude cycles already held by canisters. This view makes no transfers or conversions.</p><div class=grid>", escape(&wallet.principal), escape(&wallet.icp_address)).expect("writing to String");
for (label, balance) in [("ICP", &wallet.icp), ("Cycles ledger", &wallet.cycles)] {
write!(html, "<section><h3>{label}</h3><strong>{}</strong><p class=muted>Observed <time data-ns=\"{}\">{} Unix seconds</time></p>", escape(balance.display.as_deref().unwrap_or("Unknown")), balance.observed_at_ns, balance.observed_at_ns / 1_000_000_000).expect("writing to String");
if let Some(error) = &balance.observation_error {
write!(html, "<p class=warning>{}</p>", escape(error)).expect("writing to String");
}
html.push_str("</section>");
}
html.push_str("</div></article>");
}
html.push_str("<h2>Canisters & controllers</h2><div class=grid>");
if snapshot.canisters.is_empty() {
html.push_str("<p>No admitted target is known yet. Pending plans remain below.</p>");
}
for canister in &snapshot.canisters {
let observed = canister.observation_error.is_none();
write!(html, "<article><div class=topline><span>{}</span><span class=\"badge {}\">{}</span></div><h3>{}</h3>",
escape(&canister.network), if observed {"observed"} else {"unknown"},
if observed {"Certified metadata"} else {"Unknown / unavailable"}, escape(&canister.canister)
).expect("writing to a String");
if let Some(controllers) = &canister.controllers {
html.push_str("<div class=topology><span class=label>Observed controllers</span>");
for controller in controllers {
write!(html, "<code>{}</code>", escape(controller)).expect("writing to a String");
}
if controllers.is_empty() {
html.push_str("<span>No controllers</span>");
} else {
html.push_str("<span class=arrow>↓ controls</span>");
}
html.push_str("<strong>Deployment target</strong></div>");
}
if let Some(bytes) = canister.wasm_bytes {
write!(
html,
"<span class=label>Wasm size</span><code>{}</code>",
crate::progress::wasm_size(bytes)
)
.expect("writing to String");
}
if let Some(module) = &canister.module_hash {
write!(
html,
"<span class=label>Observed module SHA-256</span><code>{}</code>",
escape(module)
)
.expect("writing to a String");
}
if let Some(error) = &canister.observation_error {
write!(html, "<p class=warning>{}</p><p>No health or effect outcome is inferred from this observation failure.</p>", escape(error)).expect("writing to a String");
}
write!(html, "<p class=muted>Observed <time data-ns=\"{}\">{} Unix seconds</time></p><details><summary>Network trust binding</summary><code>{}</code></details></article>",
canister.observed_at_ns, canister.observed_at_ns / 1_000_000_000, escape(&canister.network_id)
).expect("writing to a String");
}
html.push_str("</div>");
html.push_str(routes);
if !snapshot.managers.is_empty() {
html.push_str("<h2>Autonomous child operations</h2><p>Root and manager reports below are uncertified. Module and controller observations above are independently certified. Observation does not resume work or create completion receipts.</p><div class=grid>");
for manager in &snapshot.managers {
write!(
html,
"<article><span class=badge>{} report (uncertified)</span><h3>{}</h3>",
manager_kind(snapshot, manager),
escape(&manager.manager)
)
.expect("writing to String");
write!(
html,
"<p>Child: <strong>{}</strong></p>",
escape(&child_label(snapshot, manager))
)
.expect("String write");
if let Some(status) = &manager.reported {
write!(html, "<p>Creation phase: <strong>{:?}</strong></p><p>Create / upload / install attempts: {} / {} / {}</p><div class=topology><code>{}</code><span class=arrow>↓ reports child</span><code>{}</code></div>", status.phase, status.attempts[0], status.attempts[1], status.attempts[2], escape(&manager.manager), escape(status.worker.as_deref().unwrap_or("No reported principal"))).expect("writing to String");
if status.phase == canic_host::ManagementPhase::CreateIssued {
html.push_str("<p class=warning>Creation outcome unresolved. The original 1T attachment remains uncertain unless a correlated refund is retained. No second creation is authorized.</p>");
}
if let Some(error) = &status.failure {
write!(html, "<p class=warning>{error:?}</p>").expect("writing to String");
}
}
if let Some(error) = &manager.observation_error {
write!(html, "<p class=warning>{}</p>", escape(error)).expect("writing to String");
}
if let Some(upgrade) = &manager.upgrade {
if let Some(status) = &upgrade.reported {
let phase = if status.approval.is_none() {
"not admitted".into()
} else {
format!("{:?}", status.phase)
};
write!(html, "<p>Upgrade phase: <strong>{phase}</strong></p><p>Upload / install attempts: {} / {}</p>", status.attempts[0], status.attempts[1]).expect("writing to String");
if let Some(failure) = &status.failure {
write!(html, "<p class=warning>Upgrade failure: {failure:?}</p>")
.expect("writing to String");
}
} else {
html.push_str("<p>Upgrade phase: <strong>UNKNOWN</strong></p>");
}
if let Some(error) = &upgrade.observation_error {
write!(html, "<p class=warning>{}</p>", escape(error))
.expect("writing to String");
}
write!(
html,
"<details><summary>Upgrade operation</summary><code>{}</code></details>",
escape(&upgrade.operation)
)
.expect("writing to String");
}
html.push_str("</article>");
}
html.push_str("</div>");
}
if !snapshot.stores.is_empty() {
html.push_str("<h2>Store maintenance</h2><p>Uncertified Root reports; completion is historical, not current Store readiness or admission.</p><div class=grid>");
for report in &snapshot.stores {
write!(
html,
"<article><h3>{}</h3><p><strong>{}</strong></p>",
escape(&report.store),
stores::summary(report)
)
.expect("String write");
if let Some(failure) = report.reported.as_ref().and_then(|s| s.failure.as_ref()) {
write!(html, "<p class=warning>Failure: {failure:?}</p>").expect("String write");
}
if let Some(error) = &report.observation_error {
write!(html, "<p class=warning>{}</p>", escape(error)).expect("String write");
}
html.push_str("<details><summary>Retained evidence</summary>");
for (label, value) in stores::details(report).into_iter().chain(std::iter::once((
"Network identity",
report.network_id.clone(),
))) {
write!(html, "<p>{label}: <code>{}</code></p>", escape(&value))
.expect("String write");
}
html.push_str("</details></article>");
}
html.push_str("</div>");
}
html.push_str(&metrics::render(snapshot));
html.push_str("<h2>Deployment & recovery operations</h2><p>Receipts are retained historical evidence. An approved plan is not proof of deployment; an old receipt need not match a later upgrade.</p><div class=grid>");
for operation in &snapshot.operations {
let observed = snapshot.canisters.iter().find(|item| {
item.network_id == operation.network_id
&& operation.canister.as_ref() == Some(&item.canister)
});
let binding = match observed {
Some(item) if item.module_hash.is_some() && item.controllers.is_some() => {
if item.module_hash.as_ref() == Some(&operation.approved_module)
&& item.controllers.as_ref().is_some_and(|values| {
values == std::slice::from_ref(&operation.approved_controller)
})
{
"Current metadata matches this approval"
} else {
"Current metadata differs from this approval (historical or changed)"
}
}
_ => "Current binding unknown",
};
write!(html, "<article><div class=topline><span>{}</span><span class=badge>{}</span></div><h3>{}</h3><p>{}</p><code>{}</code><p>{}</p><span class=label>Approved module SHA-256</span><code>{}</code><dl>",
escape(&operation.network), if operation.receipt_retained {"Receipt retained"} else {"Unfinished"},
escape(&operation.operation), binding,
escape(operation.canister.as_deref().unwrap_or("Target unknown — creation result not retained")),
if operation.approval_expired {"Original approval expired; this does not erase retained effects."} else {"Within original approval window."},
escape(&operation.approved_module)
).expect("writing to a String");
for (effect, evidence) in &operation.effects {
write!(
html,
"<dt>{}</dt><dd>{}</dd>",
escape(effect),
escape(match evidence.as_str() {
"signed_attempt_retained_outcome_unknown" =>
"Signed attempt retained · outcome unknown",
"reply_retained" => "Reply retained",
"rejection_retained" => "Rejection retained",
"not_submitted" => "Not submitted",
other => other,
})
)
.expect("writing to a String");
}
write!(html, "</dl><p class=muted>Use <code>{}</code> with the same config/journal path for retained details. This report never resumes or retries an operation.</p></article>", escape(&status_command(snapshot, &operation.operation))).expect("writing to String");
}
html.push_str("</div>");
if !snapshot.issues.is_empty() {
html.push_str("<section class=issues><h2>Partial inventory</h2><p>These records were not admitted; the snapshot is incomplete.</p><ul>");
for issue in &snapshot.issues {
write!(html, "<li>{}</li>", escape(issue)).expect("writing to a String");
}
html.push_str("</ul></section>");
}
html.push_str("<footer>Canic · Read-only snapshot · No keys, signed attempts or artifact bytes exported</footer></main><script>document.querySelectorAll('time[data-ns]').forEach(t=>{t.textContent=new Date(Number(t.dataset.ns)/1e6).toISOString()})</script></body></html>");
html
}
fn status_command(snapshot: &Fleet, operation: &str) -> String {
snapshot.configuration.as_ref().map_or_else(
|| format!("canic fleet status --no-config {operation}"),
|config| {
format!(
"canic fleet status --app {} --fleet {} {operation}",
config.app, config.fleet
)
},
)
}
fn configured_network(config: &canic_host::SelectedFleet) -> String {
match &config.config.network {
canic_host::Network::Mainnet => "IC mainnet".into(),
canic_host::Network::Local { url, .. } => format!("Local replica: {url}"),
}
}
enum SlotState<'a> {
Configured(&'a str),
Retained(&'a str),
Pending(&'a str),
Unplanned,
Issue(String),
}
impl SlotState<'_> {
fn identity(&self) -> Option<&str> {
match self {
Self::Configured(id) | Self::Retained(id) => Some(id),
Self::Pending(_) | Self::Unplanned | Self::Issue(_) => None,
}
}
}
fn slot_status(snapshot: &Fleet, slot: &str) -> String {
match slot_state(snapshot, slot) {
SlotState::Configured(id) => format!("{id} (configured identity; metadata below)"),
SlotState::Retained(id) => format!("{id} (retained deployment identity)"),
SlotState::Pending(id) => format!("Awaiting deployment; operation {id}"),
SlotState::Unplanned => "Not planned".into(),
SlotState::Issue(message) => message,
}
}
fn slot_state<'a>(snapshot: &'a Fleet, slot: &str) -> SlotState<'a> {
let Some(config) = &snapshot.configuration else {
return SlotState::Issue("No fleet configuration".into());
};
let configured_id = config
.config
.canisters
.get(slot)
.and_then(|slot| slot.id.as_ref());
let network_id = match config.config.network.binding_id() {
Ok(id) => id,
Err(error) => return SlotState::Issue(format!("Invalid configured network: {error}")),
};
let matches: Vec<_> = snapshot
.operations
.iter()
.filter(|operation| {
operation.deployment.as_ref().is_some_and(|name| {
name.fleet == config.fleet && name.app == config.app && name.canister == slot
})
})
.collect();
if matches
.iter()
.any(|operation| operation.network_id != network_id)
{
return SlotState::Issue("Network conflict; retained operation uses a different network binding. Inspect original evidence below".into());
}
if let Some(id) = configured_id {
if matches
.iter()
.any(|operation| operation.canister.as_ref() != Some(id))
{
return SlotState::Issue("Identity conflict; configured ID disagrees with retained operation. Inspect original evidence below".into());
}
return SlotState::Configured(id);
}
if matches.len() > 1 {
return SlotState::Issue("Conflicting named operations; inspect JSON evidence".into());
}
let Some(operation) = matches.first() else {
return SlotState::Unplanned;
};
match &operation.canister {
Some(id) => SlotState::Retained(id),
None => SlotState::Pending(&operation.operation),
}
}
#[derive(Clone, Copy, Default)]
pub(crate) struct ReportViewer {
pub open: bool,
pub serve: bool,
pub port: u16,
pub app_port: Option<std::num::NonZeroU16>,
}
pub(crate) fn publish(
config_path: &Path,
snapshot: &Fleet,
html: Option<&Path>,
viewer: ReportViewer,
links: &[crate::args::RouteLink],
) -> Result<()> {
let routes = declared_routes(snapshot, links)?;
let ReportViewer {
open,
serve,
port,
app_port,
} = viewer;
if html.is_none() && !open && !serve {
return Ok(());
}
if let Some(app_port) = app_port
&& (app_port.get() == port
|| !snapshot
.configuration
.as_ref()
.is_some_and(|s| matches!(s.config.network, canic_host::Network::Local { .. })))
{
return Err(Error::Invalid(
"--app-port requires a local fleet and a different port from the viewer".into(),
));
}
let path = canic_host::save_fleet_report(&render(snapshot, &routes), html)?;
eprintln!("Fleet report saved: {}", path.display());
if open || serve {
let console = match snapshot
.configuration
.as_ref()
.map(|selected| console_data(snapshot, selected, config_path, app_port))
.transpose()
{
Err(error) if app_port.is_none() => {
eprintln!("Fleet console unavailable: {error}");
None
}
result => result?,
};
crate::view::serve_report(&path, port, open, console.as_deref())?;
}
Ok(())
}
fn child_label(snapshot: &Fleet, manager: &canic_host::FleetManager) -> String {
let label = format!("slot {}", slot_number(manager));
match child_identity(snapshot, manager) {
Some(identity) => format!("{label} · {identity}"),
None => label,
}
}
fn slot_number(manager: &canic_host::FleetManager) -> usize {
manager.slot.service_index().unwrap_or(manager.slot.index()) + 1
}
fn child_identity(snapshot: &Fleet, manager: &canic_host::FleetManager) -> Option<String> {
let mut names = snapshot
.operations
.iter()
.filter(|op| {
op.network_id == manager.network_id
&& op.slot == Some(manager.slot)
&& op.management_owner() == Some(manager.manager.as_str())
})
.filter_map(|op| op.deployment.as_ref());
// Repeated records may name one child; conflicting names cannot choose a winner.
let planned = names
.next()
.filter(|first| names.all(|name| name == *first));
let reported = manager
.reported
.as_ref()
.and_then(|status| status.worker.as_deref());
planned
.map(|name| name.canister.clone())
.or_else(|| reported.and_then(|id| roles::name(snapshot, &manager.network_id, id)))
.or_else(|| reported.map(str::to_owned))
}
/// Project the selected fleet's public binding, callable exports and optional reviewed schemas.
fn console_data(
snapshot: &Fleet,
selected: &canic_host::SelectedFleet,
path: &Path,
app_port: Option<std::num::NonZeroU16>,
) -> Result<Vec<u8>> {
use std::collections::BTreeMap;
let mut canisters = BTreeMap::new();
let mut methods = BTreeMap::new();
for slot in selected.config.canisters.keys() {
let state = slot_state(snapshot, slot);
if let Some(id) = state.identity() {
canisters.insert(slot, id.to_owned());
}
if let Ok(wasm) = selected.wasm_path(path, slot, None)
&& wasm.is_file()
{
methods.insert(slot, canic_host::endpoints(&wasm)?);
}
}
let connection = match &selected.config.network {
canic_host::Network::Local { url, root_key, .. } => {
serde_json::json!({"app":selected.app,"fleet":selected.fleet,"gateway":url,"root_key":root_key,"canisters":canisters})
}
canic_host::Network::Mainnet => {
serde_json::json!({"app":selected.app,"fleet":selected.fleet,"canisters":canisters})
}
};
let baseline = path
.with_file_name("wire-baseline")
.join(&selected.app)
.join("contracts.json");
let contracts = if baseline.is_file() {
use std::io::Read as _;
let mut bytes = Vec::new();
let limit = 16 * 1024 * 1024;
std::fs::File::open(baseline)
.and_then(|f| f.take(limit + 1).read_to_end(&mut bytes))
.map_err(|e| Error::Supplier(Box::new(e)))?;
if bytes.len() as u64 > limit {
return Err(Error::Invalid("Wire inventory exceeds 16 MiB".into()));
}
serde_json::from_slice(&bytes)
.map_err(|e| Error::Invalid(format!("invalid Wire inventory: {e}")))?
} else {
serde_json::Value::Null
};
serde_json::to_vec(
&serde_json::json!({"connection":connection,"methods":methods,"contracts":contracts,"app_port":app_port}),
)
.map_err(|e| Error::Supplier(Box::new(e)))
}