canic-cli 0.224.0

Canic command line deployment tool
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use canic_host::{Error, Fleet, Result};
use std::{fmt::Write as _, path::Path};

mod metrics;
mod roles;
mod stores;
mod terminal;
#[cfg(test)]
mod tests;
mod watch;
pub(crate) use terminal::render as terminal;
pub(crate) use watch::{collect, watch};

fn escape(value: &str) -> String {
    value
        .replace('&', "&")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

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: &[String]) -> 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
            .split_once(':')
            .ok_or_else(|| Error::Invalid("route must be ENTRY:WORKER".into()))?;
        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 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(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 &amp; 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(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 &amp; 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),
    }
}

pub(crate) fn publish(
    snapshot: &Fleet,
    html: Option<&Path>,
    open: bool,
    serve: bool,
    port: u16,
    links: &[String],
) -> Result<()> {
    let routes = declared_routes(snapshot, links)?;
    if html.is_none() && !open && !serve {
        return Ok(());
    }
    let path = canic_host::save_fleet_report(&render(snapshot, &routes), html)?;
    eprintln!("Fleet report saved: {}", path.display());
    if open || serve {
        crate::view::serve(&path, port, open)?;
    }
    Ok(())
}

fn child_label(snapshot: &Fleet, manager: &canic_host::FleetManager) -> String {
    use canic_management_protocol::children::ChildId;
    let slot = manager.slot.unwrap_or(ChildId::FIRST);
    let mut names = snapshot
        .operations
        .iter()
        .filter(|op| {
            op.network_id == manager.network_id
                && op.slot.unwrap_or(ChildId::FIRST) == 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());
    let identity = 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));
    let label = format!("slot {}", slot.index() + 1);
    match identity {
        Some(identity) => format!("{label} · {identity}"),
        None => label,
    }
}