Skip to main content

canic_host/install_root/
state.rs

1use crate::release_set::icp_root;
2use serde::{Deserialize, Serialize};
3use std::{fs, path::Path, path::PathBuf};
4
5pub(super) const INSTALL_STATE_SCHEMA_VERSION: u32 = 1;
6
7///
8/// InstallState
9///
10
11#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
12pub struct InstallState {
13    pub schema_version: u32,
14    pub fleet: String,
15    pub installed_at_unix_secs: u64,
16    pub network: String,
17    pub root_target: String,
18    pub root_canister_id: String,
19    pub root_build_target: String,
20    pub workspace_root: String,
21    pub icp_root: String,
22    pub config_path: String,
23    pub release_set_manifest_path: String,
24}
25
26/// Read a named fleet install state for one project/network when present.
27pub(super) fn read_fleet_install_state(
28    icp_root: &Path,
29    network: &str,
30    fleet: &str,
31) -> Result<Option<InstallState>, Box<dyn std::error::Error>> {
32    validate_network_name(network)?;
33    validate_fleet_name(fleet)?;
34    let path = fleet_install_state_path(icp_root, network, fleet);
35    if !path.is_file() {
36        return Ok(None);
37    }
38
39    let bytes = fs::read(&path)?;
40    let state: InstallState = serde_json::from_slice(&bytes)?;
41    Ok(Some(state))
42}
43
44/// Read a named fleet state for the discovered current project.
45pub fn read_named_fleet_install_state(
46    network: &str,
47    fleet: &str,
48) -> Result<Option<InstallState>, Box<dyn std::error::Error>> {
49    let icp_root = icp_root()?;
50    read_fleet_install_state(&icp_root, network, fleet)
51}
52
53/// Return the project-local state path for one named fleet.
54#[must_use]
55pub(super) fn fleet_install_state_path(icp_root: &Path, network: &str, fleet: &str) -> PathBuf {
56    fleets_dir(icp_root, network).join(format!("{fleet}.json"))
57}
58
59// Return the directory that owns named fleet state files.
60fn fleets_dir(icp_root: &Path, network: &str) -> PathBuf {
61    icp_root.join(".canic").join(network).join("fleets")
62}
63
64// Persist the completed install state under the project-local `.canic` directory.
65pub(super) fn write_install_state(
66    icp_root: &Path,
67    network: &str,
68    state: &InstallState,
69) -> Result<PathBuf, Box<dyn std::error::Error>> {
70    validate_network_name(network)?;
71    validate_fleet_name(&state.fleet)?;
72    let path = fleet_install_state_path(icp_root, network, &state.fleet);
73    if let Some(parent) = path.parent() {
74        fs::create_dir_all(parent)?;
75    }
76    remove_conflicting_fleet_states(icp_root, network, state)?;
77    fs::write(&path, serde_json::to_vec_pretty(state)?)?;
78    Ok(path)
79}
80
81// A named ICP canister belongs to one installed fleet at a time. When a new
82// install reuses that root, older fleet state would otherwise point at the new
83// deployment and make `canic list <old-fleet>` show the wrong topology.
84fn remove_conflicting_fleet_states(
85    icp_root: &Path,
86    network: &str,
87    state: &InstallState,
88) -> Result<(), Box<dyn std::error::Error>> {
89    let dir = fleets_dir(icp_root, network);
90    if !dir.is_dir() {
91        return Ok(());
92    }
93
94    for entry in fs::read_dir(dir)? {
95        let entry = entry?;
96        let path = entry.path();
97        if !path.is_file() || path == fleet_install_state_path(icp_root, network, &state.fleet) {
98            continue;
99        }
100
101        let Ok(bytes) = fs::read(&path) else {
102            continue;
103        };
104        let Ok(existing) = serde_json::from_slice::<InstallState>(&bytes) else {
105            continue;
106        };
107        if existing.network == state.network
108            && (existing.root_target == state.root_target
109                || existing.root_canister_id == state.root_canister_id)
110        {
111            fs::remove_file(path)?;
112        }
113    }
114
115    Ok(())
116}
117
118// Keep fleet names filesystem-safe and easy to type in commands.
119pub(super) fn validate_fleet_name(name: &str) -> Result<(), Box<dyn std::error::Error>> {
120    let valid = !name.is_empty()
121        && name
122            .bytes()
123            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'));
124    if valid {
125        Ok(())
126    } else {
127        Err(format!("invalid fleet name {name:?}; use letters, numbers, '-' or '_'").into())
128    }
129}
130
131// Keep network names safe for `.canic/<network>` state paths.
132fn validate_network_name(name: &str) -> Result<(), Box<dyn std::error::Error>> {
133    let valid = !name.is_empty()
134        && name
135            .bytes()
136            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'));
137    if valid {
138        Ok(())
139    } else {
140        Err(format!("invalid network name {name:?}; use letters, numbers, '-' or '_'").into())
141    }
142}