canic-host 0.32.0

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
//! Release-set discovery, manifest emission, and staging helpers.

use std::time::{SystemTime, UNIX_EPOCH};

mod config;
mod manifest;
mod paths;
mod stage;

pub use config::{
    configured_fleet_name, configured_install_targets, configured_release_roles,
    configured_role_kinds,
};
pub use manifest::{
    ReleaseSetEntry, RootReleaseSetManifest, emit_root_release_set_manifest,
    emit_root_release_set_manifest_if_ready, emit_root_release_set_manifest_with_config,
    load_root_release_set_manifest,
};
pub use paths::{
    canister_manifest_path, canisters_root, config_path, dfx_root, load_root_package_version,
    load_workspace_package_version, resolve_artifact_root, root_manifest_path,
    root_release_set_manifest_path, workspace_manifest_path, workspace_root,
};
use stage::build_release_set_entry;
pub(crate) use stage::dfx_call;
pub use stage::{resume_root_bootstrap, stage_root_release_set};

#[cfg(test)]
use stage::read_release_artifact;

#[cfg(test)]
use config::{
    configured_fleet_name_from_source, configured_release_roles_from_source,
    configured_role_kinds_from_source,
};

pub(super) const CANISTERS_ROOT_RELATIVE: &str = "canisters";
pub(super) const ROOT_CONFIG_FILE: &str = "canic.toml";
pub(super) const WORKSPACE_MANIFEST_RELATIVE: &str = "Cargo.toml";
pub const ROOT_RELEASE_SET_MANIFEST_FILE: &str = "root.release-set.json";
pub(super) const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];
pub(super) const WASM_MAGIC: [u8; 4] = [0x00, 0x61, 0x73, 0x6d];

// Read the current host wall clock so staged manifests use a stable whole-second
// timestamp without depending on an exported root time endpoint.
pub(super) fn root_time_secs(root_canister: &str) -> Result<u64, Box<dyn std::error::Error>> {
    let _ = root_canister;
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|err| format!("system clock before unix epoch: {err}"))?;
    Ok(now.as_secs())
}

#[cfg(test)]
mod tests {
    use super::{
        canister_manifest_path, canisters_root, config_path, configured_fleet_name_from_source,
        configured_install_targets, configured_release_roles_from_source,
        configured_role_kinds_from_source, read_release_artifact, root_manifest_path,
    };
    use flate2::{Compression, write::GzEncoder};
    use std::{
        env, fs,
        io::Write,
        path::{Path, PathBuf},
        sync::{Mutex, OnceLock},
        time::{SystemTime, UNIX_EPOCH},
    };

    static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    const REAL_CONFIG: &str = r#"
controllers = []
app_index = ["user_hub", "scale_hub"]

[fleet]
name = "demo"

[app]
init_mode = "enabled"
[app.whitelist]

[auth.delegated_tokens]
enabled = true
ecdsa_key_name = "test_key_1"

[standards]
icrc21 = true

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

[subnets.prime.canisters.user_hub]
kind = "singleton"

[subnets.prime.canisters.scale_hub]
kind = "singleton"
"#;

    const MULTI_ROOT_CONFIG: &str = r#"
controllers = []
app_index = []

[app]
init_mode = "enabled"
[app.whitelist]

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

[subnets.secondary.canisters.root]
kind = "root"
"#;

    const NO_ROOT_CONFIG: &str = r#"
controllers = []
app_index = []

[app]
init_mode = "enabled"
[app.whitelist]

[subnets.prime.canisters.user_hub]
kind = "singleton"
"#;

    fn with_guarded_env<T>(test: impl FnOnce() -> T) -> T {
        let lock = ENV_LOCK.get_or_init(|| Mutex::new(()));
        let _guard = lock.lock().unwrap();
        test()
    }

    struct TempWorkspace {
        path: PathBuf,
    }

    impl TempWorkspace {
        fn new() -> Self {
            let unique = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_or(0, |duration| duration.as_nanos());
            let path = env::temp_dir().join(format!(
                "canic-host-release-set-tests-{}-{unique}",
                std::process::id()
            ));
            fs::create_dir_all(&path).expect("create temp workspace");
            Self { path }
        }

        fn path(&self) -> &Path {
            &self.path
        }
    }

    impl Drop for TempWorkspace {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.path);
        }
    }

    #[test]
    fn configured_release_roles_filters_root_and_wasm_store() {
        let config = r#"
controllers = []
app_index = []

[app]
init_mode = "enabled"
[app.whitelist]

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

[subnets.prime.canisters.user_hub]
kind = "singleton"

[subnets.prime.canisters.scale_hub]
kind = "singleton"
"#;

        let roles = configured_release_roles_from_source(config).expect("release roles");

        assert_eq!(roles, vec!["scale_hub".to_string(), "user_hub".to_string()]);
    }

    #[test]
    fn configured_role_kinds_lists_configured_roles() {
        let kinds = configured_role_kinds_from_source(REAL_CONFIG).expect("role kinds");

        assert_eq!(kinds.get("root").map(String::as_str), Some("root"));
        assert_eq!(kinds.get("user_hub").map(String::as_str), Some("singleton"));
        assert_eq!(
            kinds.get("scale_hub").map(String::as_str),
            Some("singleton")
        );
    }

    #[test]
    fn configured_fleet_name_reads_required_config_identity() {
        let name = configured_fleet_name_from_source(REAL_CONFIG).expect("fleet name");

        assert_eq!(name, "demo");
    }

    #[test]
    fn configured_fleet_name_rejects_missing_config_identity() {
        let err = configured_fleet_name_from_source(
            r#"
controllers = []
app_index = []

[app]
init_mode = "enabled"
[app.whitelist]

[subnets.prime.canisters.root]
kind = "root"
"#,
        )
        .unwrap_err();

        assert!(
            err.to_string()
                .contains("missing required [fleet].name in canic.toml"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn configured_release_roles_rejects_multiple_root_subnets() {
        let err = configured_release_roles_from_source(MULTI_ROOT_CONFIG).unwrap_err();
        assert!(
            err.to_string()
                .contains("root kind must be unique globally"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn configured_release_roles_rejects_missing_root() {
        let err = configured_release_roles_from_source(NO_ROOT_CONFIG).unwrap_err();
        assert!(
            err.to_string().contains("root canister not defined"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn configured_install_targets_prefixes_root_canister() {
        let temp = TempWorkspace::new();
        let config_path = temp.path().join("canic.toml");
        fs::write(&config_path, REAL_CONFIG).expect("write config");

        let targets = configured_install_targets(&config_path, "root").expect("install targets");

        assert_eq!(
            targets,
            vec![
                "root".to_string(),
                "scale_hub".to_string(),
                "user_hub".to_string()
            ]
        );
    }

    #[test]
    fn canisters_root_follows_config_parent_when_manifest_metadata_is_unavailable() {
        with_guarded_env(|| {
            let temp = TempWorkspace::new();
            let workspace_root = temp.path();
            let config_dir = workspace_root.join("custom");
            fs::create_dir_all(&config_dir).expect("create config dir");
            let config_file = config_dir.join("override.toml");
            fs::write(&config_file, "").expect("write config");

            let previous = std::env::var_os("CANIC_CONFIG_PATH");
            unsafe {
                std::env::set_var("CANIC_CONFIG_PATH", &config_file);
            }
            let result = canisters_root(workspace_root);
            unsafe {
                if let Some(value) = previous {
                    std::env::set_var("CANIC_CONFIG_PATH", value);
                } else {
                    std::env::remove_var("CANIC_CONFIG_PATH");
                }
            }

            assert_eq!(result, config_dir);
        });
    }

    #[test]
    fn config_path_defaults_under_canisters_root() {
        with_guarded_env(|| {
            let temp = TempWorkspace::new();
            let workspace_root = temp.path();
            let canisters_dir = workspace_root.join("canisters");
            fs::create_dir_all(&canisters_dir).expect("create canisters dir");
            let expected = canisters_dir.join("canic.toml");

            let previous = std::env::var_os("CANIC_CONFIG_PATH");
            unsafe {
                std::env::remove_var("CANIC_CONFIG_PATH");
            }
            let result = config_path(workspace_root);
            unsafe {
                if let Some(value) = previous {
                    std::env::set_var("CANIC_CONFIG_PATH", value);
                }
            }

            assert_eq!(result, expected);
        });
    }

    #[test]
    fn root_manifest_path_prefers_canister_manifest_metadata() {
        let temp = TempWorkspace::new();
        let workspace_root = temp.path();
        fs::create_dir_all(workspace_root.join("canisters/demo/root")).expect("create root dir");
        fs::create_dir_all(workspace_root.join("canisters/demo/root/src"))
            .expect("create root src dir");
        fs::write(
            workspace_root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"canisters/demo/root\"]\n",
        )
        .expect("write workspace manifest");
        fs::write(
            workspace_root.join("canisters/demo/root/Cargo.toml"),
            "[package]\nname = \"canister_root\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .expect("write root manifest");
        fs::write(workspace_root.join("canisters/demo/root/src/lib.rs"), "")
            .expect("write root lib");

        assert_eq!(
            root_manifest_path(workspace_root),
            workspace_root.join("canisters/demo/root/Cargo.toml")
        );
    }

    #[test]
    fn canister_manifest_path_prefers_canister_manifest_metadata() {
        let temp = TempWorkspace::new();
        let workspace_root = temp.path();
        fs::create_dir_all(workspace_root.join("canisters/demo/user_hub"))
            .expect("create user hub dir");
        fs::create_dir_all(workspace_root.join("canisters/demo/user_hub/src"))
            .expect("create user hub src dir");
        fs::write(
            workspace_root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"canisters/demo/user_hub\"]\n",
        )
        .expect("write workspace manifest");
        fs::write(
            workspace_root.join("canisters/demo/user_hub/Cargo.toml"),
            "[package]\nname = \"canister_user_hub\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .expect("write user hub manifest");
        fs::write(
            workspace_root.join("canisters/demo/user_hub/src/lib.rs"),
            "",
        )
        .expect("write user hub lib");

        assert_eq!(
            canister_manifest_path(workspace_root, "user_hub"),
            workspace_root.join("canisters/demo/user_hub/Cargo.toml")
        );
    }

    #[test]
    fn read_release_artifact_accepts_gzip_wasm() {
        let temp = TempWorkspace::new();
        let path = temp.path().join("artifact.wasm.gz");
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder
            .write_all(&[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
            .expect("write wasm bytes");
        fs::write(&path, encoder.finish().expect("finish encoder")).expect("write artifact");

        let artifact = read_release_artifact(&path).expect("read artifact");

        assert!(!artifact.is_empty());
    }

    #[test]
    fn read_release_artifact_rejects_plain_wasm() {
        let temp = TempWorkspace::new();
        let path = temp.path().join("artifact.wasm");
        fs::write(&path, [0x00, 0x61, 0x73, 0x6d]).expect("write plain wasm");

        let err = read_release_artifact(&path).unwrap_err();

        assert!(
            err.to_string().contains("not gzip-compressed"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn read_release_artifact_rejects_non_wasm_payload() {
        let temp = TempWorkspace::new();
        let path = temp.path().join("artifact.bin.gz");
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(b"not wasm").expect("write payload");
        fs::write(&path, encoder.finish().expect("finish encoder")).expect("write artifact");

        let err = read_release_artifact(&path).unwrap_err();

        assert!(
            err.to_string()
                .contains("does not decompress to a wasm module"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn canister_manifest_path_falls_back_to_canisters_root() {
        let temp = TempWorkspace::new();
        let workspace_root = temp.path();
        fs::create_dir_all(workspace_root.join("canisters")).expect("create canisters dir");

        assert_eq!(
            canister_manifest_path(workspace_root, "user_hub"),
            workspace_root.join("canisters/user_hub/Cargo.toml")
        );
    }

    #[test]
    fn canisters_root_defaults_to_workspace_canisters_dir() {
        let temp = TempWorkspace::new();
        let workspace_root = temp.path();

        assert_eq!(
            canisters_root(workspace_root),
            workspace_root.join("canisters")
        );
    }

    #[test]
    fn config_path_override_is_normalized_against_workspace_root() {
        with_guarded_env(|| {
            let temp = TempWorkspace::new();
            let workspace_root = temp.path();
            let relative = Path::new("configs/canic.toml");
            let previous = std::env::var_os("CANIC_CONFIG_PATH");
            unsafe {
                std::env::set_var("CANIC_CONFIG_PATH", relative);
            }
            let result = config_path(workspace_root);
            unsafe {
                if let Some(value) = previous {
                    std::env::set_var("CANIC_CONFIG_PATH", value);
                } else {
                    std::env::remove_var("CANIC_CONFIG_PATH");
                }
            }

            assert_eq!(result, workspace_root.join(relative));
        });
    }
}