1use crate::error::{ErrorData, Result};
11use crate::instance_catalog::{find_instance_type, is_same_architecture_machine, Architecture};
12use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef};
13use crate::{PermissionProfile, Platform, ResourceType};
14use alien_error::AlienError;
15use bon::Builder;
16use serde::{Deserialize, Serialize};
17use std::any::Any;
18use std::collections::BTreeMap;
19use std::fmt::Debug;
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
24#[serde(rename_all = "camelCase")]
25pub struct GpuSpec {
26 #[serde(rename = "type")]
28 pub gpu_type: String,
29 pub count: u32,
31}
32
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
40#[serde(rename_all = "camelCase")]
41pub struct MachineProfile {
42 pub cpu: String,
45 pub memory_bytes: u64,
47 pub ephemeral_storage_bytes: u64,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 pub architecture: Option<Architecture>,
52 #[serde(skip_serializing_if = "Option::is_none")]
54 pub gpu: Option<GpuSpec>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub data_disk: Option<DataDiskRequirement>,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
67#[serde(rename_all = "camelCase")]
68pub struct DataDiskRequirement {
69 pub size_bytes: u64,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
76#[serde(rename_all = "camelCase")]
77pub struct ComputeChoiceRange {
78 pub min: u32,
80 pub max: u32,
82 pub default: u32,
84}
85
86impl ComputeChoiceRange {
87 pub fn contains(&self, value: u32) -> bool {
89 self.min <= value && value <= self.max
90 }
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
96#[serde(rename_all = "camelCase", tag = "type")]
97pub enum CapacityGroupScalePolicy {
98 Fixed {
100 machines: ComputeChoiceRange,
102 },
103 Autoscale {
105 min: ComputeChoiceRange,
107 max: ComputeChoiceRange,
109 },
110}
111
112impl CapacityGroupScalePolicy {
113 pub fn from_selected_bounds(min_size: u32, max_size: u32) -> Self {
115 if min_size == max_size {
116 Self::Fixed {
117 machines: ComputeChoiceRange {
118 min: min_size,
119 max: max_size,
120 default: min_size,
121 },
122 }
123 } else {
124 Self::Autoscale {
125 min: ComputeChoiceRange {
126 min: min_size,
127 max: min_size,
128 default: min_size,
129 },
130 max: ComputeChoiceRange {
131 min: max_size,
132 max: max_size,
133 default: max_size,
134 },
135 }
136 }
137 }
138
139 pub fn default_min_size(&self) -> u32 {
141 match self {
142 Self::Fixed { machines } => machines.default,
143 Self::Autoscale { min, .. } => min.default,
144 }
145 }
146
147 pub fn default_max_size(&self) -> u32 {
149 match self {
150 Self::Fixed { machines } => machines.default,
151 Self::Autoscale { max, .. } => max.default,
152 }
153 }
154}
155
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
163#[serde(rename_all = "camelCase")]
164pub struct CapacityGroup {
165 pub group_id: String,
167 #[serde(skip_serializing_if = "Option::is_none")]
171 pub instance_type: Option<String>,
172 #[serde(skip_serializing_if = "Option::is_none")]
174 pub profile: Option<MachineProfile>,
175 pub min_size: u32,
177 pub max_size: u32,
179 #[serde(skip_serializing_if = "Option::is_none")]
184 pub scale_policy: Option<CapacityGroupScalePolicy>,
185 #[serde(skip_serializing_if = "Option::is_none")]
191 pub nested_virtualization: Option<bool>,
192 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub data_disk_gib_range: Option<ComputeChoiceRange>,
198}
199
200impl CapacityGroup {
201 pub fn aws_root_volume_size_gib(&self) -> i32 {
203 self.aws_filesystem_size_gib()
204 .saturating_add(12)
205 .max(20)
206 .min(i32::MAX as u64) as i32
207 }
208
209 pub fn aws_runtime_data_volume_size_gib(&self) -> Option<i32> {
213 if let Some(size_gib) = self.data_disk_size_gib() {
214 return Some(size_gib.min(i32::MAX as u64) as i32);
215 }
216 (self.nested_virtualization == Some(true))
217 .then(|| self.aws_filesystem_size_gib().max(20).min(i32::MAX as u64) as i32)
218 }
219
220 pub fn aws_nested_virtualization(&self, instance_type: &str) -> Option<&'static str> {
227 let bare_metal = find_instance_type(Platform::Aws, instance_type)
228 .is_some_and(|spec| spec.bare_metal);
229 if bare_metal {
230 Some("disabled")
231 } else if self.nested_virtualization == Some(true) {
232 Some("enabled")
233 } else {
234 None
235 }
236 }
237
238 pub fn disks_differ(&self, other: &CapacityGroup) -> bool {
241 let disks = |group: &CapacityGroup| {
242 group
243 .profile
244 .as_ref()
245 .map(|profile| (profile.ephemeral_storage_bytes, profile.data_disk.clone()))
246 };
247 disks(self) != disks(other)
248 }
249
250 pub fn data_disk_choices(&self) -> Option<ComputeChoiceRange> {
253 if let Some(range) = &self.data_disk_gib_range {
254 return Some(range.clone());
255 }
256 let size_gib = u32::try_from(self.data_disk_size_gib()?).unwrap_or(u32::MAX);
257 Some(ComputeChoiceRange {
258 min: size_gib,
259 max: size_gib,
260 default: size_gib,
261 })
262 }
263
264 pub fn effective_data_disk_gib(
267 &self,
268 selected: Option<u32>,
269 ) -> std::result::Result<Option<u32>, String> {
270 let Some(choices) = self.data_disk_choices() else {
271 return match selected {
272 None | Some(0) => Ok(None),
273 Some(size) => Err(format!(
274 "pool '{}' declares no data disk, so dataDiskGib {size} cannot be chosen",
275 self.group_id
276 )),
277 };
278 };
279 let size = selected.unwrap_or(choices.default);
280 if !choices.contains(size) {
281 return Err(if choices.min == choices.max {
282 format!(
283 "pool '{}' has a fixed {} GiB data disk; dataDiskGib {size} cannot be chosen",
284 self.group_id, choices.min
285 )
286 } else {
287 format!(
288 "pool '{}' data disk must be between {} and {} GiB; dataDiskGib {size} is outside that range",
289 self.group_id, choices.min, choices.max
290 )
291 });
292 }
293 Ok(Some(size))
294 }
295
296 pub fn selected_data_disk(
299 &self,
300 selected: Option<u32>,
301 ) -> std::result::Result<Option<DataDiskRequirement>, String> {
302 let size_gib = self.effective_data_disk_gib(selected)?;
303 if self.data_disk_gib_range.is_none() {
304 return Ok(self
307 .profile
308 .as_ref()
309 .and_then(|profile| profile.data_disk.clone()));
310 }
311 Ok(size_gib
312 .filter(|size_gib| *size_gib > 0)
313 .map(|size_gib| DataDiskRequirement {
314 size_bytes: u64::from(size_gib) * 1024 * 1024 * 1024,
315 }))
316 }
317
318 pub fn data_disk_size_gib(&self) -> Option<u64> {
320 let data_disk = self.profile.as_ref()?.data_disk.as_ref()?;
321 Some(data_disk.size_bytes.div_ceil(1024 * 1024 * 1024))
322 }
323
324 fn aws_filesystem_size_gib(&self) -> u64 {
325 self.profile
326 .as_ref()
327 .map_or(0, |profile| profile.ephemeral_storage_bytes)
328 .div_ceil(1024 * 1024 * 1024)
329 .saturating_mul(5)
330 .div_ceil(4)
331 }
332}
333
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
373#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
374#[serde(rename_all = "camelCase", deny_unknown_fields)]
375#[builder(start_fn = new)]
376pub struct ComputeCluster {
377 #[builder(start_fn)]
380 pub id: String,
381
382 #[builder(field)]
385 pub capacity_groups: Vec<CapacityGroup>,
386
387 #[serde(default, skip_serializing_if = "Option::is_none")]
390 pub node_permissions: Option<PermissionProfile>,
391
392 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub node_permissions_platforms: Option<Vec<Platform>>,
395
396 #[serde(default, skip_serializing_if = "Option::is_none")]
399 pub dynamic_container_pool: Option<String>,
400
401 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
404 #[builder(default)]
405 pub selected_failure_domains: BTreeMap<String, Vec<String>>,
406
407 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
410 #[builder(default)]
411 pub failure_domain_spread: BTreeMap<String, u8>,
412
413 #[serde(skip_serializing_if = "Option::is_none")]
417 pub container_cidr: Option<String>,
418}
419
420impl ComputeCluster {
421 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("compute-cluster");
423
424 pub fn id(&self) -> &str {
426 &self.id
427 }
428
429 pub fn container_cidr(&self) -> &str {
431 self.container_cidr.as_deref().unwrap_or("10.244.0.0/16")
432 }
433}
434
435impl<S: compute_cluster_builder::State> ComputeClusterBuilder<S> {
436 pub fn capacity_group(mut self, group: CapacityGroup) -> Self {
438 self.capacity_groups.push(group);
439 self
440 }
441}
442
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
445#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
446#[serde(rename_all = "camelCase")]
447pub struct CapacityGroupStatus {
448 pub group_id: String,
450 pub current_machines: u32,
452 pub desired_machines: u32,
454 pub instance_type: String,
456}
457
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
460#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
461#[serde(rename_all = "camelCase")]
462pub struct ComputeClusterOutputs {
463 pub cluster_id: String,
465 pub horizon_ready: bool,
467 pub capacity_group_statuses: Vec<CapacityGroupStatus>,
469 pub total_machines: u32,
471}
472
473impl ResourceOutputsDefinition for ComputeClusterOutputs {
474 fn get_resource_type(&self) -> ResourceType {
475 ComputeCluster::RESOURCE_TYPE.clone()
476 }
477
478 fn as_any(&self) -> &dyn Any {
479 self
480 }
481
482 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
483 Box::new(self.clone())
484 }
485
486 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
487 other.as_any().downcast_ref::<ComputeClusterOutputs>() == Some(self)
488 }
489
490 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
491 serde_json::to_value(self)
492 }
493}
494
495impl ResourceDefinition for ComputeCluster {
496 fn get_resource_type(&self) -> ResourceType {
497 Self::RESOURCE_TYPE
498 }
499
500 fn id(&self) -> &str {
501 &self.id
502 }
503
504 fn replace_after_failed_create_is_safe(&self) -> bool {
505 false
508 }
509
510 fn get_dependencies(&self) -> Vec<ResourceRef> {
511 Vec::new()
517 }
518
519 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
520 let new_cluster = new_config
521 .as_any()
522 .downcast_ref::<ComputeCluster>()
523 .ok_or_else(|| {
524 AlienError::new(ErrorData::UnexpectedResourceType {
525 resource_id: self.id.clone(),
526 expected: Self::RESOURCE_TYPE,
527 actual: new_config.get_resource_type(),
528 })
529 })?;
530
531 if self.id != new_cluster.id {
532 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
533 resource_id: self.id.clone(),
534 reason: "the 'id' field is immutable".to_string(),
535 }));
536 }
537
538 if self.container_cidr.is_some()
540 && new_cluster.container_cidr.is_some()
541 && self.container_cidr != new_cluster.container_cidr
542 {
543 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
544 resource_id: self.id.clone(),
545 reason: "the 'containerCidr' field is immutable once set".to_string(),
546 }));
547 }
548
549 for new_group in &new_cluster.capacity_groups {
551 if let Some(existing_group) = self
552 .capacity_groups
553 .iter()
554 .find(|g| g.group_id == new_group.group_id)
555 {
556 if let (Some(old), Some(new)) = (
560 existing_group.instance_type.as_deref(),
561 new_group.instance_type.as_deref(),
562 ) {
563 if old != new
564 && ![Platform::Aws, Platform::Gcp, Platform::Azure]
565 .into_iter()
566 .any(|platform| is_same_architecture_machine(platform, old, new))
567 {
568 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
569 resource_id: self.id.clone(),
570 reason: format!(
571 "capacity group '{}' can't change machine from '{old}' to '{new}': only a catalog machine in the same cloud and of the same CPU architecture can replace it",
572 new_group.group_id
573 ),
574 }));
575 }
576 }
577 }
578 }
579
580 Ok(())
581 }
582
583 fn as_any(&self) -> &dyn Any {
584 self
585 }
586
587 fn as_any_mut(&mut self) -> &mut dyn Any {
588 self
589 }
590
591 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
592 Box::new(self.clone())
593 }
594
595 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
596 other.as_any().downcast_ref::<ComputeCluster>() == Some(self)
597 }
598
599 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
600 serde_json::to_value(self)
601 }
602}
603
604#[cfg(test)]
605mod tests {
606 use super::*;
607
608 #[test]
609 fn aws_nested_virtualization_follows_the_machine() {
610 let group = |nested: Option<bool>| CapacityGroup {
611 group_id: "general".into(),
612 instance_type: None,
613 profile: None,
614 min_size: 1,
615 max_size: 1,
616 scale_policy: None,
617 nested_virtualization: nested,
618 data_disk_gib_range: None,
619 };
620 for (instance_type, nested, expected) in [
621 ("c8id.4xlarge", Some(true), Some("enabled")),
622 ("c8id.4xlarge", None, None),
623 ("m7g.large", Some(false), None),
624 ("c8id.metal-48xl", Some(true), Some("disabled")),
625 ("m8id.metal-96xl", None, Some("disabled")),
626 ("c5.metal", Some(true), Some("disabled")),
627 ] {
628 assert_eq!(
629 group(nested).aws_nested_virtualization(instance_type),
630 expected,
631 "{instance_type} nested={nested:?}"
632 );
633 }
634 }
635
636 #[test]
637 fn aws_disk_sizing_preserves_rounding_minimums_and_saturation() {
638 let gib = 1024 * 1024 * 1024;
639 for (bytes, root, data) in [
640 (0, 20, 20),
641 (gib, 20, 20),
642 (20 * gib, 37, 25),
643 (20 * gib + 1, 39, 27),
644 (u64::MAX, i32::MAX, i32::MAX),
645 ] {
646 let mut group = CapacityGroup {
647 group_id: "general".into(),
648 instance_type: None,
649 profile: Some(MachineProfile {
650 cpu: "4.0".into(),
651 memory_bytes: 8 * gib,
652 ephemeral_storage_bytes: bytes,
653 architecture: None,
654 gpu: None,
655 data_disk: None,
656 }),
657 min_size: 1,
658 max_size: 1,
659 scale_policy: None,
660 nested_virtualization: None,
661 data_disk_gib_range: None,
662 };
663 assert_eq!(group.aws_root_volume_size_gib(), root);
664 assert_eq!(group.aws_runtime_data_volume_size_gib(), None);
665 group.nested_virtualization = Some(true);
666 assert_eq!(group.aws_root_volume_size_gib(), root);
667 assert_eq!(group.aws_runtime_data_volume_size_gib(), Some(data));
668 }
669 }
670
671 #[test]
674 fn a_fixed_data_disk_keeps_its_declared_bytes() {
675 let gib: u64 = 1024 * 1024 * 1024;
676 let declared = DataDiskRequirement {
677 size_bytes: 500_000_000_000,
678 };
679 let mut group = CapacityGroup {
680 group_id: "general".into(),
681 instance_type: None,
682 profile: Some(MachineProfile {
683 cpu: "4.0".into(),
684 memory_bytes: 8 * gib,
685 ephemeral_storage_bytes: 20 * gib,
686 architecture: None,
687 gpu: None,
688 data_disk: Some(declared.clone()),
689 }),
690 min_size: 1,
691 max_size: 1,
692 scale_policy: None,
693 nested_virtualization: None,
694 data_disk_gib_range: None,
695 };
696 assert_eq!(group.selected_data_disk(None), Ok(Some(declared.clone())));
698 assert_eq!(group.selected_data_disk(Some(466)), Ok(Some(declared)));
699 assert!(group.selected_data_disk(Some(500)).is_err());
700
701 group.data_disk_gib_range = Some(ComputeChoiceRange {
702 min: 0,
703 max: 1024,
704 default: 466,
705 });
706 assert_eq!(
707 group.selected_data_disk(None),
708 Ok(Some(DataDiskRequirement {
709 size_bytes: 466 * gib
710 }))
711 );
712 assert_eq!(group.selected_data_disk(Some(0)), Ok(None));
713 }
714
715 #[test]
716 fn declared_data_disk_replaces_the_nested_virtualization_volume() {
717 let gib = 1024 * 1024 * 1024;
718 let group = |nested: Option<bool>, data_disk_bytes: u64| CapacityGroup {
719 group_id: "general".into(),
720 instance_type: None,
721 profile: Some(MachineProfile {
722 cpu: "4.0".into(),
723 memory_bytes: 8 * gib,
724 ephemeral_storage_bytes: 20 * gib,
725 architecture: None,
726 gpu: None,
727 data_disk: Some(DataDiskRequirement {
728 size_bytes: data_disk_bytes,
729 }),
730 }),
731 min_size: 1,
732 max_size: 1,
733 scale_policy: None,
734 nested_virtualization: nested,
735 data_disk_gib_range: None,
736 };
737 for nested in [None, Some(false), Some(true)] {
738 assert_eq!(group(nested, 30 * gib).aws_root_volume_size_gib(), 37);
741 assert_eq!(
742 group(nested, 30 * gib).aws_runtime_data_volume_size_gib(),
743 Some(30)
744 );
745 assert_eq!(
746 group(nested, 30 * gib + 1).aws_runtime_data_volume_size_gib(),
747 Some(31)
748 );
749 }
750 assert_eq!(group(None, 512 * 1024 * 1024).data_disk_size_gib(), Some(1));
751 }
752
753 #[test]
754 fn test_compute_cluster_creation() {
755 let cluster = ComputeCluster::new("compute".to_string())
756 .capacity_group(CapacityGroup {
757 group_id: "general".to_string(),
758 instance_type: Some("m7g.xlarge".to_string()),
759 profile: None,
760 min_size: 1,
761 max_size: 5,
762 scale_policy: None,
763 nested_virtualization: None,
764 data_disk_gib_range: None,
765 })
766 .build();
767
768 assert_eq!(cluster.id(), "compute");
769 assert_eq!(cluster.capacity_groups.len(), 1);
770 assert_eq!(cluster.capacity_groups[0].group_id, "general");
771 assert_eq!(cluster.container_cidr(), "10.244.0.0/16");
772 }
773
774 #[test]
775 fn test_compute_cluster_multiple_capacity_groups() {
776 let cluster = ComputeCluster::new("multi-pool".to_string())
777 .capacity_group(CapacityGroup {
778 group_id: "general".to_string(),
779 instance_type: Some("m7g.xlarge".to_string()),
780 profile: None,
781 min_size: 1,
782 max_size: 3,
783 scale_policy: None,
784 nested_virtualization: None,
785 data_disk_gib_range: None,
786 })
787 .capacity_group(CapacityGroup {
788 group_id: "gpu".to_string(),
789 instance_type: Some("g5.xlarge".to_string()),
790 profile: Some(MachineProfile {
791 cpu: "4.0".to_string(),
792 memory_bytes: 17179869184, ephemeral_storage_bytes: 214748364800, architecture: None,
795 gpu: Some(GpuSpec {
796 gpu_type: "nvidia-a10g".to_string(),
797 count: 1,
798 }),
799 data_disk: None,
800 }),
801 min_size: 0,
802 max_size: 2,
803 scale_policy: None,
804 nested_virtualization: None,
805 data_disk_gib_range: None,
806 })
807 .build();
808
809 assert_eq!(cluster.capacity_groups.len(), 2);
810 assert_eq!(cluster.capacity_groups[0].group_id, "general");
811 assert_eq!(cluster.capacity_groups[1].group_id, "gpu");
812 assert!(cluster.capacity_groups[1]
813 .profile
814 .as_ref()
815 .unwrap()
816 .gpu
817 .is_some());
818 }
819
820 #[test]
821 fn test_compute_cluster_custom_cidr() {
822 let cluster = ComputeCluster::new("custom-net".to_string())
823 .container_cidr("172.30.0.0/16".to_string())
824 .capacity_group(CapacityGroup {
825 group_id: "general".to_string(),
826 instance_type: None,
827 profile: None,
828 min_size: 1,
829 max_size: 5,
830 scale_policy: None,
831 nested_virtualization: None,
832 data_disk_gib_range: None,
833 })
834 .build();
835
836 assert_eq!(cluster.container_cidr(), "172.30.0.0/16");
837 }
838
839 #[test]
840 fn test_compute_cluster_validate_update_immutable_id() {
841 let cluster1 = ComputeCluster::new("cluster-1".to_string())
842 .capacity_group(CapacityGroup {
843 group_id: "general".to_string(),
844 instance_type: None,
845 profile: None,
846 min_size: 1,
847 max_size: 5,
848 scale_policy: None,
849 nested_virtualization: None,
850 data_disk_gib_range: None,
851 })
852 .build();
853
854 let cluster2 = ComputeCluster::new("cluster-2".to_string())
855 .capacity_group(CapacityGroup {
856 group_id: "general".to_string(),
857 instance_type: None,
858 profile: None,
859 min_size: 1,
860 max_size: 5,
861 scale_policy: None,
862 nested_virtualization: None,
863 data_disk_gib_range: None,
864 })
865 .build();
866
867 let result = cluster1.validate_update(&cluster2);
868 assert!(result.is_err());
869 }
870
871 #[test]
872 fn test_compute_cluster_validate_update_scale_change() {
873 let cluster1 = ComputeCluster::new("compute".to_string())
874 .capacity_group(CapacityGroup {
875 group_id: "general".to_string(),
876 instance_type: Some("m7g.xlarge".to_string()),
877 profile: None,
878 min_size: 1,
879 max_size: 5,
880 scale_policy: None,
881 nested_virtualization: None,
882 data_disk_gib_range: None,
883 })
884 .build();
885
886 let cluster2 = ComputeCluster::new("compute".to_string())
887 .capacity_group(CapacityGroup {
888 group_id: "general".to_string(),
889 instance_type: Some("m7g.xlarge".to_string()),
890 profile: None,
891 min_size: 2,
892 max_size: 10,
893 scale_policy: None,
894 nested_virtualization: None,
895 data_disk_gib_range: None,
896 })
897 .build();
898
899 let result = cluster1.validate_update(&cluster2);
901 assert!(result.is_ok());
902 }
903
904 #[test]
905 fn machine_changes_stay_within_one_cloud_and_architecture() {
906 let cluster = |machine: &str| {
907 ComputeCluster::new("compute".to_string())
908 .capacity_group(CapacityGroup {
909 group_id: "general".to_string(),
910 instance_type: Some(machine.to_string()),
911 profile: None,
912 min_size: 1,
913 max_size: 5,
914 scale_policy: None,
915 nested_virtualization: None,
916 data_disk_gib_range: None,
917 })
918 .build()
919 };
920 for (old, new) in [
921 ("t4g.small", "t4g.medium"),
922 ("e2-medium", "n2-standard-4"),
923 ("Standard_D2s_v5", "Standard_D4s_v5"),
924 ] {
925 cluster(old)
926 .validate_update(&cluster(new))
927 .expect("same cloud and architecture");
928 }
929 for (old, new) in [
930 ("t4g.small", "m7i.large"),
931 ("t4g.small", "t4g.unknown"),
932 ("n2-standard-2", "m7i.large"),
933 ("Standard_D2s_v5", "n2-standard-4"),
934 ] {
935 let error = cluster(old)
936 .validate_update(&cluster(new))
937 .expect_err("needs setup");
938 assert_eq!(error.code, "INVALID_RESOURCE_UPDATE", "{old} -> {new}");
939 }
940 }
941
942 #[test]
943 fn node_permissions_are_inline_optional_and_roundtrip_exactly() {
944 let mut cluster = ComputeCluster::new("compute".to_string()).build();
945 let absent = serde_json::to_value(&cluster).unwrap();
946 assert!(absent.get("nodePermissions").is_none());
947 assert_eq!(
948 serde_json::from_value::<ComputeCluster>(absent).unwrap(),
949 cluster
950 );
951 cluster.node_permissions =
952 Some(PermissionProfile::new().resource("objects", ["storage/data-read"]));
953 let json = serde_json::to_value(&cluster).unwrap();
954 assert_eq!(
955 json["nodePermissions"],
956 serde_json::json!({"objects": ["storage/data-read"]})
957 );
958 assert_eq!(
959 serde_json::from_value::<ComputeCluster>(json).unwrap(),
960 cluster
961 );
962 assert_eq!(ResourceDefinition::get_permissions(&cluster), None);
963 }
964
965 #[test]
966 fn test_compute_cluster_serialization() {
967 let cluster = ComputeCluster::new("test-cluster".to_string())
968 .capacity_group(CapacityGroup {
969 group_id: "general".to_string(),
970 instance_type: Some("m7g.xlarge".to_string()),
971 profile: None,
972 min_size: 1,
973 max_size: 5,
974 scale_policy: None,
975 nested_virtualization: None,
976 data_disk_gib_range: None,
977 })
978 .build();
979
980 let json = serde_json::to_string(&cluster).unwrap();
981 let deserialized: ComputeCluster = serde_json::from_str(&json).unwrap();
982 assert_eq!(cluster, deserialized);
983 }
984}