1use crate::format::cycles_tc;
2use canic_core::{
3 bootstrap::{compiled::MetricsProfile, parse_config_model},
4 ids::CanisterRole,
5};
6use std::{
7 collections::{BTreeMap, BTreeSet},
8 fs,
9 path::{Path, PathBuf},
10};
11use toml::Value as TomlValue;
12
13#[derive(Clone, Copy)]
14enum RootSubnetRoleScope {
15 Release,
16 Deployable,
17}
18
19const DEFAULT_INITIAL_CYCLES: u128 = 5_000_000_000_000;
20pub const LOCAL_ROOT_MIN_READY_CYCLES: u128 = 100_000_000_000_000;
21const DEFAULT_RANDOMNESS_RESEED_INTERVAL_SECS: u64 = 3600;
22
23#[derive(Clone, Debug, Eq, PartialEq)]
27pub struct ConfiguredPoolExpectation {
28 pub pool: String,
29 pub canister_role: String,
30}
31
32#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct ConfiguredRoleLifecycle {
37 pub fleet: String,
38 pub role: String,
39 pub display: String,
40 pub declaration_kind: String,
41 pub package: String,
42 pub attached: bool,
43 pub state: String,
44 pub topology: Option<String>,
45}
46
47#[derive(Clone, Debug, Eq, PartialEq)]
51pub struct DeclaredFleetRole {
52 pub fleet: String,
53 pub role: String,
54 pub display: String,
55 pub package: String,
56}
57
58#[derive(Clone, Debug, Eq, PartialEq)]
62pub struct AttachedFleetRole {
63 pub fleet: String,
64 pub role: String,
65 pub display: String,
66 pub subnet: String,
67 pub kind: String,
68 pub topology: String,
69}
70
71#[derive(Clone, Debug, Eq, PartialEq)]
75pub struct RenamedFleetRole {
76 pub fleet: String,
77 pub old_role: String,
78 pub new_role: String,
79 pub old_display: String,
80 pub new_display: String,
81 pub package_manifest: Option<PathBuf>,
82 pub package_manifest_note: Option<String>,
83}
84
85impl RootSubnetRoleScope {
86 const fn includes_root(self) -> bool {
87 matches!(self, Self::Deployable)
88 }
89}
90
91pub fn configured_release_roles(
93 config_path: &Path,
94) -> Result<Vec<String>, Box<dyn std::error::Error>> {
95 let config_source = fs::read_to_string(config_path)?;
96 configured_release_roles_from_source(&config_source)
97 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
98}
99
100pub fn configured_deployable_roles(
102 config_path: &Path,
103) -> Result<Vec<String>, Box<dyn std::error::Error>> {
104 let config_source = fs::read_to_string(config_path)?;
105 configured_deployable_roles_from_source(&config_source)
106 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
107}
108
109pub fn configured_bootstrap_roles(
111 config_path: &Path,
112) -> Result<Vec<String>, Box<dyn std::error::Error>> {
113 let config_source = fs::read_to_string(config_path)?;
114 configured_bootstrap_roles_from_source(&config_source)
115 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
116}
117
118pub fn configured_install_targets(
120 config_path: &Path,
121 root_canister: &str,
122) -> Result<Vec<String>, Box<dyn std::error::Error>> {
123 let mut targets = vec![root_canister.to_string()];
124 targets.extend(configured_release_roles(config_path)?);
125 Ok(targets)
126}
127
128pub fn configured_local_root_create_cycles(
130 config_path: &Path,
131) -> Result<u128, Box<dyn std::error::Error>> {
132 let config_source = fs::read_to_string(config_path)?;
133 configured_local_root_create_cycles_from_source(&config_source)
134 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
135}
136
137pub fn configured_fleet_name(config_path: &Path) -> Result<String, Box<dyn std::error::Error>> {
139 let config_source = fs::read_to_string(config_path)?;
140 configured_fleet_name_from_source(&config_source)
141 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
142}
143
144pub fn configured_controllers(
146 config_path: &Path,
147) -> Result<Vec<String>, Box<dyn std::error::Error>> {
148 let config_source = fs::read_to_string(config_path)?;
149 configured_controllers_from_source(&config_source)
150 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
151}
152
153pub fn configured_pool_expectations(
155 config_path: &Path,
156) -> Result<Vec<ConfiguredPoolExpectation>, Box<dyn std::error::Error>> {
157 let config_source = fs::read_to_string(config_path)?;
158 configured_pool_expectations_from_source(&config_source)
159 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
160}
161
162pub fn configured_role_lifecycle(
164 config_path: &Path,
165) -> Result<Vec<ConfiguredRoleLifecycle>, Box<dyn std::error::Error>> {
166 let config_source = fs::read_to_string(config_path)?;
167 configured_role_lifecycle_from_source(&config_source)
168 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
169}
170
171pub fn declare_fleet_role(
173 config_path: &Path,
174 expected_fleet: &str,
175 role: &str,
176 package: &str,
177) -> Result<DeclaredFleetRole, Box<dyn std::error::Error>> {
178 let source = fs::read_to_string(config_path)?;
179 let updated = declare_fleet_role_source(&source, expected_fleet, role, package)
180 .map_err(|err| format!("invalid {}: {err}", config_path.display()))?;
181 fs::write(config_path, updated.source)?;
182 Ok(updated.role)
183}
184
185pub fn attach_fleet_role(
187 config_path: &Path,
188 expected_fleet: &str,
189 role: &str,
190 subnet: &str,
191 kind: &str,
192) -> Result<AttachedFleetRole, Box<dyn std::error::Error>> {
193 let source = fs::read_to_string(config_path)?;
194 let updated = attach_fleet_role_source(&source, expected_fleet, role, subnet, kind)
195 .map_err(|err| format!("invalid {}: {err}", config_path.display()))?;
196 fs::write(config_path, updated.source)?;
197 Ok(updated.role)
198}
199
200pub fn rename_fleet_role(
202 config_path: &Path,
203 expected_fleet: &str,
204 old_role: &str,
205 new_role: &str,
206) -> Result<RenamedFleetRole, Box<dyn std::error::Error>> {
207 let source = fs::read_to_string(config_path)?;
208 let updated =
209 rename_fleet_role_source(&source, config_path, expected_fleet, old_role, new_role)
210 .map_err(|err| format!("invalid {}: {err}", config_path.display()))?;
211 fs::write(config_path, updated.source)?;
212 if let (Some(path), Some(source)) = (&updated.package_manifest, &updated.package_source) {
213 fs::write(path, source)?;
214 }
215 Ok(updated.role)
216}
217
218#[must_use]
220pub fn matching_fleet_config_paths(choices: &[PathBuf], fleet: &str) -> Vec<PathBuf> {
221 choices
222 .iter()
223 .filter_map(|path| match configured_fleet_name(path) {
224 Ok(name) if name == fleet => Some(path.clone()),
225 Ok(_) | Err(_) => None,
226 })
227 .collect()
228}
229
230pub fn configured_role_kinds(
232 config_path: &Path,
233) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
234 let config_source = fs::read_to_string(config_path)?;
235 configured_role_kinds_from_source(&config_source)
236 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
237}
238
239pub fn configured_role_capabilities(
241 config_path: &Path,
242) -> Result<BTreeMap<String, Vec<String>>, Box<dyn std::error::Error>> {
243 let config_source = fs::read_to_string(config_path)?;
244 configured_role_capabilities_from_source(&config_source)
245 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
246}
247
248pub fn configured_role_auto_create(
250 config_path: &Path,
251) -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
252 let config_source = fs::read_to_string(config_path)?;
253 configured_role_auto_create_from_source(&config_source)
254 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
255}
256
257pub fn configured_role_topups(
259 config_path: &Path,
260) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
261 let config_source = fs::read_to_string(config_path)?;
262 configured_role_topups_from_source(&config_source)
263 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
264}
265
266pub fn configured_role_metrics_profiles(
268 config_path: &Path,
269) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
270 let config_source = fs::read_to_string(config_path)?;
271 configured_role_metrics_profiles_from_source(&config_source)
272 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
273}
274
275pub fn configured_role_details(
277 config_path: &Path,
278) -> Result<BTreeMap<String, Vec<String>>, Box<dyn std::error::Error>> {
279 let config_source = fs::read_to_string(config_path)?;
280 configured_role_details_from_source(&config_source)
281 .map_err(|err| format!("invalid {}: {err}", config_path.display()).into())
282}
283
284pub(super) fn configured_role_kinds_from_source(
286 config_source: &str,
287) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
288 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
289 let mut kinds = BTreeMap::<String, String>::new();
290
291 for subnet in config.subnets.values() {
292 for (role, canister) in &subnet.canisters {
293 let role = role.as_str().to_string();
294 let kind = canister.kind.to_string();
295 match kinds.get(&role) {
296 Some(existing) if existing != &kind => {
297 kinds.insert(role, "mixed".to_string());
298 }
299 Some(_) => {}
300 None => {
301 kinds.insert(role, kind);
302 }
303 }
304 }
305 }
306
307 Ok(kinds)
308}
309
310pub(super) fn configured_role_lifecycle_from_source(
312 config_source: &str,
313) -> Result<Vec<ConfiguredRoleLifecycle>, Box<dyn std::error::Error>> {
314 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
315 let fleet = config
316 .fleet_name()
317 .ok_or_else(|| "missing required [fleet].name in canic.toml".to_string())?
318 .to_string();
319 let attached_roles = config.attached_roles();
320 let mut topology = BTreeMap::<CanisterRole, Vec<String>>::new();
321
322 for (subnet_role, subnet) in &config.subnets {
323 for (role, canister) in &subnet.canisters {
324 topology
325 .entry(role.clone())
326 .or_default()
327 .push(format!("{subnet_role}/{role}"));
328
329 if let Some(scaling) = &canister.scaling {
330 for (pool, scale_pool) in &scaling.pools {
331 topology
332 .entry(scale_pool.canister_role.clone())
333 .or_default()
334 .push(format!("{subnet_role}/{role}/scaling/{pool}"));
335 }
336 }
337
338 if let Some(sharding) = &canister.sharding {
339 for (pool, shard_pool) in &sharding.pools {
340 topology
341 .entry(shard_pool.canister_role.clone())
342 .or_default()
343 .push(format!("{subnet_role}/{role}/sharding/{pool}"));
344 }
345 }
346
347 if let Some(directory) = &canister.directory {
348 for (pool, directory_pool) in &directory.pools {
349 topology
350 .entry(directory_pool.canister_role.clone())
351 .or_default()
352 .push(format!("{subnet_role}/{role}/directory/{pool}"));
353 }
354 }
355 }
356 }
357
358 Ok(config
359 .roles
360 .iter()
361 .map(|(role, declaration)| {
362 let role_name = role.as_str().to_string();
363 let attached = attached_roles.contains(role);
364 ConfiguredRoleLifecycle {
365 fleet: fleet.clone(),
366 display: format!("{fleet}.{role}"),
367 role: role_name,
368 declaration_kind: if role.is_root() { "root" } else { "canister" }.to_string(),
369 package: declaration.package.clone(),
370 attached,
371 state: if attached { "attached" } else { "declared" }.to_string(),
372 topology: topology.get(role).map(|labels| labels.join(",")),
373 }
374 })
375 .collect())
376}
377
378#[derive(Debug)]
379pub(super) struct DeclaredFleetRoleSource {
380 pub(super) source: String,
381 pub(super) role: DeclaredFleetRole,
382}
383
384#[derive(Debug)]
385pub(super) struct AttachedFleetRoleSource {
386 pub(super) source: String,
387 pub(super) role: AttachedFleetRole,
388}
389
390#[derive(Debug)]
391pub(super) struct RenamedFleetRoleSource {
392 pub(super) source: String,
393 pub(super) package_manifest: Option<PathBuf>,
394 pub(super) package_source: Option<String>,
395 pub(super) role: RenamedFleetRole,
396}
397
398pub(super) fn declare_fleet_role_source(
399 config_source: &str,
400 expected_fleet: &str,
401 role: &str,
402 package: &str,
403) -> Result<DeclaredFleetRoleSource, Box<dyn std::error::Error>> {
404 let role = role.trim();
405 let package = package.trim();
406 if role.is_empty() {
407 return Err("role must not be empty".into());
408 }
409 if package.is_empty() {
410 return Err("package must not be empty".into());
411 }
412 if role == "root" {
413 return Err("root role must be attached to topology; declare ordinary roles only".into());
414 }
415 if !role
416 .bytes()
417 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
418 {
419 return Err("role must contain only ASCII letters, numbers, '_' or '-'".into());
420 }
421
422 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
423 let actual_fleet = config
424 .fleet_name()
425 .ok_or_else(|| "missing required [fleet].name in canic.toml".to_string())?;
426 if actual_fleet != expected_fleet {
427 return Err(format!(
428 "selected config declares fleet {actual_fleet:?}, not {expected_fleet:?}"
429 )
430 .into());
431 }
432
433 let role_id = CanisterRole::owned(role.to_string());
434 if config.declares_role(&role_id) {
435 return Err(format!("role {expected_fleet}.{role} is already declared").into());
436 }
437
438 let mut source = config_source.trim_end().to_string();
439 source.push_str("\n\n[roles.");
440 source.push_str(&toml_string_literal(role));
441 source.push_str("]\nkind = \"canister\"\npackage = ");
442 source.push_str(&toml_string_literal(package));
443 source.push('\n');
444
445 parse_config_model(&source).map_err(|err| err.to_string())?;
446
447 Ok(DeclaredFleetRoleSource {
448 source,
449 role: DeclaredFleetRole {
450 fleet: expected_fleet.to_string(),
451 role: role.to_string(),
452 display: format!("{expected_fleet}.{role}"),
453 package: package.to_string(),
454 },
455 })
456}
457
458pub(super) fn attach_fleet_role_source(
459 config_source: &str,
460 expected_fleet: &str,
461 role: &str,
462 subnet: &str,
463 kind: &str,
464) -> Result<AttachedFleetRoleSource, Box<dyn std::error::Error>> {
465 let role = role.trim();
466 let subnet = subnet.trim();
467 let kind = kind.trim();
468 validate_role_name(role)?;
469 validate_subnet_name(subnet)?;
470 validate_attach_kind(kind)?;
471 if role == "root" {
472 return Err("root role must already be attached through root topology".into());
473 }
474
475 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
476 let actual_fleet = config
477 .fleet_name()
478 .ok_or_else(|| "missing required [fleet].name in canic.toml".to_string())?;
479 if actual_fleet != expected_fleet {
480 return Err(format!(
481 "selected config declares fleet {actual_fleet:?}, not {expected_fleet:?}"
482 )
483 .into());
484 }
485
486 let role_id = CanisterRole::owned(role.to_string());
487 config
488 .roles
489 .get(&role_id)
490 .ok_or_else(|| format!("role {expected_fleet}.{role} is not declared"))?;
491 if config.attached_roles().contains(&role_id) {
492 return Err(format!("role {expected_fleet}.{role} is already attached").into());
493 }
494
495 let mut source = config_source.trim_end().to_string();
496 source.push_str("\n\n[subnets.");
497 source.push_str(&toml_string_literal(subnet));
498 source.push_str(".canisters.");
499 source.push_str(&toml_string_literal(role));
500 source.push_str("]\nkind = ");
501 source.push_str(&toml_string_literal(kind));
502 source.push('\n');
503
504 parse_config_model(&source).map_err(|err| err.to_string())?;
505
506 Ok(AttachedFleetRoleSource {
507 source,
508 role: AttachedFleetRole {
509 fleet: expected_fleet.to_string(),
510 role: role.to_string(),
511 display: format!("{expected_fleet}.{role}"),
512 subnet: subnet.to_string(),
513 kind: kind.to_string(),
514 topology: format!("{subnet}/{role}"),
515 },
516 })
517}
518
519pub(super) fn rename_fleet_role_source(
520 config_source: &str,
521 config_path: &Path,
522 expected_fleet: &str,
523 old_role: &str,
524 new_role: &str,
525) -> Result<RenamedFleetRoleSource, Box<dyn std::error::Error>> {
526 let old_role = old_role.trim();
527 let new_role = new_role.trim();
528 validate_role_name(old_role)?;
529 validate_role_name(new_role)?;
530 if old_role == "root" || new_role == "root" {
531 return Err("root role cannot be renamed through fleet role rename".into());
532 }
533 if old_role == new_role {
534 return Err("old role and new role must differ".into());
535 }
536
537 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
538 let actual_fleet = config
539 .fleet_name()
540 .ok_or_else(|| "missing required [fleet].name in canic.toml".to_string())?;
541 if actual_fleet != expected_fleet {
542 return Err(format!(
543 "selected config declares fleet {actual_fleet:?}, not {expected_fleet:?}"
544 )
545 .into());
546 }
547
548 let old_id = CanisterRole::owned(old_role.to_string());
549 let new_id = CanisterRole::owned(new_role.to_string());
550 let declaration = config
551 .roles
552 .get(&old_id)
553 .ok_or_else(|| format!("role {expected_fleet}.{old_role} is not declared"))?;
554 if config.declares_role(&new_id) {
555 return Err(format!("role {expected_fleet}.{new_role} is already declared").into());
556 }
557
558 let source = rename_config_role_references(config_source, old_role, new_role)?;
559 parse_config_model(&source).map_err(|err| err.to_string())?;
560
561 let (package_manifest, package_source, package_manifest_note) =
562 config_path.parent().map_or_else(
563 || (None, None, Some("config path has no parent".to_string())),
564 |parent| {
565 let manifest = parent.join(&declaration.package).join("Cargo.toml");
566 match update_package_manifest_role(&manifest, expected_fleet, old_role, new_role) {
567 Ok(Some(updated)) => (Some(manifest), Some(updated), None),
568 Ok(None) => (
569 None,
570 None,
571 Some(format!(
572 "{} did not contain matching [package.metadata.canic] fleet/role metadata",
573 manifest.display()
574 )),
575 ),
576 Err(err) => (None, None, Some(err.to_string())),
577 }
578 },
579 );
580
581 Ok(RenamedFleetRoleSource {
582 source,
583 package_manifest: package_manifest.clone(),
584 package_source,
585 role: RenamedFleetRole {
586 fleet: expected_fleet.to_string(),
587 old_role: old_role.to_string(),
588 new_role: new_role.to_string(),
589 old_display: format!("{expected_fleet}.{old_role}"),
590 new_display: format!("{expected_fleet}.{new_role}"),
591 package_manifest,
592 package_manifest_note,
593 },
594 })
595}
596
597fn rename_config_role_references(
598 source: &str,
599 old_role: &str,
600 new_role: &str,
601) -> Result<String, Box<dyn std::error::Error>> {
602 let old_literal = toml_string_literal(old_role);
603 let new_literal = toml_string_literal(new_role);
604 let mut updated = Vec::new();
605
606 for line in source.lines() {
607 let mut line = rename_role_header(line, old_role, new_role)?;
608 let trimmed = line.trim_start();
609 if toml_assignment_key(trimmed) == Some("canister_role")
610 || toml_assignment_key(trimmed) == Some("app_index")
611 {
612 line = line.replace(&old_literal, &new_literal);
613 }
614 updated.push(line);
615 }
616
617 let mut result = updated.join("\n");
618 if source.ends_with('\n') {
619 result.push('\n');
620 }
621 Ok(result)
622}
623
624fn rename_role_header(
625 line: &str,
626 old_role: &str,
627 new_role: &str,
628) -> Result<String, Box<dyn std::error::Error>> {
629 let trimmed = line.trim();
630 if !trimmed.starts_with('[') || !trimmed.ends_with(']') || trimmed.starts_with("[[") {
631 return Ok(line.to_string());
632 }
633
634 let Some(prefix_len) = line.find('[') else {
635 return Ok(line.to_string());
636 };
637 let inner = &trimmed[1..trimmed.len() - 1];
638 let mut path = parse_toml_dotted_path(inner)?;
639 let rename_roles_header = path.len() == 2 && path[0] == "roles" && path[1] == old_role;
640 let rename_canister_header =
641 path.len() >= 4 && path[0] == "subnets" && path[2] == "canisters" && path[3] == old_role;
642
643 if rename_roles_header {
644 path[1] = new_role.to_string();
645 } else if rename_canister_header {
646 path[3] = new_role.to_string();
647 } else {
648 return Ok(line.to_string());
649 }
650
651 Ok(format!(
652 "{}[{}]",
653 &line[..prefix_len],
654 path.iter()
655 .map(|part| toml_string_literal(part))
656 .collect::<Vec<_>>()
657 .join(".")
658 ))
659}
660
661fn parse_toml_dotted_path(path: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
662 let mut parts = Vec::new();
663 let mut current = String::new();
664 let mut chars = path.chars();
665 let mut in_quote = false;
666
667 while let Some(ch) = chars.next() {
668 match ch {
669 '"' if !in_quote => in_quote = true,
670 '"' if in_quote => in_quote = false,
671 '\\' if in_quote => {
672 let Some(escaped) = chars.next() else {
673 return Err("unterminated TOML escape in table header".into());
674 };
675 current.push(escaped);
676 }
677 '.' if !in_quote => {
678 parts.push(current.trim().to_string());
679 current.clear();
680 }
681 ch => current.push(ch),
682 }
683 }
684
685 if in_quote {
686 return Err("unterminated quoted TOML table header".into());
687 }
688 parts.push(current.trim().to_string());
689 Ok(parts)
690}
691
692fn toml_assignment_key(line: &str) -> Option<&str> {
693 let (key, _) = line.split_once('=')?;
694 Some(key.trim())
695}
696
697fn update_package_manifest_role(
698 manifest: &Path,
699 expected_fleet: &str,
700 old_role: &str,
701 new_role: &str,
702) -> Result<Option<String>, Box<dyn std::error::Error>> {
703 if !manifest.is_file() {
704 return Ok(None);
705 }
706
707 let source = fs::read_to_string(manifest)?;
708 let metadata = toml::from_str::<TomlValue>(&source)?;
709 let Some(canic_metadata) = metadata
710 .get("package")
711 .and_then(TomlValue::as_table)
712 .and_then(|package| package.get("metadata"))
713 .and_then(TomlValue::as_table)
714 .and_then(|metadata| metadata.get("canic"))
715 .and_then(TomlValue::as_table)
716 else {
717 return Ok(None);
718 };
719 if canic_metadata.get("fleet").and_then(TomlValue::as_str) != Some(expected_fleet)
720 || canic_metadata.get("role").and_then(TomlValue::as_str) != Some(old_role)
721 {
722 return Ok(None);
723 }
724
725 Ok(Some(rename_package_metadata_role_source(
726 &source, old_role, new_role,
727 )))
728}
729
730fn rename_package_metadata_role_source(source: &str, old_role: &str, new_role: &str) -> String {
731 let mut in_canic_metadata = false;
732 let old_literal = toml_string_literal(old_role);
733 let new_literal = toml_string_literal(new_role);
734 let mut lines = Vec::new();
735
736 for line in source.lines() {
737 let trimmed = line.trim();
738 if trimmed.starts_with('[') && trimmed.ends_with(']') {
739 in_canic_metadata = trimmed == "[package.metadata.canic]";
740 }
741 if in_canic_metadata && toml_assignment_key(line.trim_start()) == Some("role") {
742 lines.push(line.replace(&old_literal, &new_literal));
743 } else {
744 lines.push(line.to_string());
745 }
746 }
747
748 let mut result = lines.join("\n");
749 if source.ends_with('\n') {
750 result.push('\n');
751 }
752 result
753}
754
755fn validate_role_name(role: &str) -> Result<(), Box<dyn std::error::Error>> {
756 if role.is_empty() {
757 return Err("role must not be empty".into());
758 }
759 if !role
760 .bytes()
761 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
762 {
763 return Err("role must contain only ASCII letters, numbers, '_' or '-'".into());
764 }
765 Ok(())
766}
767
768fn validate_subnet_name(subnet: &str) -> Result<(), Box<dyn std::error::Error>> {
769 if subnet.is_empty() {
770 return Err("subnet must not be empty".into());
771 }
772 if !subnet
773 .bytes()
774 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
775 {
776 return Err("subnet must contain only ASCII letters, numbers, '_' or '-'".into());
777 }
778 Ok(())
779}
780
781fn validate_attach_kind(kind: &str) -> Result<(), Box<dyn std::error::Error>> {
782 if matches!(kind, "singleton" | "shard" | "replica" | "instance") {
783 return Ok(());
784 }
785
786 Err("kind must be one of: singleton, shard, replica, instance".into())
787}
788
789fn toml_string_literal(value: &str) -> String {
790 let mut escaped = String::from("\"");
791 for ch in value.chars() {
792 match ch {
793 '\\' => escaped.push_str("\\\\"),
794 '"' => escaped.push_str("\\\""),
795 '\n' => escaped.push_str("\\n"),
796 '\r' => escaped.push_str("\\r"),
797 '\t' => escaped.push_str("\\t"),
798 ch => escaped.push(ch),
799 }
800 }
801 escaped.push('"');
802 escaped
803}
804
805pub(super) fn configured_role_capabilities_from_source(
807 config_source: &str,
808) -> Result<BTreeMap<String, Vec<String>>, Box<dyn std::error::Error>> {
809 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
810 let mut capabilities = BTreeMap::<String, BTreeSet<String>>::new();
811
812 for subnet in config.subnets.values() {
813 for (role, canister) in &subnet.canisters {
814 let mut role_capabilities = BTreeSet::new();
815 if canister.auth.delegated_token_signer || canister.auth.role_attestation_cache {
816 role_capabilities.insert("auth".to_string());
817 }
818 if canister.sharding.is_some() {
819 role_capabilities.insert("sharding".to_string());
820 }
821 if canister.scaling.is_some() {
822 role_capabilities.insert("scaling".to_string());
823 }
824 if canister.directory.is_some() {
825 role_capabilities.insert("directory".to_string());
826 }
827 if canister.standards.icrc21 {
828 role_capabilities.insert("icrc21".to_string());
829 }
830 if !role_capabilities.is_empty() {
831 capabilities
832 .entry(role.as_str().to_string())
833 .or_default()
834 .extend(role_capabilities);
835 }
836 }
837 }
838
839 Ok(capabilities
840 .into_iter()
841 .map(|(role, capabilities)| (role, capabilities.into_iter().collect()))
842 .collect())
843}
844
845pub(super) fn configured_role_auto_create_from_source(
847 config_source: &str,
848) -> Result<BTreeSet<String>, Box<dyn std::error::Error>> {
849 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
850 let mut auto_create = BTreeSet::<String>::new();
851
852 for subnet in config.subnets.values() {
853 auto_create.extend(
854 subnet
855 .auto_create_roles()
856 .iter()
857 .map(|role| role.as_str().to_string()),
858 );
859 }
860
861 Ok(auto_create)
862}
863
864pub(super) fn configured_role_topups_from_source(
866 config_source: &str,
867) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
868 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
869 let mut topups = BTreeMap::<String, String>::new();
870
871 for subnet in config.subnets.values() {
872 for (role, canister) in &subnet.canisters {
873 if let Some(policy) = &canister.topup {
874 topups.insert(
875 role.as_str().to_string(),
876 format!(
877 "{} @ {}",
878 cycles_tc(policy.amount.to_u128()),
879 cycles_tc(policy.threshold.to_u128())
880 ),
881 );
882 }
883 }
884 }
885
886 Ok(topups)
887}
888
889pub(super) fn configured_role_metrics_profiles_from_source(
891 config_source: &str,
892) -> Result<BTreeMap<String, String>, Box<dyn std::error::Error>> {
893 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
894 let mut profiles = BTreeMap::<String, String>::new();
895
896 for subnet in config.subnets.values() {
897 for (role, canister) in &subnet.canisters {
898 let role_name = role.as_str().to_string();
899 let profile = metrics_profile_label(canister.resolved_metrics_profile(role));
900 match profiles.get(&role_name) {
901 Some(existing) if existing != profile => {
902 profiles.insert(role_name, "mixed".to_string());
903 }
904 Some(_) => {}
905 None => {
906 profiles.insert(role_name, profile.to_string());
907 }
908 }
909 }
910 }
911
912 Ok(profiles)
913}
914
915pub(super) fn configured_local_root_create_cycles_from_source(
917 config_source: &str,
918) -> Result<u128, Box<dyn std::error::Error>> {
919 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
920 let mut root_subnet = None;
921
922 for (subnet_role, subnet) in &config.subnets {
923 if !subnet.canisters.keys().any(CanisterRole::is_root) {
924 continue;
925 }
926 if root_subnet.is_some() {
927 return Err(format!(
928 "multiple subnets define a root canister; expected exactly one root subnet (found at least '{subnet_role}')"
929 )
930 .into());
931 }
932 root_subnet = Some(subnet);
933 }
934
935 let subnet = root_subnet.ok_or_else(|| {
936 "no subnet defines a root canister; expected exactly one root subnet".to_string()
937 })?;
938
939 let mut cycles = subnet
940 .get_canister(&CanisterRole::WASM_STORE)
941 .map_or(DEFAULT_INITIAL_CYCLES, |cfg| cfg.initial_cycles.to_u128());
942 for role in subnet.auto_create_roles() {
943 if let Some(cfg) = subnet.get_canister(&role) {
944 cycles = cycles.saturating_add(cfg.initial_cycles.to_u128());
945 }
946 }
947 cycles = cycles.saturating_add(
948 u128::from(subnet.pool.minimum_size).saturating_mul(DEFAULT_INITIAL_CYCLES),
949 );
950
951 Ok(cycles.saturating_add(LOCAL_ROOT_MIN_READY_CYCLES))
952}
953
954pub(super) fn configured_role_details_from_source(
956 config_source: &str,
957) -> Result<BTreeMap<String, Vec<String>>, Box<dyn std::error::Error>> {
958 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
959 let mut details = BTreeMap::<String, BTreeSet<String>>::new();
960
961 for role in &config.app_index {
962 details
963 .entry(role.as_str().to_string())
964 .or_default()
965 .insert("app_index".to_string());
966 }
967
968 for subnet in config.subnets.values() {
969 for role in subnet.auto_create_roles() {
970 details
971 .entry(role.as_str().to_string())
972 .or_default()
973 .insert("auto_create".to_string());
974 }
975 for role in subnet.subnet_index_roles() {
976 details
977 .entry(role.as_str().to_string())
978 .or_default()
979 .insert("subnet_index".to_string());
980 }
981
982 for (role, canister) in &subnet.canisters {
983 let role_details = details.entry(role.as_str().to_string()).or_default();
984 let profile = canister.resolved_metrics_profile(role);
985 let profile_source = if canister.metrics.profile.is_some() {
986 "configured"
987 } else {
988 "inferred"
989 };
990 role_details.insert(format!(
991 "metrics profile={} tiers={} ({profile_source})",
992 metrics_profile_label(profile),
993 metrics_profile_tiers_label(profile)
994 ));
995 if canister.initial_cycles.to_u128() != DEFAULT_INITIAL_CYCLES {
996 role_details.insert(format!("initial_cycles={}", canister.initial_cycles));
997 }
998 if !canister.randomness.enabled {
999 role_details.insert("randomness=off".to_string());
1000 } else if randomness_source_label(canister.randomness.source) != "ic"
1001 || canister.randomness.reseed_interval_secs
1002 != DEFAULT_RANDOMNESS_RESEED_INTERVAL_SECS
1003 {
1004 role_details.insert(format!(
1005 "randomness={} reseed={}s",
1006 randomness_source_label(canister.randomness.source),
1007 canister.randomness.reseed_interval_secs
1008 ));
1009 }
1010 if canister.auth.delegated_token_signer {
1011 role_details.insert("auth delegated-token-signer".to_string());
1012 }
1013 if canister.auth.role_attestation_cache {
1014 role_details.insert("auth role-attestation-cache".to_string());
1015 }
1016 if canister.standards.icrc21 {
1017 role_details.insert("standard icrc21".to_string());
1018 }
1019 if let Some(scaling) = &canister.scaling {
1020 for (pool_name, pool) in &scaling.pools {
1021 role_details.insert(format!(
1022 "scaling {pool_name}->{} initial={} min={} max={}",
1023 pool.canister_role.as_str(),
1024 pool.policy.initial_workers,
1025 pool.policy.min_workers,
1026 pool.policy.max_workers
1027 ));
1028 }
1029 }
1030 if let Some(sharding) = &canister.sharding {
1031 for (pool_name, pool) in &sharding.pools {
1032 role_details.insert(format!(
1033 "sharding {pool_name}->{} cap={} initial={} max={}",
1034 pool.canister_role.as_str(),
1035 pool.policy.capacity,
1036 pool.policy.initial_shards,
1037 pool.policy.max_shards
1038 ));
1039 }
1040 }
1041 if let Some(directory) = &canister.directory {
1042 for (pool_name, pool) in &directory.pools {
1043 role_details.insert(format!(
1044 "directory {pool_name}->{} key={}",
1045 pool.canister_role.as_str(),
1046 pool.key_name
1047 ));
1048 }
1049 }
1050 }
1051 }
1052
1053 Ok(details
1054 .into_iter()
1055 .filter(|(_, details)| !details.is_empty())
1056 .map(|(role, details)| (role, details.into_iter().collect()))
1057 .collect())
1058}
1059
1060fn randomness_source_label(source: impl std::fmt::Debug) -> String {
1061 format!("{source:?}").to_ascii_lowercase()
1062}
1063
1064const fn metrics_profile_label(profile: MetricsProfile) -> &'static str {
1065 match profile {
1066 MetricsProfile::Leaf => "leaf",
1067 MetricsProfile::Hub => "hub",
1068 MetricsProfile::Storage => "storage",
1069 MetricsProfile::Root => "root",
1070 MetricsProfile::Full => "full",
1071 }
1072}
1073
1074const fn metrics_profile_tiers_label(profile: MetricsProfile) -> &'static str {
1075 match profile {
1076 MetricsProfile::Leaf => "core,runtime,security",
1077 MetricsProfile::Hub => "core,placement,runtime,security",
1078 MetricsProfile::Storage => "core,runtime,storage",
1079 MetricsProfile::Root | MetricsProfile::Full => {
1080 "core,placement,platform,runtime,security,storage"
1081 }
1082 }
1083}
1084
1085pub(super) fn configured_fleet_name_from_source(
1087 config_source: &str,
1088) -> Result<String, Box<dyn std::error::Error>> {
1089 let config = toml::from_str::<TomlValue>(config_source)?;
1090 let name = config
1091 .get("fleet")
1092 .and_then(TomlValue::as_table)
1093 .and_then(|fleet| fleet.get("name"))
1094 .and_then(TomlValue::as_str)
1095 .ok_or_else(|| "missing required [fleet].name in canic.toml".to_string())?;
1096 Ok(name.to_string())
1097}
1098
1099pub(super) fn configured_controllers_from_source(
1101 config_source: &str,
1102) -> Result<Vec<String>, Box<dyn std::error::Error>> {
1103 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
1104 let mut controllers = config
1105 .controllers
1106 .iter()
1107 .map(canic_core::cdk::types::Principal::to_text)
1108 .collect::<Vec<_>>();
1109 controllers.sort();
1110 controllers.dedup();
1111 Ok(controllers)
1112}
1113
1114pub(super) fn configured_pool_expectations_from_source(
1116 config_source: &str,
1117) -> Result<Vec<ConfiguredPoolExpectation>, Box<dyn std::error::Error>> {
1118 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
1119 let mut root_subnet = None;
1120
1121 for (subnet_role, subnet) in &config.subnets {
1122 if !subnet.canisters.keys().any(CanisterRole::is_root) {
1123 continue;
1124 }
1125
1126 if root_subnet.is_some() {
1127 return Err(format!(
1128 "multiple subnets define a root canister; expected exactly one root subnet (found at least '{subnet_role}')"
1129 )
1130 .into());
1131 }
1132
1133 root_subnet = Some(subnet);
1134 }
1135
1136 let subnet = root_subnet.ok_or_else(|| {
1137 "no subnet defines a root canister; expected exactly one root subnet".to_string()
1138 })?;
1139 let mut pools = BTreeMap::<String, ConfiguredPoolExpectation>::new();
1140
1141 for canister in subnet.canisters.values() {
1142 if let Some(scaling) = &canister.scaling {
1143 for (pool_name, pool) in &scaling.pools {
1144 pools.insert(
1145 format!("scaling:{pool_name}:{}", pool.canister_role.as_str()),
1146 ConfiguredPoolExpectation {
1147 pool: pool_name.clone(),
1148 canister_role: pool.canister_role.as_str().to_string(),
1149 },
1150 );
1151 }
1152 }
1153 if let Some(sharding) = &canister.sharding {
1154 for (pool_name, pool) in &sharding.pools {
1155 pools.insert(
1156 format!("sharding:{pool_name}:{}", pool.canister_role.as_str()),
1157 ConfiguredPoolExpectation {
1158 pool: pool_name.clone(),
1159 canister_role: pool.canister_role.as_str().to_string(),
1160 },
1161 );
1162 }
1163 }
1164 if let Some(directory) = &canister.directory {
1165 for (pool_name, pool) in &directory.pools {
1166 pools.insert(
1167 format!("directory:{pool_name}:{}", pool.canister_role.as_str()),
1168 ConfiguredPoolExpectation {
1169 pool: pool_name.clone(),
1170 canister_role: pool.canister_role.as_str().to_string(),
1171 },
1172 );
1173 }
1174 }
1175 }
1176
1177 Ok(pools.into_values().collect())
1178}
1179
1180pub(super) fn configured_release_roles_from_source(
1182 config_source: &str,
1183) -> Result<Vec<String>, Box<dyn std::error::Error>> {
1184 configured_root_subnet_roles_from_source(config_source, RootSubnetRoleScope::Release)
1185}
1186
1187pub(super) fn configured_deployable_roles_from_source(
1190 config_source: &str,
1191) -> Result<Vec<String>, Box<dyn std::error::Error>> {
1192 configured_root_subnet_roles_from_source(config_source, RootSubnetRoleScope::Deployable)
1193}
1194
1195pub(super) fn configured_bootstrap_roles_from_source(
1197 config_source: &str,
1198) -> Result<Vec<String>, Box<dyn std::error::Error>> {
1199 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
1200 let mut root_subnet = None;
1201
1202 for (subnet_role, subnet) in &config.subnets {
1203 if !subnet.canisters.keys().any(CanisterRole::is_root) {
1204 continue;
1205 }
1206
1207 if root_subnet.is_some() {
1208 return Err(format!(
1209 "multiple subnets define a root canister; expected exactly one root subnet (found at least '{subnet_role}')"
1210 )
1211 .into());
1212 }
1213
1214 root_subnet = Some(subnet);
1215 }
1216
1217 let subnet = root_subnet.ok_or_else(|| {
1218 "no subnet defines a root canister; expected exactly one root subnet".to_string()
1219 })?;
1220
1221 let mut roles = BTreeSet::<String>::new();
1222 roles.insert(CanisterRole::ROOT.as_str().to_string());
1223 roles.extend(
1224 subnet
1225 .auto_create_roles()
1226 .iter()
1227 .map(|role| role.as_str().to_string()),
1228 );
1229
1230 for role in subnet.auto_create_roles() {
1231 let Some(canister) = subnet.get_canister(&role) else {
1232 continue;
1233 };
1234
1235 if let Some(sharding) = &canister.sharding {
1236 for pool in sharding.pools.values() {
1237 if pool.policy.initial_shards > 0 {
1238 roles.insert(pool.canister_role.as_str().to_string());
1239 }
1240 }
1241 }
1242
1243 if let Some(scaling) = &canister.scaling {
1244 for pool in scaling.pools.values() {
1245 if pool.policy.initial_workers > 0 {
1246 roles.insert(pool.canister_role.as_str().to_string());
1247 }
1248 }
1249 }
1250 }
1251
1252 Ok(sort_root_subnet_roles(roles.into_iter().collect()))
1253}
1254
1255fn configured_root_subnet_roles_from_source(
1257 config_source: &str,
1258 scope: RootSubnetRoleScope,
1259) -> Result<Vec<String>, Box<dyn std::error::Error>> {
1260 let config = parse_config_model(config_source).map_err(|err| err.to_string())?;
1261 let mut root_subnet_roles = None;
1262
1263 for (subnet_role, subnet) in &config.subnets {
1264 if !subnet.canisters.keys().any(CanisterRole::is_root) {
1265 continue;
1266 }
1267
1268 if root_subnet_roles.is_some() {
1269 return Err(format!(
1270 "multiple subnets define a root canister; expected exactly one root subnet (found at least '{subnet_role}')"
1271 )
1272 .into());
1273 }
1274
1275 root_subnet_roles = Some(
1276 subnet
1277 .canisters
1278 .keys()
1279 .filter(|role| !role.is_wasm_store())
1280 .filter(|role| scope.includes_root() || !role.is_root())
1281 .map(|role| role.as_str().to_string())
1282 .collect::<Vec<_>>(),
1283 );
1284 }
1285
1286 let root_subnet_roles = root_subnet_roles.ok_or_else(|| {
1287 "no subnet defines a root canister; expected exactly one root subnet".to_string()
1288 })?;
1289
1290 Ok(sort_root_subnet_roles(root_subnet_roles))
1291}
1292
1293fn sort_root_subnet_roles(mut roles: Vec<String>) -> Vec<String> {
1295 roles.sort_by(|left, right| {
1296 match (
1297 left == CanisterRole::ROOT.as_str(),
1298 right == CanisterRole::ROOT.as_str(),
1299 ) {
1300 (true, false) => std::cmp::Ordering::Less,
1301 (false, true) => std::cmp::Ordering::Greater,
1302 _ => left.cmp(right),
1303 }
1304 });
1305 roles
1306}