canic-cli 0.110.3

Operator CLI for Canic fleet setup, builds, evidence, catalog, backup, and restore workflows
Documentation
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
//! Module: canic_cli::state
//!
//! Responsibility: expose state manifest and audit reports as diagnostic CLI
//! commands.
//! Does not own: stable-memory reads, generated files, or runtime introspection.
//! Boundary: parses `canic state` command forms and delegates report
//! construction to `canic-host`.

#[cfg(test)]
mod tests;

use crate::{
    cli::{
        clap::{flag_arg, parse_matches, parse_required_subcommand, render_usage, string_option},
        help::print_help_or_version,
    },
    version_text,
};
use canic_core::state_contract::StateManifest;
use canic_host::{
    config_discovery::{ConfigDiscoveryError, discover_workspace_canic_config_choices},
    icp_config::{IcpConfigError, resolve_current_canic_icp_root},
    role_contract::finding_detail,
    state_manifest::{
        STATE_AUDIT_COMMAND, STATE_MANIFEST_COMMAND, StateAuditReport, StateAuditStatus,
        StateManifestResolution, build_state_audit_report, resolve_workspace_state_manifest,
    },
};
use clap::Command as ClapCommand;
use std::ffi::OsString;
use thiserror::Error as ThisError;

const AUDIT_COMMAND: &str = "audit";
const CI_ARG: &str = "ci";
const MANIFEST_COMMAND: &str = "manifest";
const JSON_ARG: &str = "json";
const ROLE_ARG: &str = "role";

const STATE_HELP_AFTER: &str = "\
Examples:
  canic state audit
  canic state manifest

State commands are diagnostic-only metadata reports. They do not read stable
memory values, repair memory IDs, write generated files, modify config, create
a reviewed Fleet plan, or mutate canisters.";

const AUDIT_HELP_AFTER: &str = "\
Examples:
  canic state audit
  canic state audit --ci
  canic state audit --role root --json

Audits Rust-authored state metadata declarations only. Warnings do not exit
nonzero; failing checks exit with code 1. CI output omits passing check detail.";

const MANIFEST_HELP_AFTER: &str = "\
Examples:
  canic state manifest
  canic state manifest --role root
  canic state manifest --json

Renders the derived state manifest to stdout. This command does not write
manifest files.";

///
/// StateCommandError
///

#[derive(Debug, ThisError)]
pub enum StateCommandError {
    #[error("{0}")]
    Usage(String),

    #[error("failed to render state JSON output: {0}")]
    Json(#[from] serde_json::Error),

    #[error("state audit failed")]
    AuditFailed,

    #[error("failed to resolve ICP project root: {0}")]
    IcpRoot(#[from] IcpConfigError),

    #[error("failed to discover Canic workspace App configs: {0}")]
    ConfigDiscovery(#[from] ConfigDiscoveryError),

    #[error("state contract resolution failed: {0}")]
    ContractRejected(String),
}

impl StateCommandError {
    pub const fn exit_code(&self) -> u8 {
        match self {
            Self::Usage(_) | Self::Json(_) => 2,
            Self::AuditFailed
            | Self::IcpRoot(_)
            | Self::ConfigDiscovery(_)
            | Self::ContractRejected(_) => 1,
        }
    }

    pub const fn suppress_stderr(&self) -> bool {
        matches!(self, Self::AuditFailed)
    }
}

///
/// StateOptions
///

#[derive(Clone, Debug, Eq, PartialEq)]
struct StateOptions {
    role: Option<String>,
    json: bool,
    ci: bool,
}

impl StateOptions {
    fn parse_audit<I>(args: I) -> Result<Self, StateCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        Self::parse(args, audit_command, audit_usage, true)
    }

    fn parse_manifest<I>(args: I) -> Result<Self, StateCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        Self::parse(args, manifest_command, manifest_usage, false)
    }

    fn parse<I>(
        args: I,
        command: fn() -> ClapCommand,
        usage: fn() -> String,
        supports_ci: bool,
    ) -> Result<Self, StateCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        let matches =
            parse_matches(command(), args).map_err(|_| StateCommandError::Usage(usage()))?;
        Ok(Self {
            role: string_option(&matches, ROLE_ARG),
            json: matches.get_flag(JSON_ARG),
            ci: supports_ci && matches.get_flag(CI_ARG),
        })
    }
}

pub fn run<I>(args: I) -> Result<(), StateCommandError>
where
    I: IntoIterator<Item = OsString>,
{
    let args = args.into_iter().collect::<Vec<_>>();
    if print_help_or_version(&args, usage, version_text()) {
        return Ok(());
    }

    match parse_required_subcommand(state_command(), args)
        .map_err(|_| StateCommandError::Usage(usage()))?
    {
        (command, args) if command == AUDIT_COMMAND => run_audit(args),
        (command, args) if command == MANIFEST_COMMAND => run_manifest(args),
        _ => unreachable!("state dispatch command only defines known commands"),
    }
}

fn run_audit(args: Vec<OsString>) -> Result<(), StateCommandError> {
    if print_help_or_version(&args, audit_usage, version_text()) {
        return Ok(());
    }

    let options = StateOptions::parse_audit(args)?;
    let resolution = workspace_state_resolution(options.role.as_deref())?;
    let report = build_state_audit_report(&resolution, options.role.as_deref());
    if options.json {
        println!("{}", render_json(&report)?);
    } else if options.ci {
        println!("{}", render_audit_ci_text(&report));
    } else {
        println!("{}", render_audit_text(&report));
    }
    if report.status == StateAuditStatus::Fail {
        return Err(StateCommandError::AuditFailed);
    }
    Ok(())
}

fn run_manifest(args: Vec<OsString>) -> Result<(), StateCommandError> {
    if print_help_or_version(&args, manifest_usage, version_text()) {
        return Ok(());
    }

    let options = StateOptions::parse_manifest(args)?;
    let resolution = workspace_state_resolution(options.role.as_deref())?;
    let manifest = match resolution {
        StateManifestResolution::Resolved { manifest, .. } => manifest,
        StateManifestResolution::Rejected { errors } => {
            return Err(StateCommandError::ContractRejected(
                errors
                    .iter()
                    .map(|finding| format!("{}: {}", finding.code(), finding_detail(finding)))
                    .collect::<Vec<_>>()
                    .join("; "),
            ));
        }
    };
    if options.json {
        println!("{}", render_json(&manifest)?);
    } else {
        println!("{}", render_manifest_text(&manifest));
    }
    Ok(())
}

fn workspace_state_resolution(
    role: Option<&str>,
) -> Result<StateManifestResolution, StateCommandError> {
    let workspace_root = resolve_current_canic_icp_root()?;
    let configs = discover_workspace_canic_config_choices(&workspace_root)?;
    Ok(resolve_workspace_state_manifest(
        &workspace_root,
        &configs,
        role,
    ))
}

fn render_json<T: serde::Serialize>(value: &T) -> Result<String, StateCommandError> {
    serde_json::to_string_pretty(value).map_err(StateCommandError::from)
}

fn state_command() -> ClapCommand {
    ClapCommand::new("state")
        .bin_name("canic state")
        .about("Audit declared Canic state metadata")
        .disable_help_flag(true)
        .subcommand(crate::cli::clap::passthrough_subcommand(
            ClapCommand::new(AUDIT_COMMAND)
                .about("Audit declared state metadata")
                .disable_help_flag(true),
        ))
        .subcommand(crate::cli::clap::passthrough_subcommand(
            ClapCommand::new(MANIFEST_COMMAND)
                .about("Render the derived state manifest")
                .disable_help_flag(true),
        ))
        .after_help(STATE_HELP_AFTER)
}

fn audit_command() -> ClapCommand {
    ClapCommand::new(AUDIT_COMMAND)
        .bin_name(STATE_AUDIT_COMMAND)
        .about("Audit declared state metadata")
        .disable_help_flag(true)
        .arg(
            flag_arg(CI_ARG)
                .long(CI_ARG)
                .conflicts_with(JSON_ARG)
                .help("Print concise CI output"),
        )
        .arg(
            crate::cli::clap::value_arg(ROLE_ARG)
                .long(ROLE_ARG)
                .value_name("role")
                .help("Limit the report to one canister role"),
        )
        .arg(
            flag_arg(JSON_ARG)
                .long(JSON_ARG)
                .conflicts_with(CI_ARG)
                .help("Print JSON output"),
        )
        .after_help(AUDIT_HELP_AFTER)
}

fn manifest_command() -> ClapCommand {
    ClapCommand::new(MANIFEST_COMMAND)
        .bin_name(STATE_MANIFEST_COMMAND)
        .about("Render the derived state manifest")
        .disable_help_flag(true)
        .arg(
            crate::cli::clap::value_arg(ROLE_ARG)
                .long(ROLE_ARG)
                .value_name("role")
                .help("Limit the manifest to one canister role"),
        )
        .arg(flag_arg(JSON_ARG).long(JSON_ARG).help("Print JSON output"))
        .after_help(MANIFEST_HELP_AFTER)
}

fn usage() -> String {
    render_usage(state_command)
}

fn audit_usage() -> String {
    render_usage(audit_command)
}

fn manifest_usage() -> String {
    render_usage(manifest_command)
}

fn render_audit_text(report: &StateAuditReport) -> String {
    let mut lines = vec![
        report.command.to_string(),
        format!("status: {}", report.status.label()),
        format!("schema_version: {}", report.schema_version),
        format!("scope: {}", report.scope.label()),
    ];
    if let Some(role) = &report.role {
        lines.push(format!("role: {role}"));
    }
    lines.push(String::new());
    lines.push("checks".to_string());
    for check in &report.checks {
        lines.push(format!(
            "{} [{}] {}",
            check.category.label(),
            check.status.label(),
            check.code
        ));
        lines.push(format!("  subject: {}", check.subject));
        lines.push(format!("  detail: {}", check.detail));
        if let Some(next) = &check.next {
            lines.push(format!("  next: {next}"));
        }
        lines.push(format!("  source: {}", check.source.label()));
    }
    if !report.next_actions.is_empty() {
        lines.push(String::new());
        lines.push("next actions".to_string());
        for action in &report.next_actions {
            lines.push(format!("  - {action}"));
        }
    }
    lines.join("\n")
}

fn render_audit_ci_text(report: &StateAuditReport) -> String {
    let warnings = report
        .checks
        .iter()
        .filter(|check| check.status == StateAuditStatus::Warn)
        .collect::<Vec<_>>();
    let failures = report
        .checks
        .iter()
        .filter(|check| check.status == StateAuditStatus::Fail)
        .collect::<Vec<_>>();
    let mut lines = vec![
        report.command.to_string(),
        format!("status: {}", report.status.label()),
        format!("scope: {}", report.scope.label()),
    ];
    if let Some(role) = &report.role {
        lines.push(format!("role: {role}"));
    }
    lines.extend([
        format!("checks: {}", report.checks.len()),
        format!("warnings: {}", warnings.len()),
        format!("failures: {}", failures.len()),
    ]);

    for check in warnings.into_iter().chain(failures) {
        lines.push(format!(
            "{} {} {} {}",
            check.status.label(),
            check.category.label(),
            check.code,
            check.subject
        ));
        lines.push(format!("  detail: {}", check.detail));
        if let Some(next) = &check.next {
            lines.push(format!("  next: {next}"));
        }
        lines.push(format!("  source: {}", check.source.label()));
    }

    lines.join("\n")
}

fn render_manifest_text(manifest: &StateManifest) -> String {
    let mut lines = vec![
        "canic state manifest".to_string(),
        format!("schema_version: {}", manifest.schema_version),
    ];
    for role in &manifest.roles {
        lines.push(String::new());
        lines.push(format!("role: {}", role.canister_role));
        lines.push("state".to_string());
        for domain in &role.state {
            lines.push(format!("  {} [{}]", domain.domain, domain.storage.as_str()));
            lines.push(format!("    version: {}", domain.version));
            lines.push(format!(
                "    memory_id: {}",
                domain
                    .memory_id
                    .map_or_else(|| "none".to_string(), |id| id.to_string())
            ));
            lines.push(format!("    owner: {}", domain.owner));
            lines.push(format!("    record: {}", domain.record));
            lines.push(format!("    snapshot: {}", domain.snapshot));
        }
        if !role.reserved_memory.is_empty() {
            lines.push("reserved_memory".to_string());
            for entry in &role.reserved_memory {
                lines.push(format!("  {}", entry.label));
                lines.push(format!("    memory_id: {}", entry.memory_id));
                lines.push(format!("    owner: {}", entry.owner));
                lines.push(format!("    reason: {}", entry.reason));
            }
        }
    }
    lines.join("\n")
}