canic-host 0.36.11

Host-side build, install, fleet, and release-set 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
use crate::{
    install_root::{
        current_canic_project_root, discover_project_canic_config_choices, project_fleet_roots,
    },
    release_set::{configured_fleet_name, configured_fleet_roles, icp_root},
    workspace_discovery::discover_icp_root_from,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    error::Error,
    fmt, fs,
    io::ErrorKind,
    path::{Path, PathBuf},
};

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

///
/// 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)
    }
}

///
/// IcpProjectSyncReport
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcpProjectSyncReport {
    pub path: PathBuf,
    pub icp_root: PathBuf,
    pub changed: bool,
    pub canisters: Vec<String>,
    pub environments: Vec<String>,
}

/// Return the configured local ICP gateway port, falling back to ICP's default.
pub 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(configured_local_gateway_port_from_source(&source))
}

/// Set the local ICP gateway port in one ICP project root.
pub fn set_configured_local_gateway_port_in_root(
    root: &Path,
    port: u16,
) -> Result<PathBuf, IcpConfigError> {
    let path = root.join(ICP_CONFIG_FILE);
    let source = fs::read_to_string(&path)?;
    let updated = upsert_local_gateway_port(&source, port);
    fs::write(&path, updated)?;
    Ok(path)
}

/// Reconcile the Canic-managed canister and environment sections in `icp.yaml`.
pub fn sync_canic_icp_yaml(
    fleet_filter: Option<&str>,
) -> Result<IcpProjectSyncReport, IcpConfigError> {
    let root = resolve_current_canic_icp_root()?;
    let path = root.join(ICP_CONFIG_FILE);
    let source = match fs::read_to_string(&path) {
        Ok(source) => source,
        Err(err) if err.kind() == ErrorKind::NotFound => String::new(),
        Err(err) => return Err(err.into()),
    };
    let spec = discover_project_spec(&root, fleet_filter)?;
    let updated = sync_canic_sections(&source, &spec.canisters, &spec.environments);
    let changed = updated != source;
    if changed {
        fs::write(&path, updated)?;
    }

    Ok(IcpProjectSyncReport {
        path,
        icp_root: root,
        changed,
        canisters: spec.canisters,
        environments: spec.environments.into_keys().collect(),
    })
}

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> {
    if let Ok(path) = std::env::var("CANIC_ICP_ROOT") {
        return PathBuf::from(path)
            .canonicalize()
            .map_err(IcpConfigError::from);
    }

    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 rerun `canic replica start` or `canic fleet sync --fleet <fleet>`.",
            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 fleet_filter.is_some_and(|filter| filter == fleet) {
            matched_filter = true;
        }

        let roles = configured_fleet_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 sync_canic_sections(
    source: &str,
    canisters: &[String],
    environments: &BTreeMap<String, Vec<String>>,
) -> String {
    let without_canisters = remove_top_level_section(source, "canisters:");
    let without_environments = remove_top_level_section(&without_canisters, "environments:");
    let (networks, rest) = take_top_level_section(&without_environments, "networks:");
    let mut sections = vec![render_canisters_section(canisters)];
    if let Some(networks) = networks {
        sections.push(networks);
    }
    sections.push(render_environments_section(environments));
    let rest = rest.trim();
    if !rest.is_empty() {
        sections.push(rest.to_string());
    }

    let mut updated = sections.join("\n\n");
    updated.push('\n');
    updated
}

fn take_top_level_section(source: &str, header: &str) -> (Option<String>, String) {
    let mut lines = source.lines().map(str::to_string).collect::<Vec<_>>();
    let line_refs = lines.iter().map(String::as_str).collect::<Vec<_>>();
    let Some((start, end)) = top_level_section(&line_refs, header) else {
        return (None, source.to_string());
    };

    let section = lines[start..end].join("\n");
    lines.drain(start..end);

    let rest = compact_blank_lines(lines).join("\n");
    (Some(section), rest)
}

fn render_canisters_section(canisters: &[String]) -> String {
    if canisters.is_empty() {
        return "canisters: []".to_string();
    }

    let mut lines = vec!["canisters:".to_string()];
    for (index, canister) in canisters.iter().enumerate() {
        if index > 0 {
            lines.push(String::new());
        }
        lines.extend([
            format!("  - name: {canister}"),
            "    build:".to_string(),
            "      steps:".to_string(),
            "        - type: script".to_string(),
            "          commands:".to_string(),
            format!(
                "            - cargo run -q -p canic-host --example build_artifact -- {canister}"
            ),
        ]);
    }
    lines.join("\n")
}

fn render_environments_section(environments: &BTreeMap<String, Vec<String>>) -> String {
    if environments.is_empty() {
        return "environments: []".to_string();
    }

    environments
        .iter()
        .enumerate()
        .flat_map(|(index, (environment, canisters))| {
            let mut lines = Vec::new();
            if index > 0 {
                lines.push(String::new());
            }
            if index == 0 {
                lines.push("environments:".to_string());
            }
            lines.extend([
                format!("  - name: {environment}"),
                "    network: local".to_string(),
                format!("    canisters: [{}]", canisters.join(", ")),
            ]);
            lines
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn remove_top_level_section(source: &str, header: &str) -> String {
    let mut lines = source.lines().map(str::to_string).collect::<Vec<_>>();
    let line_refs = lines.iter().map(String::as_str).collect::<Vec<_>>();
    let Some((start, end)) = top_level_section(&line_refs, header) else {
        return source.to_string();
    };
    lines.drain(start..end);

    compact_blank_lines(lines).join("\n")
}

fn compact_blank_lines(lines: Vec<String>) -> Vec<String> {
    let mut compacted = Vec::<String>::new();
    let mut previous_blank = false;
    for line in lines {
        let blank = line.trim().is_empty();
        if blank && previous_blank {
            continue;
        }
        compacted.push(line);
        previous_blank = blank;
    }

    compacted
}

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 configured_local_gateway_port_from_source(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 upsert_local_gateway_port(source: &str, port: u16) -> String {
    let had_trailing_newline = source.ends_with('\n');
    let mut lines = source.lines().map(str::to_string).collect::<Vec<_>>();

    let local_block = {
        let line_refs = lines.iter().map(String::as_str).collect::<Vec<_>>();
        local_network_block(&line_refs)
    };
    if let Some((start, end)) = local_block {
        if let Some(index) = (start..end).find(|index| lines[*index].trim().starts_with("port:")) {
            let indent = line_indent(&lines[index]);
            lines[index] = format!("{}port: {port}", " ".repeat(indent));
            return join_lines(lines, had_trailing_newline);
        }

        if let Some(gateway_index) = (start..end).find(|index| lines[*index].trim() == "gateway:") {
            let indent = line_indent(&lines[gateway_index]) + 2;
            lines.insert(
                gateway_index + 1,
                format!("{}port: {port}", " ".repeat(indent)),
            );
            return join_lines(lines, had_trailing_newline);
        }

        lines.splice(end..end, local_network_gateway_lines(port));
        return join_lines(lines, had_trailing_newline);
    }

    let networks = {
        let line_refs = lines.iter().map(String::as_str).collect::<Vec<_>>();
        top_level_section(&line_refs, "networks:")
    };
    if let Some((networks_start, networks_end)) = networks {
        let local_network = local_network_lines(port);
        let inserted_len = local_network.len();
        lines.splice(networks_end..networks_end, local_network);
        if networks_end == networks_start + 1 {
            lines.insert(networks_end + inserted_len, String::new());
        }
        return join_lines(lines, had_trailing_newline);
    }

    let insert_at = lines
        .iter()
        .position(|line| line.trim() == "environments:")
        .unwrap_or(lines.len());
    let mut insert = vec!["networks:".to_string()];
    insert.extend(local_network_lines(port));
    insert.push(String::new());
    lines.splice(insert_at..insert_at, insert);
    join_lines(lines, had_trailing_newline)
}

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 local_network_lines(port: u16) -> Vec<String> {
    vec![
        "  - name: local".to_string(),
        "    mode: managed".to_string(),
        "    gateway:".to_string(),
        "      bind: 127.0.0.1".to_string(),
        format!("      port: {port}"),
    ]
}

fn local_network_gateway_lines(port: u16) -> Vec<String> {
    vec![
        "    gateway:".to_string(),
        "      bind: 127.0.0.1".to_string(),
        format!("      port: {port}"),
    ]
}

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

fn join_lines(lines: Vec<String>, had_trailing_newline: bool) -> String {
    let mut joined = lines.join("\n");
    if had_trailing_newline {
        joined.push('\n');
    }
    joined
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::temp_dir;
    use std::fs;

    #[test]
    fn defaults_local_gateway_port_without_network_config() {
        let source = "canisters: []\n";

        assert_eq!(
            configured_local_gateway_port_from_source(source),
            DEFAULT_LOCAL_GATEWAY_PORT
        );
    }

    #[test]
    fn reads_local_gateway_port_from_network_config() {
        let source = "networks:\n  - name: local\n    mode: managed\n    gateway:\n      bind: 127.0.0.1\n      port: 8001\n";

        assert_eq!(configured_local_gateway_port_from_source(source), 8001);
    }

    #[test]
    fn ignores_nested_networks_keys_when_reading_local_gateway_port() {
        let source = "canisters:\n  - name: root\n    metadata:\n      networks:\n        - local\n\nnetworks:\n  - name: local\n    mode: managed\n    gateway:\n      bind: 127.0.0.1\n      port: 8010\n";

        assert_eq!(configured_local_gateway_port_from_source(source), 8010);
    }

    #[test]
    fn inserts_local_network_before_environments() {
        let source = "canisters: []\n\nenvironments:\n  - name: local\n    network: local\n";

        let updated = upsert_local_gateway_port(source, 8002);

        assert!(updated.contains("networks:\n  - name: local\n    mode: managed"));
        assert!(updated.contains("      port: 8002"));
        assert!(updated.find("networks:") < updated.find("environments:"));
    }

    #[test]
    fn replaces_existing_local_gateway_port() {
        let source = "networks:\n  - name: local\n    mode: managed\n    gateway:\n      bind: 127.0.0.1\n      port: 8001\n";

        let updated = upsert_local_gateway_port(source, 8003);

        assert!(updated.contains("      port: 8003"));
        assert!(!updated.contains("      port: 8001"));
    }

    #[test]
    fn syncs_canic_sections_and_preserves_other_top_level_sections() {
        let source = "canisters:\n  - name: old\n\nnetworks:\n  - name: local\n    mode: managed\n    gateway:\n      bind: 127.0.0.1\n      port: 8009\n\nenvironments:\n  - name: old\n    network: local\n    canisters: [old]\n";
        let canisters = vec!["root".to_string(), "app".to_string()];
        let environments = BTreeMap::from([(
            "test".to_string(),
            vec!["root".to_string(), "app".to_string()],
        )]);

        let updated = sync_canic_sections(source, &canisters, &environments);

        assert!(updated.starts_with("canisters:\n  - name: root\n"));
        assert!(
            updated.contains(
                "            - cargo run -q -p canic-host --example build_artifact -- app"
            )
        );
        assert!(updated.contains(
            "environments:\n  - name: test\n    network: local\n    canisters: [root, app]"
        ));
        assert!(updated.contains("networks:\n  - name: local\n    mode: managed"));
        assert!(updated.find("networks:") < updated.find("environments:"));
        assert!(!updated.contains("- name: old"));
    }

    #[test]
    fn renders_empty_canic_sections_for_empty_project_specs() {
        let updated = sync_canic_sections("", &[], &BTreeMap::new());

        assert_eq!(updated, "canisters: []\n\nenvironments: []\n");
    }

    #[test]
    fn discovers_root_fleet_configs_for_icp_sync() {
        let root = temp_dir("canic-icp-sync-root-fleets");
        let config = root.join("fleets/toko/canic.toml");
        fs::create_dir_all(config.parent().expect("config parent")).expect("create config parent");
        fs::write(
            &config,
            r#"
[fleet]
name = "toko"

[subnets.prime.canisters.root]
kind = "root"

[subnets.prime.canisters.app]
kind = "singleton"
"#,
        )
        .expect("write config");

        let spec = discover_project_spec(&root, Some("toko")).expect("discover spec");

        assert_eq!(spec.canisters, vec!["root", "app"]);
        assert_eq!(
            spec.environments,
            BTreeMap::from([(
                "toko".to_string(),
                vec!["root".to_string(), "app".to_string()]
            )])
        );
        fs::remove_dir_all(root).expect("clean temp dir");
    }

    #[test]
    fn nested_commands_discover_outer_project_root_with_fleets() {
        let root = temp_dir("canic-icp-root-nested");
        let config = root.join("fleets/toko/canic.toml");
        let nested = root.join("backend/src");
        fs::create_dir_all(&nested).expect("create nested dir");
        fs::create_dir_all(config.parent().expect("config parent")).expect("create config parent");
        fs::write(root.join("icp.yaml"), "").expect("write icp config");
        fs::write(&config, "[fleet]\nname = \"toko\"\n").expect("write config");

        let icp_root = crate::install_root::discover_canic_project_root_from(&nested)
            .expect("discover project root")
            .expect("project root is present");

        assert_eq!(icp_root, root.canonicalize().expect("canonical root"));
        fs::remove_dir_all(root).expect("clean temp dir");
    }

    #[test]
    fn outer_project_root_wins_over_nested_fleets() {
        let root = temp_dir("canic-icp-root-outer-wins");
        let outer_config = root.join("fleets/toko/canic.toml");
        let nested_config = root.join("services/fleets/toko/canic.toml");
        let nested = root.join("services/src");
        fs::create_dir_all(outer_config.parent().expect("outer config parent"))
            .expect("create outer config parent");
        fs::create_dir_all(nested_config.parent().expect("nested config parent"))
            .expect("create nested config parent");
        fs::create_dir_all(&nested).expect("create nested dir");
        fs::write(root.join("icp.yaml"), "").expect("write icp config");
        fs::write(&outer_config, "[fleet]\nname = \"toko\"\n").expect("write outer config");
        fs::write(&nested_config, "[fleet]\nname = \"toko\"\n").expect("write nested config");

        let icp_root = crate::install_root::discover_canic_project_root_from(&nested)
            .expect("discover project root")
            .expect("project root is present");

        assert_eq!(icp_root, root.canonicalize().expect("canonical root"));
        fs::remove_dir_all(root).expect("clean temp dir");
    }

    #[test]
    fn icp_sync_rejects_missing_fleet_configs() {
        let root = temp_dir("canic-icp-sync-missing");
        fs::create_dir_all(&root).expect("create root");

        let err = discover_project_spec(&root, None).expect_err("missing configs should fail");
        let message = err.to_string();

        assert!(message.contains("no Canic fleet configs found under"));
        assert!(message.contains("fleets/<fleet>/canic.toml"));
        fs::remove_dir_all(root).expect("clean temp dir");
    }
}