1use crate::error::{ErrorData, Result};
15use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
16use crate::resources::{
17 ComputeCluster, PublicEndpoint, PublicEndpointOutput, ToolchainConfig, APEX_HOST_LABEL,
18};
19use alien_error::AlienError;
20use bon::Builder;
21use serde::{Deserialize, Serialize};
22use std::any::Any;
23use std::collections::HashMap;
24use std::fmt::Debug;
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
29#[serde(rename_all = "camelCase", tag = "type")]
30pub enum ContainerCode {
31 #[serde(rename_all = "camelCase")]
33 Image {
34 image: String,
36 },
37 #[serde(rename_all = "camelCase")]
39 Source {
40 src: String,
42 toolchain: ToolchainConfig,
44 },
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
50#[serde(rename_all = "camelCase")]
51pub struct ResourceSpec {
52 pub min: String,
54 pub desired: String,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
61#[serde(rename_all = "camelCase", deny_unknown_fields)]
62pub struct ResourceChoiceRange {
63 pub min: String,
65 pub max: String,
67 pub default: String,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
73#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
74#[serde(rename_all = "camelCase", deny_unknown_fields)]
75pub struct ContainerResourceChoices {
76 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub cpu: Option<ResourceChoiceRange>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub memory: Option<ResourceChoiceRange>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
87#[serde(rename_all = "camelCase")]
88pub struct ContainerGpuSpec {
89 #[serde(rename = "type")]
91 pub gpu_type: String,
92 pub count: u32,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
99#[serde(rename_all = "camelCase")]
100pub struct PersistentStorage {
101 pub size: String,
103 pub mount_path: String,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub encryption_key: Option<ResourceRef>,
108 #[serde(default)]
110 pub backups: VolumeBackups,
111}
112
113pub const VOLUME_BACKUP_INTERVAL_HOURS: [u32; 7] = [1, 2, 4, 6, 8, 12, 24];
115
116pub const VOLUME_BACKUP_MAX_SNAPSHOTS: u32 = 450;
120
121pub const VOLUME_BACKUP_MAX_RETENTION_DAYS: u32 = 365;
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
138#[serde(rename_all = "camelCase")]
139pub struct VolumeBackups {
140 #[serde(default = "default_volume_backups_enabled")]
142 pub enabled: bool,
143 #[serde(default = "default_volume_backup_interval_hours")]
145 pub interval_hours: u32,
146 #[serde(default = "default_volume_backup_retention_days")]
148 pub retention_days: u32,
149}
150
151fn default_volume_backups_enabled() -> bool {
152 true
153}
154
155fn default_volume_backup_interval_hours() -> u32 {
156 24
157}
158
159fn default_volume_backup_retention_days() -> u32 {
160 7
161}
162
163impl Default for VolumeBackups {
164 fn default() -> Self {
165 Self {
166 enabled: default_volume_backups_enabled(),
167 interval_hours: default_volume_backup_interval_hours(),
168 retention_days: default_volume_backup_retention_days(),
169 }
170 }
171}
172
173impl VolumeBackups {
174 pub fn disabled() -> Self {
176 Self {
177 enabled: false,
178 ..Self::default()
179 }
180 }
181
182 pub fn validation_error(&self) -> Option<String> {
184 if !self.enabled {
185 return None;
186 }
187 if !VOLUME_BACKUP_INTERVAL_HOURS.contains(&self.interval_hours) {
188 return Some(format!(
189 "backup intervalHours must be one of {VOLUME_BACKUP_INTERVAL_HOURS:?}, got {}",
190 self.interval_hours
191 ));
192 }
193 if self.retention_days == 0 {
194 return Some("backup retentionDays must be at least 1".to_string());
195 }
196 if self.retention_days > VOLUME_BACKUP_MAX_RETENTION_DAYS {
197 return Some(format!(
198 "backup retentionDays must be at most {VOLUME_BACKUP_MAX_RETENTION_DAYS}, got {}",
199 self.retention_days
200 ));
201 }
202 let snapshots = self.retention_days * 24 / self.interval_hours;
203 if snapshots > VOLUME_BACKUP_MAX_SNAPSHOTS {
204 return Some(format!(
205 "backups every {} hours for {} days keep {snapshots} snapshots per volume; \
206 the most is {VOLUME_BACKUP_MAX_SNAPSHOTS}",
207 self.interval_hours, self.retention_days
208 ));
209 }
210 None
211 }
212}
213
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
218#[serde(rename_all = "camelCase")]
219pub struct KubernetesSecretMount {
220 pub secret_name: String,
222 pub mount_path: String,
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
228#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
229#[serde(rename_all = "camelCase")]
230pub struct KubernetesHttpProbe {
231 pub path: String,
233 pub port: u16,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
242#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
243#[serde(rename_all = "camelCase")]
244pub enum WorkloadPriority {
245 Critical,
246 High,
247 Normal,
248 Low,
249}
250
251impl WorkloadPriority {
252 pub fn as_str(&self) -> &'static str {
254 match self {
255 Self::Critical => "critical",
256 Self::High => "high",
257 Self::Normal => "normal",
258 Self::Low => "low",
259 }
260 }
261}
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
266#[serde(rename_all = "camelCase")]
267pub enum ContainerSecurityProfile {
268 Restricted,
269}
270
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
274#[serde(rename_all = "camelCase")]
275pub struct ContainerSecurity {
276 pub profile: ContainerSecurityProfile,
278 pub run_as_user: i64,
280 pub run_as_group: i64,
282 pub read_only_root_filesystem: bool,
284}
285
286#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
288#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
289#[serde(rename_all = "camelCase")]
290pub struct ContainerAutoscaling {
291 pub min: u32,
293 pub desired: u32,
295 pub max: u32,
297 #[serde(skip_serializing_if = "Option::is_none")]
299 pub target_cpu_percent: Option<f64>,
300 #[serde(skip_serializing_if = "Option::is_none")]
302 pub target_memory_percent: Option<f64>,
303 #[serde(skip_serializing_if = "Option::is_none")]
305 pub target_http_in_flight_per_replica: Option<u32>,
306 #[serde(skip_serializing_if = "Option::is_none")]
308 pub max_http_p95_latency_ms: Option<f64>,
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
313#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
314#[serde(rename_all = "camelCase")]
315pub struct HealthCheck {
316 #[serde(default = "default_health_path")]
318 pub path: String,
319 #[serde(skip_serializing_if = "Option::is_none")]
321 pub port: Option<u16>,
322 #[serde(default = "default_health_method")]
324 pub method: String,
325 #[serde(default = "default_timeout_seconds")]
327 pub timeout_seconds: u32,
328 #[serde(default = "default_failure_threshold")]
330 pub failure_threshold: u32,
331}
332
333impl Default for HealthCheck {
334 fn default() -> Self {
336 HealthCheck {
337 path: default_health_path(),
338 port: None,
339 method: default_health_method(),
340 timeout_seconds: default_timeout_seconds(),
341 failure_threshold: default_failure_threshold(),
342 }
343 }
344}
345
346fn default_health_path() -> String {
347 "/health".to_string()
348}
349
350fn default_health_method() -> String {
351 "GET".to_string()
352}
353
354fn default_timeout_seconds() -> u32 {
355 1
356}
357
358fn default_failure_threshold() -> u32 {
359 3
360}
361
362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
364#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
365#[serde(rename_all = "camelCase")]
366pub struct ContainerPort {
367 pub port: u16,
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
376#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
377#[serde(rename_all = "camelCase")]
378pub enum ContainerEgress {
379 Internet,
383}
384
385#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
424#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
425#[serde(rename_all = "camelCase", deny_unknown_fields)]
426#[builder(start_fn = new)]
427pub struct Container {
428 #[builder(start_fn)]
431 pub id: String,
432
433 #[builder(field)]
435 pub links: Vec<ResourceRef>,
436
437 #[builder(field)]
439 pub ports: Vec<ContainerPort>,
440
441 #[builder(field)]
443 #[serde(default, skip_serializing_if = "Vec::is_empty")]
444 pub kubernetes_secret_mounts: Vec<KubernetesSecretMount>,
445
446 #[builder(field)]
448 #[serde(default, skip_serializing_if = "Vec::is_empty")]
449 pub public_endpoints: Vec<PublicEndpoint>,
450
451 #[serde(default, skip_serializing_if = "Option::is_none")]
453 pub egress: Option<ContainerEgress>,
454
455 #[serde(default, skip_serializing_if = "Option::is_none")]
459 pub tunnel: Option<ContainerTunnel>,
460
461 #[serde(skip_serializing_if = "Option::is_none")]
463 pub kubernetes_liveness_probe: Option<KubernetesHttpProbe>,
464
465 #[serde(skip_serializing_if = "Option::is_none")]
467 pub kubernetes_readiness_probe: Option<KubernetesHttpProbe>,
468
469 #[serde(skip_serializing_if = "Option::is_none")]
471 pub security: Option<ContainerSecurity>,
472
473 #[serde(skip_serializing_if = "Option::is_none")]
476 pub cluster: Option<String>,
477
478 pub code: ContainerCode,
480
481 pub cpu: ResourceSpec,
483
484 pub memory: ResourceSpec,
486
487 #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub resource_choices: Option<ContainerResourceChoices>,
490
491 #[serde(skip_serializing_if = "Option::is_none")]
493 pub gpu: Option<ContainerGpuSpec>,
494
495 #[serde(skip_serializing_if = "Option::is_none")]
497 pub ephemeral_storage: Option<String>,
498
499 #[serde(skip_serializing_if = "Option::is_none")]
501 pub persistent_storage: Option<PersistentStorage>,
502
503 #[serde(skip_serializing_if = "Option::is_none")]
505 pub replicas: Option<u32>,
506
507 #[serde(skip_serializing_if = "Option::is_none")]
509 pub autoscaling: Option<ContainerAutoscaling>,
510
511 #[builder(default = false)]
513 #[serde(default)]
514 pub stateful: bool,
515
516 #[builder(default)]
518 #[serde(default)]
519 pub environment: HashMap<String, String>,
520
521 #[serde(skip_serializing_if = "Option::is_none")]
524 pub pool: Option<String>,
525
526 pub permissions: String,
528
529 #[serde(skip_serializing_if = "Option::is_none")]
531 pub health_check: Option<HealthCheck>,
532
533 #[serde(skip_serializing_if = "Option::is_none")]
535 pub command: Option<Vec<String>>,
536
537 #[builder(default = default_commands_enabled())]
541 #[serde(default = "default_commands_enabled")]
542 #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
543 pub commands_enabled: bool,
544
545 #[builder(default)]
551 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
552 pub commands_capability_file: bool,
553
554 #[serde(skip_serializing_if = "Option::is_none")]
559 #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
560 pub stop_grace_period_seconds: Option<u32>,
561
562 #[serde(default, skip_serializing_if = "Option::is_none")]
566 pub priority: Option<WorkloadPriority>,
567}
568
569impl Container {
570 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
572
573 pub fn id(&self) -> &str {
575 &self.id
576 }
577
578 pub fn get_permissions(&self) -> &str {
580 &self.permissions
581 }
582
583 pub fn is_stateless(&self) -> bool {
585 !self.stateful
586 }
587
588 pub fn validate_network_settings(&self) -> Result<()> {
590 let invalid = |reason: String| {
591 AlienError::new(ErrorData::InvalidResourceUpdate {
592 resource_id: self.id.clone(),
593 reason,
594 })
595 };
596 if self.egress.is_some()
597 && !self
598 .security
599 .as_ref()
600 .is_some_and(|security| security.profile == ContainerSecurityProfile::Restricted)
601 {
602 return Err(invalid(
603 "container egress internet requires security.profile restricted".into(),
604 ));
605 }
606 Ok(())
607 }
608
609 fn validate_public_endpoints(&self) -> Result<()> {
611 let mut endpoint_names = std::collections::HashSet::new();
612 let mut backend_ports = std::collections::HashSet::new();
613 let mut apex_endpoint_name: Option<&str> = None;
614
615 for endpoint in &self.public_endpoints {
616 endpoint.validate_for_resource(&self.id)?;
617
618 if !endpoint_names.insert(endpoint.name.as_str()) {
619 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
620 resource_id: self.id.clone(),
621 reason: format!("duplicate public endpoint name '{}'", endpoint.name),
622 }));
623 }
624
625 if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
626 if let Some(existing_name) = apex_endpoint_name {
627 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
628 resource_id: self.id.clone(),
629 reason: format!(
630 "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
631 existing_name
632 ),
633 }));
634 }
635 apex_endpoint_name = Some(endpoint.name.as_str());
636 }
637
638 backend_ports.insert(endpoint.port);
639
640 if !self.ports.iter().any(|port| port.port == endpoint.port) {
641 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
642 resource_id: self.id.clone(),
643 reason: format!(
644 "public endpoint '{}' references undeclared port {}",
645 endpoint.name, endpoint.port
646 ),
647 }));
648 }
649 }
650
651 if backend_ports.len() > 1 {
652 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
653 resource_id: self.id.clone(),
654 reason:
655 "public endpoints on one container must currently route to the same backend port"
656 .to_string(),
657 }));
658 }
659
660 Ok(())
661 }
662}
663
664fn default_commands_enabled() -> bool {
665 false
666}
667
668impl<S: container_builder::State> ContainerBuilder<S> {
669 pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
671 where
672 for<'a> &'a R: Into<ResourceRef>,
673 {
674 let resource_ref: ResourceRef = resource.into();
675 self.links.push(resource_ref);
676 self
677 }
678
679 pub fn port(mut self, port: u16) -> Self {
681 self.ports.push(ContainerPort { port });
682 self
683 }
684
685 pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
687 self.kubernetes_secret_mounts.push(mount);
688 self
689 }
690
691 pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
693 if !self.ports.iter().any(|p| p.port == endpoint.port) {
694 self.ports.push(ContainerPort {
695 port: endpoint.port,
696 });
697 }
698 self.public_endpoints.push(endpoint);
699 self
700 }
701}
702
703#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
705#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
706#[serde(rename_all = "camelCase")]
707pub enum ContainerStatus {
708 Pending,
710 Running,
712 Stopped,
714 Failing,
717}
718
719#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
721#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
722#[serde(rename_all = "camelCase")]
723pub struct ReplicaStatus {
724 pub replica_id: String,
726 pub ordinal: Option<u32>,
728 pub machine_id: Option<String>,
730 pub healthy: bool,
732 pub container_ip: Option<String>,
734}
735
736#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
743#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
744#[serde(rename_all = "camelCase", deny_unknown_fields)]
745pub struct ContainerTunnel {
746 pub port: u16,
748}
749
750#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
752#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
753#[serde(rename_all = "camelCase")]
754pub struct ContainerOutputs {
755 pub name: String,
757 pub status: ContainerStatus,
759 pub current_replicas: u32,
761 pub desired_replicas: u32,
763 pub internal_dns: String,
765 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
767 pub public_endpoints: HashMap<String, PublicEndpointOutput>,
768 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
770 pub internal_urls: HashMap<u16, String>,
771 pub replicas: Vec<ReplicaStatus>,
773 #[serde(default, skip_serializing_if = "Vec::is_empty")]
775 pub volumes: Vec<VolumeOutput>,
776 #[serde(default, skip_serializing_if = "Option::is_none")]
778 pub volume_backups: Option<VolumeBackupsStatus>,
779}
780
781#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
783#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
784#[serde(rename_all = "camelCase")]
785pub struct VolumeBackupsStatus {
786 pub state: VolumeBackupsState,
788 #[serde(skip_serializing_if = "Option::is_none")]
790 pub message: Option<String>,
791}
792
793#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
795#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
796#[serde(rename_all = "camelCase")]
797pub enum VolumeBackupsState {
798 Active,
800 Disabled,
802 SetupRequired,
806}
807
808#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
810#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
811#[serde(rename_all = "camelCase")]
812pub struct VolumeOutput {
813 pub ordinal: u32,
815 pub volume_id: String,
817 pub zone: String,
819 #[serde(skip_serializing_if = "Option::is_none")]
821 pub last_snapshot_id: Option<String>,
822 #[serde(skip_serializing_if = "Option::is_none")]
824 pub last_snapshot_at: Option<String>,
825 #[serde(skip_serializing_if = "Option::is_none")]
827 pub last_restore: Option<VolumeRestoreOutput>,
828}
829
830#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
832#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
833#[serde(rename_all = "camelCase")]
834pub struct VolumeRestoreOutput {
835 pub request_id: String,
837 pub snapshot_id: String,
839 pub replaced_volume_snapshot_id: String,
841 pub completed_at: String,
843}
844
845impl ResourceOutputsDefinition for ContainerOutputs {
846 fn get_resource_type(&self) -> ResourceType {
847 Container::RESOURCE_TYPE.clone()
848 }
849
850 fn as_any(&self) -> &dyn Any {
851 self
852 }
853
854 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
855 Box::new(self.clone())
856 }
857
858 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
859 other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
860 }
861
862 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
863 serde_json::to_value(self)
864 }
865}
866
867impl ResourceDefinition for Container {
868 fn get_resource_type(&self) -> ResourceType {
869 Self::RESOURCE_TYPE
870 }
871
872 fn id(&self) -> &str {
873 &self.id
874 }
875
876 fn replace_after_failed_create_is_safe(&self) -> bool {
877 !(self.stateful && self.persistent_storage.is_some())
879 }
880
881 fn get_dependencies(&self) -> Vec<ResourceRef> {
882 let mut deps = self.links.clone();
883 if let Some(key) = self
884 .persistent_storage
885 .as_ref()
886 .and_then(|storage| storage.encryption_key.as_ref())
887 {
888 deps.push(key.clone());
889 }
890 if let Some(cluster) = &self.cluster {
893 deps.push(ResourceRef::new(
894 ComputeCluster::RESOURCE_TYPE.clone(),
895 cluster,
896 ));
897 }
898 deps
899 }
900
901 fn get_permissions(&self) -> Option<&str> {
902 Some(&self.permissions)
903 }
904
905 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
906 let new_container = new_config
907 .as_any()
908 .downcast_ref::<Container>()
909 .ok_or_else(|| {
910 AlienError::new(ErrorData::UnexpectedResourceType {
911 resource_id: self.id.clone(),
912 expected: Self::RESOURCE_TYPE,
913 actual: new_config.get_resource_type(),
914 })
915 })?;
916
917 new_container.validate_public_endpoints()?;
919 new_container.validate_network_settings()?;
920
921 if self.id != new_container.id {
922 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
923 resource_id: self.id.clone(),
924 reason: "the 'id' field is immutable".to_string(),
925 }));
926 }
927
928 if self.cluster != new_container.cluster {
930 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
931 resource_id: self.id.clone(),
932 reason: "the 'cluster' field is immutable".to_string(),
933 }));
934 }
935
936 if self.stateful != new_container.stateful {
938 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
939 resource_id: self.id.clone(),
940 reason: "the 'stateful' field is immutable".to_string(),
941 }));
942 }
943
944 let old_key = self
945 .persistent_storage
946 .as_ref()
947 .and_then(|storage| storage.encryption_key.as_ref());
948 let new_key = new_container
949 .persistent_storage
950 .as_ref()
951 .and_then(|storage| storage.encryption_key.as_ref());
952 if old_key != new_key {
953 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
954 resource_id: self.id.clone(),
955 reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
956 }));
957 }
958
959 if self.ports != new_container.ports {
961 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
962 resource_id: self.id.clone(),
963 reason: "the 'ports' field is immutable".to_string(),
964 }));
965 }
966
967 if self.public_endpoints != new_container.public_endpoints {
968 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
969 resource_id: self.id.clone(),
970 reason: "the 'publicEndpoints' field is immutable".to_string(),
971 }));
972 }
973
974 if self.pool != new_container.pool {
976 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
977 resource_id: self.id.clone(),
978 reason: "the 'pool' field is immutable".to_string(),
979 }));
980 }
981
982 Ok(())
983 }
984
985 fn as_any(&self) -> &dyn Any {
986 self
987 }
988
989 fn as_any_mut(&mut self) -> &mut dyn Any {
990 self
991 }
992
993 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
994 Box::new(self.clone())
995 }
996
997 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
998 other.as_any().downcast_ref::<Container>() == Some(self)
999 }
1000
1001 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1002 serde_json::to_value(self)
1003 }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008 use super::*;
1009 use crate::resources::ExposeProtocol;
1010
1011 fn network_container() -> Container {
1012 Container::new("api".to_string())
1013 .code(ContainerCode::Image {
1014 image: "example:latest".into(),
1015 })
1016 .cpu(ResourceSpec {
1017 min: "1".into(),
1018 desired: "1".into(),
1019 })
1020 .memory(ResourceSpec {
1021 min: "512Mi".into(),
1022 desired: "512Mi".into(),
1023 })
1024 .permissions("execution".into())
1025 .public_endpoint(PublicEndpoint {
1026 name: "web".into(),
1027 port: 8080,
1028 protocol: ExposeProtocol::Http,
1029 host_label: None,
1030 wildcard_subdomains: false,
1031 })
1032 .build()
1033 }
1034
1035 #[test]
1036 fn internet_egress_requires_restricted_security_and_is_opt_in() {
1037 let mut container = network_container();
1038 assert!(serde_json::to_value(&container)
1039 .unwrap()
1040 .get("egress")
1041 .is_none());
1042 container.egress = Some(ContainerEgress::Internet);
1043 assert!(container.validate_update(&container).is_err());
1044 container.security = Some(ContainerSecurity {
1045 profile: ContainerSecurityProfile::Restricted,
1046 run_as_user: 65532,
1047 run_as_group: 65532,
1048 read_only_root_filesystem: true,
1049 });
1050 container.validate_update(&container).unwrap();
1051 assert_eq!(
1052 serde_json::to_value(&container).unwrap()["egress"],
1053 "internet"
1054 );
1055 }
1056
1057 #[test]
1058 fn test_container_creation_with_autoscaling() {
1059 let container = Container::new("api".to_string())
1060 .cluster("compute".to_string())
1061 .code(ContainerCode::Image {
1062 image: "myapp:latest".to_string(),
1063 })
1064 .cpu(ResourceSpec {
1065 min: "0.5".to_string(),
1066 desired: "1".to_string(),
1067 })
1068 .memory(ResourceSpec {
1069 min: "512Mi".to_string(),
1070 desired: "1Gi".to_string(),
1071 })
1072 .port(8080)
1073 .public_endpoint(PublicEndpoint {
1074 name: "api".to_string(),
1075 port: 8080,
1076 protocol: ExposeProtocol::Http,
1077 host_label: None,
1078 wildcard_subdomains: false,
1079 })
1080 .autoscaling(ContainerAutoscaling {
1081 min: 2,
1082 desired: 3,
1083 max: 10,
1084 target_cpu_percent: Some(70.0),
1085 target_memory_percent: None,
1086 target_http_in_flight_per_replica: Some(100),
1087 max_http_p95_latency_ms: None,
1088 })
1089 .permissions("container-execution".to_string())
1090 .build();
1091
1092 assert_eq!(container.id(), "api");
1093 assert_eq!(container.cluster, Some("compute".to_string()));
1094 assert!(!container.stateful);
1095 assert!(container.autoscaling.is_some());
1096 assert_eq!(container.ports.len(), 1);
1097 assert_eq!(container.ports[0].port, 8080);
1098 }
1099
1100 #[test]
1101 fn container_serializes_stop_grace_period_when_set() {
1102 let container = Container::new("api".to_string())
1103 .cluster("compute".to_string())
1104 .code(ContainerCode::Image {
1105 image: "myapp:latest".to_string(),
1106 })
1107 .cpu(ResourceSpec {
1108 min: "0.5".to_string(),
1109 desired: "1".to_string(),
1110 })
1111 .memory(ResourceSpec {
1112 min: "512Mi".to_string(),
1113 desired: "1Gi".to_string(),
1114 })
1115 .port(8080)
1116 .permissions("container-execution".to_string())
1117 .stop_grace_period_seconds(21_600)
1118 .build();
1119
1120 let json = serde_json::to_value(&container).expect("container should serialize");
1121 assert_eq!(json["stopGracePeriodSeconds"], 21_600);
1122 }
1123
1124 #[test]
1125 fn container_omits_stop_grace_period_when_absent() {
1126 let container = Container::new("api".to_string())
1127 .cluster("compute".to_string())
1128 .code(ContainerCode::Image {
1129 image: "myapp:latest".to_string(),
1130 })
1131 .cpu(ResourceSpec {
1132 min: "0.5".to_string(),
1133 desired: "1".to_string(),
1134 })
1135 .memory(ResourceSpec {
1136 min: "512Mi".to_string(),
1137 desired: "1Gi".to_string(),
1138 })
1139 .port(8080)
1140 .permissions("container-execution".to_string())
1141 .build();
1142
1143 let json = serde_json::to_value(&container).expect("container should serialize");
1144 assert!(json.get("stopGracePeriodSeconds").is_none());
1145 }
1146
1147 #[test]
1148 fn test_stateful_container_with_storage() {
1149 let container = Container::new("postgres".to_string())
1150 .cluster("compute".to_string())
1151 .code(ContainerCode::Image {
1152 image: "postgres:16".to_string(),
1153 })
1154 .cpu(ResourceSpec {
1155 min: "1".to_string(),
1156 desired: "2".to_string(),
1157 })
1158 .memory(ResourceSpec {
1159 min: "2Gi".to_string(),
1160 desired: "4Gi".to_string(),
1161 })
1162 .port(5432)
1163 .stateful(true)
1164 .replicas(1)
1165 .persistent_storage(PersistentStorage {
1166 encryption_key: None,
1167 size: "100Gi".to_string(),
1168 mount_path: "/var/lib/postgresql/data".to_string(),
1169 backups: VolumeBackups::default(),
1170 })
1171 .permissions("database".to_string())
1172 .build();
1173
1174 assert_eq!(container.id(), "postgres");
1175 assert!(container.stateful);
1176 assert!(container.replicas.is_some());
1177 assert!(container.persistent_storage.is_some());
1178 }
1179
1180 #[test]
1181 fn test_public_container() {
1182 let container = Container::new("frontend".to_string())
1183 .cluster("compute".to_string())
1184 .code(ContainerCode::Image {
1185 image: "frontend:latest".to_string(),
1186 })
1187 .cpu(ResourceSpec {
1188 min: "0.25".to_string(),
1189 desired: "0.5".to_string(),
1190 })
1191 .memory(ResourceSpec {
1192 min: "256Mi".to_string(),
1193 desired: "512Mi".to_string(),
1194 })
1195 .port(3000)
1196 .public_endpoint(PublicEndpoint {
1197 name: "web".to_string(),
1198 port: 3000,
1199 protocol: ExposeProtocol::Http,
1200 host_label: None,
1201 wildcard_subdomains: false,
1202 })
1203 .autoscaling(ContainerAutoscaling {
1204 min: 2,
1205 desired: 2,
1206 max: 20,
1207 target_cpu_percent: None,
1208 target_memory_percent: None,
1209 target_http_in_flight_per_replica: Some(50),
1210 max_http_p95_latency_ms: Some(100.0),
1211 })
1212 .health_check(HealthCheck {
1213 path: "/health".to_string(),
1214 port: None,
1215 method: "GET".to_string(),
1216 timeout_seconds: 1,
1217 failure_threshold: 3,
1218 })
1219 .permissions("frontend".to_string())
1220 .build();
1221
1222 assert_eq!(container.ports[0].port, 3000);
1223 assert_eq!(container.public_endpoints[0].name, "web");
1224 assert!(container.health_check.is_some());
1225 }
1226
1227 #[test]
1228 fn test_public_container_endpoint_options() {
1229 let container = Container::new("router".to_string())
1230 .cluster("compute".to_string())
1231 .code(ContainerCode::Image {
1232 image: "router:latest".to_string(),
1233 })
1234 .cpu(ResourceSpec {
1235 min: "0.25".to_string(),
1236 desired: "0.5".to_string(),
1237 })
1238 .memory(ResourceSpec {
1239 min: "256Mi".to_string(),
1240 desired: "512Mi".to_string(),
1241 })
1242 .public_endpoint(PublicEndpoint {
1243 name: "gateway".to_string(),
1244 port: 8080,
1245 protocol: ExposeProtocol::Http,
1246 host_label: Some("gateway".to_string()),
1247 wildcard_subdomains: true,
1248 })
1249 .permissions("router".to_string())
1250 .build();
1251
1252 assert!(container.validate_public_endpoints().is_ok());
1253 assert_eq!(container.ports.len(), 1);
1254 assert_eq!(container.public_endpoints.len(), 1);
1255 assert_eq!(
1256 container.public_endpoints[0].host_label.as_deref(),
1257 Some("gateway")
1258 );
1259 assert!(container.public_endpoints[0].wildcard_subdomains);
1260 }
1261
1262 #[test]
1263 fn test_public_container_rejects_invalid_host_label() {
1264 let container = Container::new("router".to_string())
1265 .cluster("compute".to_string())
1266 .code(ContainerCode::Image {
1267 image: "router:latest".to_string(),
1268 })
1269 .cpu(ResourceSpec {
1270 min: "0.25".to_string(),
1271 desired: "0.5".to_string(),
1272 })
1273 .memory(ResourceSpec {
1274 min: "256Mi".to_string(),
1275 desired: "512Mi".to_string(),
1276 })
1277 .public_endpoint(PublicEndpoint {
1278 name: "gateway".to_string(),
1279 port: 8080,
1280 protocol: ExposeProtocol::Http,
1281 host_label: Some("bad.label".to_string()),
1282 wildcard_subdomains: true,
1283 })
1284 .permissions("router".to_string())
1285 .build();
1286
1287 assert!(container.validate_public_endpoints().is_err());
1288 }
1289
1290 #[test]
1291 fn test_container_with_links() {
1292 use crate::Storage;
1293
1294 let storage = Storage::new("data".to_string()).build();
1295
1296 let container = Container::new("worker".to_string())
1297 .cluster("compute".to_string())
1298 .code(ContainerCode::Image {
1299 image: "worker:latest".to_string(),
1300 })
1301 .cpu(ResourceSpec {
1302 min: "0.5".to_string(),
1303 desired: "1".to_string(),
1304 })
1305 .memory(ResourceSpec {
1306 min: "512Mi".to_string(),
1307 desired: "1Gi".to_string(),
1308 })
1309 .port(8080)
1310 .replicas(3)
1311 .link(&storage)
1312 .permissions("worker".to_string())
1313 .build();
1314
1315 let deps = container.get_dependencies();
1317 assert_eq!(deps.len(), 2);
1318 }
1319
1320 #[test]
1321 fn test_container_validate_update_immutable_cluster() {
1322 let container1 = Container::new("api".to_string())
1323 .cluster("cluster-1".to_string())
1324 .code(ContainerCode::Image {
1325 image: "myapp:v1".to_string(),
1326 })
1327 .cpu(ResourceSpec {
1328 min: "0.5".to_string(),
1329 desired: "1".to_string(),
1330 })
1331 .memory(ResourceSpec {
1332 min: "512Mi".to_string(),
1333 desired: "1Gi".to_string(),
1334 })
1335 .port(8080)
1336 .replicas(2)
1337 .permissions("execution".to_string())
1338 .build();
1339
1340 let container2 = Container::new("api".to_string())
1341 .cluster("cluster-2".to_string()) .code(ContainerCode::Image {
1343 image: "myapp:v2".to_string(),
1344 })
1345 .cpu(ResourceSpec {
1346 min: "0.5".to_string(),
1347 desired: "1".to_string(),
1348 })
1349 .memory(ResourceSpec {
1350 min: "512Mi".to_string(),
1351 desired: "1Gi".to_string(),
1352 })
1353 .port(8080)
1354 .replicas(2)
1355 .permissions("execution".to_string())
1356 .build();
1357
1358 let result = container1.validate_update(&container2);
1359 assert!(result.is_err());
1360 }
1361
1362 #[test]
1363 fn test_container_validate_update_allowed_changes() {
1364 let container1 = Container::new("api".to_string())
1365 .cluster("compute".to_string())
1366 .code(ContainerCode::Image {
1367 image: "myapp:v1".to_string(),
1368 })
1369 .cpu(ResourceSpec {
1370 min: "0.5".to_string(),
1371 desired: "1".to_string(),
1372 })
1373 .memory(ResourceSpec {
1374 min: "512Mi".to_string(),
1375 desired: "1Gi".to_string(),
1376 })
1377 .port(8080)
1378 .replicas(2)
1379 .permissions("execution".to_string())
1380 .build();
1381
1382 let container2 = Container::new("api".to_string())
1383 .cluster("compute".to_string())
1384 .code(ContainerCode::Image {
1385 image: "myapp:v2".to_string(), })
1387 .cpu(ResourceSpec {
1388 min: "1".to_string(), desired: "2".to_string(),
1390 })
1391 .memory(ResourceSpec {
1392 min: "1Gi".to_string(),
1393 desired: "2Gi".to_string(),
1394 })
1395 .port(8080)
1396 .replicas(5) .permissions("execution".to_string())
1398 .build();
1399
1400 let result = container1.validate_update(&container2);
1401 assert!(result.is_ok());
1402 }
1403
1404 #[test]
1405 fn test_container_serialization() {
1406 let container = Container::new("test".to_string())
1407 .cluster("compute".to_string())
1408 .code(ContainerCode::Image {
1409 image: "test:latest".to_string(),
1410 })
1411 .cpu(ResourceSpec {
1412 min: "0.5".to_string(),
1413 desired: "1".to_string(),
1414 })
1415 .memory(ResourceSpec {
1416 min: "512Mi".to_string(),
1417 desired: "1Gi".to_string(),
1418 })
1419 .port(8080)
1420 .replicas(1)
1421 .permissions("test".to_string())
1422 .build();
1423
1424 let json = serde_json::to_string(&container).unwrap();
1425 let deserialized: Container = serde_json::from_str(&json).unwrap();
1426 assert_eq!(container, deserialized);
1427 }
1428
1429 #[test]
1430 fn test_container_multi_endpoint_validation() {
1431 let container = Container::new("multi-tcp".to_string())
1432 .cluster("compute".to_string())
1433 .code(ContainerCode::Image {
1434 image: "test:latest".to_string(),
1435 })
1436 .cpu(ResourceSpec {
1437 min: "1".to_string(),
1438 desired: "1".to_string(),
1439 })
1440 .memory(ResourceSpec {
1441 min: "1Gi".to_string(),
1442 desired: "1Gi".to_string(),
1443 })
1444 .port(8080)
1445 .public_endpoint(PublicEndpoint {
1446 name: "api".to_string(),
1447 port: 8080,
1448 protocol: ExposeProtocol::Http,
1449 host_label: None,
1450 wildcard_subdomains: false,
1451 })
1452 .public_endpoint(PublicEndpoint {
1453 name: "wildcard".to_string(),
1454 port: 8080,
1455 protocol: ExposeProtocol::Http,
1456 host_label: Some("wildcard".to_string()),
1457 wildcard_subdomains: true,
1458 })
1459 .replicas(1)
1460 .permissions("test".to_string())
1461 .build();
1462
1463 assert!(container.validate_public_endpoints().is_ok());
1464
1465 let invalid_container = Container::new("multi-http".to_string())
1466 .cluster("compute".to_string())
1467 .code(ContainerCode::Image {
1468 image: "test:latest".to_string(),
1469 })
1470 .cpu(ResourceSpec {
1471 min: "1".to_string(),
1472 desired: "1".to_string(),
1473 })
1474 .memory(ResourceSpec {
1475 min: "1Gi".to_string(),
1476 desired: "1Gi".to_string(),
1477 })
1478 .port(8080)
1479 .port(9090)
1480 .public_endpoint(PublicEndpoint {
1481 name: "api".to_string(),
1482 port: 8080,
1483 protocol: ExposeProtocol::Http,
1484 host_label: None,
1485 wildcard_subdomains: false,
1486 })
1487 .public_endpoint(PublicEndpoint {
1488 name: "admin".to_string(),
1489 port: 9090,
1490 protocol: ExposeProtocol::Http,
1491 host_label: None,
1492 wildcard_subdomains: false,
1493 })
1494 .replicas(1)
1495 .permissions("test".to_string())
1496 .build();
1497
1498 assert!(invalid_container.validate_public_endpoints().is_err());
1499 }
1500
1501 #[test]
1502 fn container_rejects_multiple_apex_public_endpoints() {
1503 let container = Container::new("apex-container".to_string())
1504 .cluster("compute".to_string())
1505 .code(ContainerCode::Image {
1506 image: "test:latest".to_string(),
1507 })
1508 .cpu(ResourceSpec {
1509 min: "1".to_string(),
1510 desired: "1".to_string(),
1511 })
1512 .memory(ResourceSpec {
1513 min: "1Gi".to_string(),
1514 desired: "1Gi".to_string(),
1515 })
1516 .port(8080)
1517 .public_endpoint(PublicEndpoint {
1518 name: "web".to_string(),
1519 port: 8080,
1520 protocol: ExposeProtocol::Http,
1521 host_label: Some(APEX_HOST_LABEL.to_string()),
1522 wildcard_subdomains: false,
1523 })
1524 .public_endpoint(PublicEndpoint {
1525 name: "admin".to_string(),
1526 port: 8080,
1527 protocol: ExposeProtocol::Http,
1528 host_label: Some(APEX_HOST_LABEL.to_string()),
1529 wildcard_subdomains: false,
1530 })
1531 .replicas(1)
1532 .permissions("test".to_string())
1533 .build();
1534
1535 assert!(container.validate_public_endpoints().is_err());
1536 }
1537
1538 #[test]
1539 fn test_container_empty_ports_validation() {
1540 let container = Container::new("no-ports".to_string())
1541 .cluster("compute".to_string())
1542 .code(ContainerCode::Image {
1543 image: "test:latest".to_string(),
1544 })
1545 .cpu(ResourceSpec {
1546 min: "1".to_string(),
1547 desired: "1".to_string(),
1548 })
1549 .memory(ResourceSpec {
1550 min: "1Gi".to_string(),
1551 desired: "1Gi".to_string(),
1552 })
1553 .replicas(1)
1554 .permissions("test".to_string())
1555 .build();
1556
1557 assert!(container.validate_public_endpoints().is_ok());
1558 }
1559
1560 #[test]
1561 fn test_container_commands_enabled_defaults_false() {
1562 let container = Container::new("no-commands".to_string())
1563 .cluster("compute".to_string())
1564 .code(ContainerCode::Image {
1565 image: "test:latest".to_string(),
1566 })
1567 .cpu(ResourceSpec {
1568 min: "0.5".to_string(),
1569 desired: "1".to_string(),
1570 })
1571 .memory(ResourceSpec {
1572 min: "512Mi".to_string(),
1573 desired: "1Gi".to_string(),
1574 })
1575 .port(8080)
1576 .permissions("test".to_string())
1577 .build();
1578
1579 assert!(!container.commands_enabled);
1580 }
1581
1582 #[test]
1583 fn test_container_commands_enabled_builder() {
1584 let container = Container::new("cmd-container".to_string())
1585 .cluster("compute".to_string())
1586 .code(ContainerCode::Image {
1587 image: "test:latest".to_string(),
1588 })
1589 .cpu(ResourceSpec {
1590 min: "0.5".to_string(),
1591 desired: "1".to_string(),
1592 })
1593 .memory(ResourceSpec {
1594 min: "512Mi".to_string(),
1595 desired: "1Gi".to_string(),
1596 })
1597 .port(8080)
1598 .permissions("test".to_string())
1599 .commands_enabled(true)
1600 .build();
1601
1602 assert!(container.commands_enabled);
1603 }
1604
1605 #[test]
1606 fn test_container_commands_enabled_serializes_camel_case() {
1607 let container = Container::new("cmd-container".to_string())
1608 .cluster("compute".to_string())
1609 .code(ContainerCode::Image {
1610 image: "test:latest".to_string(),
1611 })
1612 .cpu(ResourceSpec {
1613 min: "0.5".to_string(),
1614 desired: "1".to_string(),
1615 })
1616 .memory(ResourceSpec {
1617 min: "512Mi".to_string(),
1618 desired: "1Gi".to_string(),
1619 })
1620 .port(8080)
1621 .permissions("test".to_string())
1622 .commands_enabled(true)
1623 .build();
1624
1625 let json = serde_json::to_value(&container).expect("container should serialize");
1626 assert_eq!(json["commandsEnabled"], true);
1627
1628 let deserialized: Container =
1629 serde_json::from_value(json).expect("container should deserialize");
1630 assert_eq!(deserialized, container);
1631 }
1632}