canic-host 0.88.1

Host-side build, install, deployment, and fleet-template library for Canic workspaces
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
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use crate::{
    install_root::{
        current_canic_project_root, discover_project_canic_config_choices, project_fleet_roots,
    },
    release_set::{configured_deployable_roles, configured_fleet_name, icp_root},
    workspace_discovery::discover_icp_root_from,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    error::Error,
    fmt, fs,
    path::{Path, PathBuf},
};

const ICP_CONFIG_FILE: &str = "icp.yaml";
pub const DEFAULT_LOCAL_GATEWAY_PORT: u16 = 8000;

///
/// IcpBuildEnvironment
///
/// Build-time network class baked into Canic Wasm artifacts.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IcpBuildEnvironment {
    Ic,
    Local,
}

impl IcpBuildEnvironment {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Ic => "ic",
            Self::Local => "local",
        }
    }
}

///
/// IcpConfigError
///

#[derive(Debug)]
pub enum IcpConfigError {
    NoIcpRoot { start: PathBuf },
    Config(String),
    Io(std::io::Error),
}

impl fmt::Display for IcpConfigError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoIcpRoot { start } => {
                write!(
                    formatter,
                    "could not find icp.yaml from {}",
                    start.display()
                )
            }
            Self::Config(message) => write!(formatter, "{message}"),
            Self::Io(err) => write!(formatter, "{err}"),
        }
    }
}

impl Error for IcpConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io(err) => Some(err),
            Self::Config(_) | Self::NoIcpRoot { .. } => None,
        }
    }
}

impl From<std::io::Error> for IcpConfigError {
    fn from(err: std::io::Error) -> Self {
        Self::Io(err)
    }
}

///
/// IcpProjectConfigReport
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcpProjectConfigReport {
    pub path: PathBuf,
    pub icp_root: PathBuf,
    pub icp_yaml_present: bool,
    pub canisters: Vec<String>,
    pub environments: Vec<String>,
    pub missing_canisters: Vec<String>,
    pub missing_environments: Vec<String>,
    pub local_network_present: bool,
}

impl IcpProjectConfigReport {
    #[must_use]
    pub const fn is_ready(&self) -> bool {
        self.icp_yaml_present
            && self.local_network_present
            && self.missing_canisters.is_empty()
            && self.missing_environments.is_empty()
    }

    #[must_use]
    pub fn issues(&self) -> Vec<String> {
        let mut issues = Vec::new();
        if !self.icp_yaml_present {
            issues.push(format!("missing {}", self.path.display()));
        }
        if !self.local_network_present {
            issues.push("missing local network entry".to_string());
        }
        if !self.missing_canisters.is_empty() {
            issues.push(format!(
                "missing canisters: {}",
                self.missing_canisters.join(", ")
            ));
        }
        if !self.missing_environments.is_empty() {
            issues.push(format!(
                "missing environments: {}",
                self.missing_environments.join(", ")
            ));
        }
        issues
    }
}

/// Return the configured local ICP gateway port, falling back to ICP's default.
pub(crate) fn configured_local_gateway_port() -> Result<u16, IcpConfigError> {
    let root = current_icp_root()?;
    configured_local_gateway_port_from_root(&root)
}

/// Return the configured local ICP gateway port for one ICP project root.
pub fn configured_local_gateway_port_from_root(root: &Path) -> Result<u16, IcpConfigError> {
    let source = fs::read_to_string(root.join(ICP_CONFIG_FILE))?;
    Ok(local_gateway_port_from_yaml(&source))
}

/// Resolve an ICP environment name to the build-time network class used by Canic.
///
/// The implicit `local` and `ic` environments resolve without project config.
/// Named environments must exist in `icp.yaml`; their declared network decides
/// whether Cargo builds a local/test artifact or an IC mainnet artifact.
pub fn resolve_icp_build_environment_from_root(
    root: &Path,
    environment: &str,
) -> Result<IcpBuildEnvironment, IcpConfigError> {
    let environment = environment.trim();
    if environment.is_empty() {
        return Err(IcpConfigError::Config(
            "ICP environment name must not be empty".to_string(),
        ));
    }
    match environment {
        "local" => return Ok(IcpBuildEnvironment::Local),
        "ic" => return Ok(IcpBuildEnvironment::Ic),
        _ => {}
    }

    let path = root.join(ICP_CONFIG_FILE);
    let source = fs::read_to_string(&path).map_err(|err| {
        if err.kind() == std::io::ErrorKind::NotFound {
            IcpConfigError::Config(format!(
                "ICP environment '{environment}' cannot be resolved because {} is missing",
                path.display()
            ))
        } else {
            IcpConfigError::Io(err)
        }
    })?;
    resolve_icp_build_environment_from_yaml(&source, environment)
        .map_err(|message| IcpConfigError::Config(format!("{}: {message}", path.display())))
}

/// Inspect whether `icp.yaml` contains the entries implied by Canic fleet configs.
pub fn inspect_canic_icp_yaml(
    fleet_filter: Option<&str>,
) -> Result<IcpProjectConfigReport, IcpConfigError> {
    let root = resolve_current_canic_icp_root()?;
    inspect_canic_icp_yaml_from_root(&root, fleet_filter)
}

/// Inspect one ICP project root without mutating its `icp.yaml`.
pub fn inspect_canic_icp_yaml_from_root(
    root: &Path,
    fleet_filter: Option<&str>,
) -> Result<IcpProjectConfigReport, IcpConfigError> {
    let path = root.join(ICP_CONFIG_FILE);
    let (source, icp_yaml_present) = read_optional_icp_yaml(&path)?;
    let spec = discover_project_spec(root, fleet_filter)?;
    let configured_canisters = top_level_named_items(&source, "canisters:");
    let configured_environments = top_level_named_items(&source, "environments:");
    let lines = source.lines().collect::<Vec<_>>();
    let local_network_present = local_network_block(&lines).is_some();

    let missing_canisters = spec
        .canisters
        .iter()
        .filter(|name| !configured_canisters.contains(*name))
        .cloned()
        .collect::<Vec<_>>();
    let missing_environments = spec
        .environments
        .keys()
        .filter(|name| !configured_environments.contains(*name))
        .cloned()
        .collect::<Vec<_>>();

    Ok(IcpProjectConfigReport {
        path,
        icp_root: root.to_path_buf(),
        icp_yaml_present,
        canisters: spec.canisters,
        environments: spec.environments.into_keys().collect(),
        missing_canisters,
        missing_environments,
        local_network_present,
    })
}

fn read_optional_icp_yaml(path: &Path) -> Result<(String, bool), IcpConfigError> {
    match fs::read_to_string(path) {
        Ok(source) => Ok((source, true)),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok((String::new(), false)),
        Err(err) => Err(err.into()),
    }
}

fn current_icp_root() -> Result<PathBuf, IcpConfigError> {
    let start = std::env::current_dir()?;
    discover_icp_root_from(&start).ok_or(IcpConfigError::NoIcpRoot { start })
}

/// Resolve the ICP project root implied by the current Canic fleet layout.
pub fn resolve_current_canic_icp_root() -> Result<PathBuf, IcpConfigError> {
    let search_root = current_project_search_root()?;
    let choices = discover_project_canic_config_choices(&search_root)
        .map_err(|err| IcpConfigError::Config(err.to_string()))?;
    if !choices.is_empty() {
        return Ok(search_root);
    }

    current_icp_root().or_else(|_| {
        icp_root()
            .map_err(|err| IcpConfigError::Config(err.to_string()))
            .and_then(|path| path.canonicalize().map_err(IcpConfigError::from))
    })
}

fn current_project_search_root() -> Result<PathBuf, IcpConfigError> {
    let root = current_canic_project_root()
        .map_err(|err| IcpConfigError::Config(err.to_string()))?
        .canonicalize()?;
    if !discover_project_canic_config_choices(&root)
        .map_err(|err| IcpConfigError::Config(err.to_string()))?
        .is_empty()
    {
        return Ok(root);
    }

    if let Ok(root) = icp_root() {
        return Ok(root);
    }
    Ok(std::env::current_dir()?.canonicalize()?)
}

///
/// CanicIcpSpec
///

#[derive(Clone, Debug, Eq, PartialEq)]
struct CanicIcpSpec {
    canisters: Vec<String>,
    environments: BTreeMap<String, Vec<String>>,
}

fn discover_project_spec(
    root: &Path,
    fleet_filter: Option<&str>,
) -> Result<CanicIcpSpec, IcpConfigError> {
    let choices = discover_project_canic_config_choices(root)
        .map_err(|err| IcpConfigError::Config(err.to_string()))?;
    if choices.is_empty() {
        return Err(IcpConfigError::Config(format!(
            "no Canic fleet configs found under {}\nCreate fleets/<fleet>/canic.toml, then add matching entries to icp.yaml and rerun `canic status`.",
            display_project_fleet_roots(root)
        )));
    }

    let mut canisters = Vec::<String>::new();
    let mut seen_canisters = BTreeSet::<String>::new();
    let mut environments = BTreeMap::<String, Vec<String>>::new();
    let mut matched_filter = fleet_filter.is_none();

    for config_path in choices {
        let fleet = configured_fleet_name(&config_path)
            .map_err(|err| IcpConfigError::Config(err.to_string()))?;
        if let Some(filter) = fleet_filter {
            if filter != fleet {
                continue;
            }
            matched_filter = true;
        }

        let roles = configured_deployable_roles(&config_path)
            .map_err(|err| IcpConfigError::Config(err.to_string()))?;
        for role in &roles {
            if seen_canisters.insert(role.clone()) {
                canisters.push(role.clone());
            }
        }
        environments.insert(fleet, roles);
    }

    if let Some(fleet) = fleet_filter
        && !matched_filter
    {
        return Err(IcpConfigError::Config(format!(
            "no Canic fleet config found for {fleet}\nExpected a config under {} with `[fleet].name = \"{fleet}\"`.",
            display_project_fleet_roots(root)
        )));
    }

    Ok(CanicIcpSpec {
        canisters,
        environments,
    })
}

fn display_project_fleet_roots(root: &Path) -> String {
    project_fleet_roots(root)
        .into_iter()
        .map(|path| path.display().to_string())
        .collect::<Vec<_>>()
        .join(" or ")
}

fn top_level_section(lines: &[&str], header: &str) -> Option<(usize, usize)> {
    let start = lines
        .iter()
        .position(|line| line_indent(line) == 0 && line.trim() == header)?;
    let end = lines
        .iter()
        .enumerate()
        .skip(start + 1)
        .find(|(_, line)| {
            !line.trim().is_empty() && line_indent(line) == 0 && !line.trim_start().starts_with('#')
        })
        .map_or(lines.len(), |(index, _)| index);
    Some((start, end))
}

fn resolve_icp_build_environment_from_yaml(
    source: &str,
    environment: &str,
) -> Result<IcpBuildEnvironment, String> {
    let lines = source.lines().collect::<Vec<_>>();
    let (_, environment_start, environment_end) =
        named_item_block(&lines, "environments:", environment)?.ok_or_else(|| {
            format!(
                "ICP environment '{environment}' is not declared; add it under environments or use the implicit local/ic environment"
            )
        })?;
    let network = item_scalar_field(&lines, environment_start, environment_end, "network")?
        .ok_or_else(|| format!("ICP environment '{environment}' has no network"))?;

    match network.as_str() {
        "ic" => Ok(IcpBuildEnvironment::Ic),
        "local" => Ok(IcpBuildEnvironment::Local),
        _ => {
            let (_, network_start, network_end) = named_item_block(&lines, "networks:", &network)?
                .ok_or_else(|| {
                    format!(
                        "ICP environment '{environment}' references undeclared network '{network}'"
                    )
                })?;
            let mode = item_scalar_field(&lines, network_start, network_end, "mode")?
                .ok_or_else(|| format!("ICP network '{network}' has no mode"))?;
            match mode.as_str() {
                // ICP CLI reserves the implicit `ic` network for mainnet.
                // Declared managed and connected networks are non-mainnet build classes.
                "connected" | "managed" => Ok(IcpBuildEnvironment::Local),
                _ => Err(format!(
                    "ICP network '{network}' has unsupported mode '{mode}'"
                )),
            }
        }
    }
}

fn named_item_block(
    lines: &[&str],
    section: &str,
    name: &str,
) -> Result<Option<(String, usize, usize)>, String> {
    let Some((section_start, section_end)) = top_level_section(lines, section) else {
        return Ok(None);
    };
    let starts = lines[section_start + 1..section_end]
        .iter()
        .enumerate()
        .filter_map(|(offset, line)| {
            if line_indent(line) != 2 {
                return None;
            }
            line.trim()
                .strip_prefix("- name:")
                .map(trim_yaml_scalar)
                .filter(|item_name| !item_name.is_empty())
                .map(|item_name| (item_name.to_string(), section_start + 1 + offset))
        })
        .collect::<Vec<_>>();
    let matches = starts
        .iter()
        .enumerate()
        .filter(|(_, (item_name, _))| item_name == name)
        .collect::<Vec<_>>();
    let [(match_index, (item_name, start))] = matches.as_slice() else {
        return if matches.is_empty() {
            Ok(None)
        } else {
            Err(format!("duplicate '{name}' entries under {section}"))
        };
    };
    let end = starts
        .get(match_index + 1)
        .map_or(section_end, |(_, next_start)| *next_start);
    Ok(Some((item_name.clone(), *start, end)))
}

fn item_scalar_field(
    lines: &[&str],
    start: usize,
    end: usize,
    field: &str,
) -> Result<Option<String>, String> {
    let prefix = format!("{field}:");
    let values = lines[start + 1..end]
        .iter()
        .filter_map(|line| {
            if line_indent(line) != 4 {
                return None;
            }
            line.trim()
                .strip_prefix(&prefix)
                .map(trim_yaml_scalar)
                .filter(|value| !value.is_empty())
                .map(str::to_string)
        })
        .collect::<Vec<_>>();
    match values.as_slice() {
        [] => Ok(None),
        [value] => Ok(Some(value.clone())),
        _ => Err(format!(
            "duplicate '{field}' fields in '{}'",
            section_name(lines, start)
        )),
    }
}

fn section_name<'a>(lines: &'a [&'a str], start: usize) -> &'a str {
    lines[start]
        .trim()
        .strip_prefix("- name:")
        .map_or("item", trim_yaml_scalar)
}

fn local_gateway_port_from_yaml(source: &str) -> u16 {
    let lines = source.lines().collect::<Vec<_>>();
    let Some((start, end)) = local_network_block(&lines) else {
        return DEFAULT_LOCAL_GATEWAY_PORT;
    };

    lines[start..end]
        .iter()
        .find_map(|line| {
            line.trim()
                .strip_prefix("port:")
                .and_then(|value| value.trim().parse::<u16>().ok())
        })
        .unwrap_or(DEFAULT_LOCAL_GATEWAY_PORT)
}

fn local_network_block(lines: &[&str]) -> Option<(usize, usize)> {
    let (section_start, section_end) = top_level_section(lines, "networks:")?;
    let start = lines[section_start + 1..section_end]
        .iter()
        .position(|line| line_indent(line) == 2 && line.trim() == "- name: local")?
        + section_start
        + 1;
    let end = lines[start + 1..section_end]
        .iter()
        .position(|line| line_indent(line) == 2 && line.trim_start().starts_with("- name:"))
        .map_or(section_end, |offset| start + 1 + offset);
    Some((start, end))
}

fn top_level_named_items(source: &str, header: &str) -> BTreeSet<String> {
    let lines = source.lines().collect::<Vec<_>>();
    let Some((start, end)) = top_level_section(&lines, header) else {
        return BTreeSet::new();
    };

    lines[start + 1..end]
        .iter()
        .filter_map(|line| {
            if line_indent(line) != 2 {
                return None;
            }
            line.trim()
                .strip_prefix("- name:")
                .map(trim_yaml_scalar)
                .filter(|name| !name.is_empty())
                .map(str::to_string)
        })
        .collect()
}

fn trim_yaml_scalar(value: &str) -> &str {
    value.trim().trim_matches('"').trim_matches('\'')
}

fn line_indent(line: &str) -> usize {
    line.chars().take_while(|c| *c == ' ').count()
}

#[cfg(test)]
mod tests;