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 #[serde(skip_serializing_if = "Option::is_none")]
550 #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
551 pub stop_grace_period_seconds: Option<u32>,
552
553 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub priority: Option<WorkloadPriority>,
558}
559
560impl Container {
561 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
563
564 pub fn id(&self) -> &str {
566 &self.id
567 }
568
569 pub fn get_permissions(&self) -> &str {
571 &self.permissions
572 }
573
574 pub fn is_stateless(&self) -> bool {
576 !self.stateful
577 }
578
579 pub fn validate_network_settings(&self) -> Result<()> {
581 let invalid = |reason: String| {
582 AlienError::new(ErrorData::InvalidResourceUpdate {
583 resource_id: self.id.clone(),
584 reason,
585 })
586 };
587 if self.egress.is_some()
588 && !self
589 .security
590 .as_ref()
591 .is_some_and(|security| security.profile == ContainerSecurityProfile::Restricted)
592 {
593 return Err(invalid(
594 "container egress internet requires security.profile restricted".into(),
595 ));
596 }
597 Ok(())
598 }
599
600 fn validate_public_endpoints(&self) -> Result<()> {
602 let mut endpoint_names = std::collections::HashSet::new();
603 let mut backend_ports = std::collections::HashSet::new();
604 let mut apex_endpoint_name: Option<&str> = None;
605
606 for endpoint in &self.public_endpoints {
607 endpoint.validate_for_resource(&self.id)?;
608
609 if !endpoint_names.insert(endpoint.name.as_str()) {
610 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
611 resource_id: self.id.clone(),
612 reason: format!("duplicate public endpoint name '{}'", endpoint.name),
613 }));
614 }
615
616 if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
617 if let Some(existing_name) = apex_endpoint_name {
618 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
619 resource_id: self.id.clone(),
620 reason: format!(
621 "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
622 existing_name
623 ),
624 }));
625 }
626 apex_endpoint_name = Some(endpoint.name.as_str());
627 }
628
629 backend_ports.insert(endpoint.port);
630
631 if !self.ports.iter().any(|port| port.port == endpoint.port) {
632 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
633 resource_id: self.id.clone(),
634 reason: format!(
635 "public endpoint '{}' references undeclared port {}",
636 endpoint.name, endpoint.port
637 ),
638 }));
639 }
640 }
641
642 if backend_ports.len() > 1 {
643 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
644 resource_id: self.id.clone(),
645 reason:
646 "public endpoints on one container must currently route to the same backend port"
647 .to_string(),
648 }));
649 }
650
651 Ok(())
652 }
653}
654
655fn default_commands_enabled() -> bool {
656 false
657}
658
659impl<S: container_builder::State> ContainerBuilder<S> {
660 pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
662 where
663 for<'a> &'a R: Into<ResourceRef>,
664 {
665 let resource_ref: ResourceRef = resource.into();
666 self.links.push(resource_ref);
667 self
668 }
669
670 pub fn port(mut self, port: u16) -> Self {
672 self.ports.push(ContainerPort { port });
673 self
674 }
675
676 pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
678 self.kubernetes_secret_mounts.push(mount);
679 self
680 }
681
682 pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
684 if !self.ports.iter().any(|p| p.port == endpoint.port) {
685 self.ports.push(ContainerPort {
686 port: endpoint.port,
687 });
688 }
689 self.public_endpoints.push(endpoint);
690 self
691 }
692}
693
694#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
696#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
697#[serde(rename_all = "camelCase")]
698pub enum ContainerStatus {
699 Pending,
701 Running,
703 Stopped,
705 Failing,
708}
709
710#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
712#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
713#[serde(rename_all = "camelCase")]
714pub struct ReplicaStatus {
715 pub replica_id: String,
717 pub ordinal: Option<u32>,
719 pub machine_id: Option<String>,
721 pub healthy: bool,
723 pub container_ip: Option<String>,
725}
726
727#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
734#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
735#[serde(rename_all = "camelCase", deny_unknown_fields)]
736pub struct ContainerTunnel {
737 pub port: u16,
739}
740
741#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
743#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
744#[serde(rename_all = "camelCase")]
745pub struct ContainerOutputs {
746 pub name: String,
748 pub status: ContainerStatus,
750 pub current_replicas: u32,
752 pub desired_replicas: u32,
754 pub internal_dns: String,
756 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
758 pub public_endpoints: HashMap<String, PublicEndpointOutput>,
759 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
761 pub internal_urls: HashMap<u16, String>,
762 pub replicas: Vec<ReplicaStatus>,
764 #[serde(default, skip_serializing_if = "Vec::is_empty")]
766 pub volumes: Vec<VolumeOutput>,
767 #[serde(default, skip_serializing_if = "Option::is_none")]
769 pub volume_backups: Option<VolumeBackupsStatus>,
770}
771
772#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
774#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
775#[serde(rename_all = "camelCase")]
776pub struct VolumeBackupsStatus {
777 pub state: VolumeBackupsState,
779 #[serde(skip_serializing_if = "Option::is_none")]
781 pub message: Option<String>,
782}
783
784#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
786#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
787#[serde(rename_all = "camelCase")]
788pub enum VolumeBackupsState {
789 Active,
791 Disabled,
793 SetupRequired,
797}
798
799#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
801#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
802#[serde(rename_all = "camelCase")]
803pub struct VolumeOutput {
804 pub ordinal: u32,
806 pub volume_id: String,
808 pub zone: String,
810 #[serde(skip_serializing_if = "Option::is_none")]
812 pub last_snapshot_id: Option<String>,
813 #[serde(skip_serializing_if = "Option::is_none")]
815 pub last_snapshot_at: Option<String>,
816 #[serde(skip_serializing_if = "Option::is_none")]
818 pub last_restore: Option<VolumeRestoreOutput>,
819}
820
821#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
823#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
824#[serde(rename_all = "camelCase")]
825pub struct VolumeRestoreOutput {
826 pub request_id: String,
828 pub snapshot_id: String,
830 pub replaced_volume_snapshot_id: String,
832 pub completed_at: String,
834}
835
836impl ResourceOutputsDefinition for ContainerOutputs {
837 fn get_resource_type(&self) -> ResourceType {
838 Container::RESOURCE_TYPE.clone()
839 }
840
841 fn as_any(&self) -> &dyn Any {
842 self
843 }
844
845 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
846 Box::new(self.clone())
847 }
848
849 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
850 other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
851 }
852
853 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
854 serde_json::to_value(self)
855 }
856}
857
858impl ResourceDefinition for Container {
859 fn get_resource_type(&self) -> ResourceType {
860 Self::RESOURCE_TYPE
861 }
862
863 fn id(&self) -> &str {
864 &self.id
865 }
866
867 fn replace_after_failed_create_is_safe(&self) -> bool {
868 !(self.stateful && self.persistent_storage.is_some())
870 }
871
872 fn get_dependencies(&self) -> Vec<ResourceRef> {
873 let mut deps = self.links.clone();
874 if let Some(key) = self
875 .persistent_storage
876 .as_ref()
877 .and_then(|storage| storage.encryption_key.as_ref())
878 {
879 deps.push(key.clone());
880 }
881 if let Some(cluster) = &self.cluster {
884 deps.push(ResourceRef::new(
885 ComputeCluster::RESOURCE_TYPE.clone(),
886 cluster,
887 ));
888 }
889 deps
890 }
891
892 fn get_permissions(&self) -> Option<&str> {
893 Some(&self.permissions)
894 }
895
896 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
897 let new_container = new_config
898 .as_any()
899 .downcast_ref::<Container>()
900 .ok_or_else(|| {
901 AlienError::new(ErrorData::UnexpectedResourceType {
902 resource_id: self.id.clone(),
903 expected: Self::RESOURCE_TYPE,
904 actual: new_config.get_resource_type(),
905 })
906 })?;
907
908 new_container.validate_public_endpoints()?;
910 new_container.validate_network_settings()?;
911
912 if self.id != new_container.id {
913 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
914 resource_id: self.id.clone(),
915 reason: "the 'id' field is immutable".to_string(),
916 }));
917 }
918
919 if self.cluster != new_container.cluster {
921 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
922 resource_id: self.id.clone(),
923 reason: "the 'cluster' field is immutable".to_string(),
924 }));
925 }
926
927 if self.stateful != new_container.stateful {
929 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
930 resource_id: self.id.clone(),
931 reason: "the 'stateful' field is immutable".to_string(),
932 }));
933 }
934
935 let old_key = self
936 .persistent_storage
937 .as_ref()
938 .and_then(|storage| storage.encryption_key.as_ref());
939 let new_key = new_container
940 .persistent_storage
941 .as_ref()
942 .and_then(|storage| storage.encryption_key.as_ref());
943 if old_key != new_key {
944 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
945 resource_id: self.id.clone(),
946 reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
947 }));
948 }
949
950 if self.ports != new_container.ports {
952 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
953 resource_id: self.id.clone(),
954 reason: "the 'ports' field is immutable".to_string(),
955 }));
956 }
957
958 if self.public_endpoints != new_container.public_endpoints {
959 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
960 resource_id: self.id.clone(),
961 reason: "the 'publicEndpoints' field is immutable".to_string(),
962 }));
963 }
964
965 if self.pool != new_container.pool {
967 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
968 resource_id: self.id.clone(),
969 reason: "the 'pool' field is immutable".to_string(),
970 }));
971 }
972
973 Ok(())
974 }
975
976 fn as_any(&self) -> &dyn Any {
977 self
978 }
979
980 fn as_any_mut(&mut self) -> &mut dyn Any {
981 self
982 }
983
984 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
985 Box::new(self.clone())
986 }
987
988 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
989 other.as_any().downcast_ref::<Container>() == Some(self)
990 }
991
992 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
993 serde_json::to_value(self)
994 }
995}
996
997#[cfg(test)]
998mod tests {
999 use super::*;
1000 use crate::resources::ExposeProtocol;
1001
1002 fn network_container() -> Container {
1003 Container::new("api".to_string())
1004 .code(ContainerCode::Image {
1005 image: "example:latest".into(),
1006 })
1007 .cpu(ResourceSpec {
1008 min: "1".into(),
1009 desired: "1".into(),
1010 })
1011 .memory(ResourceSpec {
1012 min: "512Mi".into(),
1013 desired: "512Mi".into(),
1014 })
1015 .permissions("execution".into())
1016 .public_endpoint(PublicEndpoint {
1017 name: "web".into(),
1018 port: 8080,
1019 protocol: ExposeProtocol::Http,
1020 host_label: None,
1021 wildcard_subdomains: false,
1022 })
1023 .build()
1024 }
1025
1026 #[test]
1027 fn internet_egress_requires_restricted_security_and_is_opt_in() {
1028 let mut container = network_container();
1029 assert!(serde_json::to_value(&container)
1030 .unwrap()
1031 .get("egress")
1032 .is_none());
1033 container.egress = Some(ContainerEgress::Internet);
1034 assert!(container.validate_update(&container).is_err());
1035 container.security = Some(ContainerSecurity {
1036 profile: ContainerSecurityProfile::Restricted,
1037 run_as_user: 65532,
1038 run_as_group: 65532,
1039 read_only_root_filesystem: true,
1040 });
1041 container.validate_update(&container).unwrap();
1042 assert_eq!(
1043 serde_json::to_value(&container).unwrap()["egress"],
1044 "internet"
1045 );
1046 }
1047
1048 #[test]
1049 fn test_container_creation_with_autoscaling() {
1050 let container = Container::new("api".to_string())
1051 .cluster("compute".to_string())
1052 .code(ContainerCode::Image {
1053 image: "myapp:latest".to_string(),
1054 })
1055 .cpu(ResourceSpec {
1056 min: "0.5".to_string(),
1057 desired: "1".to_string(),
1058 })
1059 .memory(ResourceSpec {
1060 min: "512Mi".to_string(),
1061 desired: "1Gi".to_string(),
1062 })
1063 .port(8080)
1064 .public_endpoint(PublicEndpoint {
1065 name: "api".to_string(),
1066 port: 8080,
1067 protocol: ExposeProtocol::Http,
1068 host_label: None,
1069 wildcard_subdomains: false,
1070 })
1071 .autoscaling(ContainerAutoscaling {
1072 min: 2,
1073 desired: 3,
1074 max: 10,
1075 target_cpu_percent: Some(70.0),
1076 target_memory_percent: None,
1077 target_http_in_flight_per_replica: Some(100),
1078 max_http_p95_latency_ms: None,
1079 })
1080 .permissions("container-execution".to_string())
1081 .build();
1082
1083 assert_eq!(container.id(), "api");
1084 assert_eq!(container.cluster, Some("compute".to_string()));
1085 assert!(!container.stateful);
1086 assert!(container.autoscaling.is_some());
1087 assert_eq!(container.ports.len(), 1);
1088 assert_eq!(container.ports[0].port, 8080);
1089 }
1090
1091 #[test]
1092 fn container_serializes_stop_grace_period_when_set() {
1093 let container = Container::new("api".to_string())
1094 .cluster("compute".to_string())
1095 .code(ContainerCode::Image {
1096 image: "myapp:latest".to_string(),
1097 })
1098 .cpu(ResourceSpec {
1099 min: "0.5".to_string(),
1100 desired: "1".to_string(),
1101 })
1102 .memory(ResourceSpec {
1103 min: "512Mi".to_string(),
1104 desired: "1Gi".to_string(),
1105 })
1106 .port(8080)
1107 .permissions("container-execution".to_string())
1108 .stop_grace_period_seconds(21_600)
1109 .build();
1110
1111 let json = serde_json::to_value(&container).expect("container should serialize");
1112 assert_eq!(json["stopGracePeriodSeconds"], 21_600);
1113 }
1114
1115 #[test]
1116 fn container_omits_stop_grace_period_when_absent() {
1117 let container = Container::new("api".to_string())
1118 .cluster("compute".to_string())
1119 .code(ContainerCode::Image {
1120 image: "myapp:latest".to_string(),
1121 })
1122 .cpu(ResourceSpec {
1123 min: "0.5".to_string(),
1124 desired: "1".to_string(),
1125 })
1126 .memory(ResourceSpec {
1127 min: "512Mi".to_string(),
1128 desired: "1Gi".to_string(),
1129 })
1130 .port(8080)
1131 .permissions("container-execution".to_string())
1132 .build();
1133
1134 let json = serde_json::to_value(&container).expect("container should serialize");
1135 assert!(json.get("stopGracePeriodSeconds").is_none());
1136 }
1137
1138 #[test]
1139 fn test_stateful_container_with_storage() {
1140 let container = Container::new("postgres".to_string())
1141 .cluster("compute".to_string())
1142 .code(ContainerCode::Image {
1143 image: "postgres:16".to_string(),
1144 })
1145 .cpu(ResourceSpec {
1146 min: "1".to_string(),
1147 desired: "2".to_string(),
1148 })
1149 .memory(ResourceSpec {
1150 min: "2Gi".to_string(),
1151 desired: "4Gi".to_string(),
1152 })
1153 .port(5432)
1154 .stateful(true)
1155 .replicas(1)
1156 .persistent_storage(PersistentStorage {
1157 encryption_key: None,
1158 size: "100Gi".to_string(),
1159 mount_path: "/var/lib/postgresql/data".to_string(),
1160 backups: VolumeBackups::default(),
1161 })
1162 .permissions("database".to_string())
1163 .build();
1164
1165 assert_eq!(container.id(), "postgres");
1166 assert!(container.stateful);
1167 assert!(container.replicas.is_some());
1168 assert!(container.persistent_storage.is_some());
1169 }
1170
1171 #[test]
1172 fn test_public_container() {
1173 let container = Container::new("frontend".to_string())
1174 .cluster("compute".to_string())
1175 .code(ContainerCode::Image {
1176 image: "frontend:latest".to_string(),
1177 })
1178 .cpu(ResourceSpec {
1179 min: "0.25".to_string(),
1180 desired: "0.5".to_string(),
1181 })
1182 .memory(ResourceSpec {
1183 min: "256Mi".to_string(),
1184 desired: "512Mi".to_string(),
1185 })
1186 .port(3000)
1187 .public_endpoint(PublicEndpoint {
1188 name: "web".to_string(),
1189 port: 3000,
1190 protocol: ExposeProtocol::Http,
1191 host_label: None,
1192 wildcard_subdomains: false,
1193 })
1194 .autoscaling(ContainerAutoscaling {
1195 min: 2,
1196 desired: 2,
1197 max: 20,
1198 target_cpu_percent: None,
1199 target_memory_percent: None,
1200 target_http_in_flight_per_replica: Some(50),
1201 max_http_p95_latency_ms: Some(100.0),
1202 })
1203 .health_check(HealthCheck {
1204 path: "/health".to_string(),
1205 port: None,
1206 method: "GET".to_string(),
1207 timeout_seconds: 1,
1208 failure_threshold: 3,
1209 })
1210 .permissions("frontend".to_string())
1211 .build();
1212
1213 assert_eq!(container.ports[0].port, 3000);
1214 assert_eq!(container.public_endpoints[0].name, "web");
1215 assert!(container.health_check.is_some());
1216 }
1217
1218 #[test]
1219 fn test_public_container_endpoint_options() {
1220 let container = Container::new("router".to_string())
1221 .cluster("compute".to_string())
1222 .code(ContainerCode::Image {
1223 image: "router:latest".to_string(),
1224 })
1225 .cpu(ResourceSpec {
1226 min: "0.25".to_string(),
1227 desired: "0.5".to_string(),
1228 })
1229 .memory(ResourceSpec {
1230 min: "256Mi".to_string(),
1231 desired: "512Mi".to_string(),
1232 })
1233 .public_endpoint(PublicEndpoint {
1234 name: "gateway".to_string(),
1235 port: 8080,
1236 protocol: ExposeProtocol::Http,
1237 host_label: Some("gateway".to_string()),
1238 wildcard_subdomains: true,
1239 })
1240 .permissions("router".to_string())
1241 .build();
1242
1243 assert!(container.validate_public_endpoints().is_ok());
1244 assert_eq!(container.ports.len(), 1);
1245 assert_eq!(container.public_endpoints.len(), 1);
1246 assert_eq!(
1247 container.public_endpoints[0].host_label.as_deref(),
1248 Some("gateway")
1249 );
1250 assert!(container.public_endpoints[0].wildcard_subdomains);
1251 }
1252
1253 #[test]
1254 fn test_public_container_rejects_invalid_host_label() {
1255 let container = Container::new("router".to_string())
1256 .cluster("compute".to_string())
1257 .code(ContainerCode::Image {
1258 image: "router:latest".to_string(),
1259 })
1260 .cpu(ResourceSpec {
1261 min: "0.25".to_string(),
1262 desired: "0.5".to_string(),
1263 })
1264 .memory(ResourceSpec {
1265 min: "256Mi".to_string(),
1266 desired: "512Mi".to_string(),
1267 })
1268 .public_endpoint(PublicEndpoint {
1269 name: "gateway".to_string(),
1270 port: 8080,
1271 protocol: ExposeProtocol::Http,
1272 host_label: Some("bad.label".to_string()),
1273 wildcard_subdomains: true,
1274 })
1275 .permissions("router".to_string())
1276 .build();
1277
1278 assert!(container.validate_public_endpoints().is_err());
1279 }
1280
1281 #[test]
1282 fn test_container_with_links() {
1283 use crate::Storage;
1284
1285 let storage = Storage::new("data".to_string()).build();
1286
1287 let container = Container::new("worker".to_string())
1288 .cluster("compute".to_string())
1289 .code(ContainerCode::Image {
1290 image: "worker:latest".to_string(),
1291 })
1292 .cpu(ResourceSpec {
1293 min: "0.5".to_string(),
1294 desired: "1".to_string(),
1295 })
1296 .memory(ResourceSpec {
1297 min: "512Mi".to_string(),
1298 desired: "1Gi".to_string(),
1299 })
1300 .port(8080)
1301 .replicas(3)
1302 .link(&storage)
1303 .permissions("worker".to_string())
1304 .build();
1305
1306 let deps = container.get_dependencies();
1308 assert_eq!(deps.len(), 2);
1309 }
1310
1311 #[test]
1312 fn test_container_validate_update_immutable_cluster() {
1313 let container1 = Container::new("api".to_string())
1314 .cluster("cluster-1".to_string())
1315 .code(ContainerCode::Image {
1316 image: "myapp:v1".to_string(),
1317 })
1318 .cpu(ResourceSpec {
1319 min: "0.5".to_string(),
1320 desired: "1".to_string(),
1321 })
1322 .memory(ResourceSpec {
1323 min: "512Mi".to_string(),
1324 desired: "1Gi".to_string(),
1325 })
1326 .port(8080)
1327 .replicas(2)
1328 .permissions("execution".to_string())
1329 .build();
1330
1331 let container2 = Container::new("api".to_string())
1332 .cluster("cluster-2".to_string()) .code(ContainerCode::Image {
1334 image: "myapp:v2".to_string(),
1335 })
1336 .cpu(ResourceSpec {
1337 min: "0.5".to_string(),
1338 desired: "1".to_string(),
1339 })
1340 .memory(ResourceSpec {
1341 min: "512Mi".to_string(),
1342 desired: "1Gi".to_string(),
1343 })
1344 .port(8080)
1345 .replicas(2)
1346 .permissions("execution".to_string())
1347 .build();
1348
1349 let result = container1.validate_update(&container2);
1350 assert!(result.is_err());
1351 }
1352
1353 #[test]
1354 fn test_container_validate_update_allowed_changes() {
1355 let container1 = Container::new("api".to_string())
1356 .cluster("compute".to_string())
1357 .code(ContainerCode::Image {
1358 image: "myapp:v1".to_string(),
1359 })
1360 .cpu(ResourceSpec {
1361 min: "0.5".to_string(),
1362 desired: "1".to_string(),
1363 })
1364 .memory(ResourceSpec {
1365 min: "512Mi".to_string(),
1366 desired: "1Gi".to_string(),
1367 })
1368 .port(8080)
1369 .replicas(2)
1370 .permissions("execution".to_string())
1371 .build();
1372
1373 let container2 = Container::new("api".to_string())
1374 .cluster("compute".to_string())
1375 .code(ContainerCode::Image {
1376 image: "myapp:v2".to_string(), })
1378 .cpu(ResourceSpec {
1379 min: "1".to_string(), desired: "2".to_string(),
1381 })
1382 .memory(ResourceSpec {
1383 min: "1Gi".to_string(),
1384 desired: "2Gi".to_string(),
1385 })
1386 .port(8080)
1387 .replicas(5) .permissions("execution".to_string())
1389 .build();
1390
1391 let result = container1.validate_update(&container2);
1392 assert!(result.is_ok());
1393 }
1394
1395 #[test]
1396 fn test_container_serialization() {
1397 let container = Container::new("test".to_string())
1398 .cluster("compute".to_string())
1399 .code(ContainerCode::Image {
1400 image: "test:latest".to_string(),
1401 })
1402 .cpu(ResourceSpec {
1403 min: "0.5".to_string(),
1404 desired: "1".to_string(),
1405 })
1406 .memory(ResourceSpec {
1407 min: "512Mi".to_string(),
1408 desired: "1Gi".to_string(),
1409 })
1410 .port(8080)
1411 .replicas(1)
1412 .permissions("test".to_string())
1413 .build();
1414
1415 let json = serde_json::to_string(&container).unwrap();
1416 let deserialized: Container = serde_json::from_str(&json).unwrap();
1417 assert_eq!(container, deserialized);
1418 }
1419
1420 #[test]
1421 fn test_container_multi_endpoint_validation() {
1422 let container = Container::new("multi-tcp".to_string())
1423 .cluster("compute".to_string())
1424 .code(ContainerCode::Image {
1425 image: "test:latest".to_string(),
1426 })
1427 .cpu(ResourceSpec {
1428 min: "1".to_string(),
1429 desired: "1".to_string(),
1430 })
1431 .memory(ResourceSpec {
1432 min: "1Gi".to_string(),
1433 desired: "1Gi".to_string(),
1434 })
1435 .port(8080)
1436 .public_endpoint(PublicEndpoint {
1437 name: "api".to_string(),
1438 port: 8080,
1439 protocol: ExposeProtocol::Http,
1440 host_label: None,
1441 wildcard_subdomains: false,
1442 })
1443 .public_endpoint(PublicEndpoint {
1444 name: "wildcard".to_string(),
1445 port: 8080,
1446 protocol: ExposeProtocol::Http,
1447 host_label: Some("wildcard".to_string()),
1448 wildcard_subdomains: true,
1449 })
1450 .replicas(1)
1451 .permissions("test".to_string())
1452 .build();
1453
1454 assert!(container.validate_public_endpoints().is_ok());
1455
1456 let invalid_container = Container::new("multi-http".to_string())
1457 .cluster("compute".to_string())
1458 .code(ContainerCode::Image {
1459 image: "test:latest".to_string(),
1460 })
1461 .cpu(ResourceSpec {
1462 min: "1".to_string(),
1463 desired: "1".to_string(),
1464 })
1465 .memory(ResourceSpec {
1466 min: "1Gi".to_string(),
1467 desired: "1Gi".to_string(),
1468 })
1469 .port(8080)
1470 .port(9090)
1471 .public_endpoint(PublicEndpoint {
1472 name: "api".to_string(),
1473 port: 8080,
1474 protocol: ExposeProtocol::Http,
1475 host_label: None,
1476 wildcard_subdomains: false,
1477 })
1478 .public_endpoint(PublicEndpoint {
1479 name: "admin".to_string(),
1480 port: 9090,
1481 protocol: ExposeProtocol::Http,
1482 host_label: None,
1483 wildcard_subdomains: false,
1484 })
1485 .replicas(1)
1486 .permissions("test".to_string())
1487 .build();
1488
1489 assert!(invalid_container.validate_public_endpoints().is_err());
1490 }
1491
1492 #[test]
1493 fn container_rejects_multiple_apex_public_endpoints() {
1494 let container = Container::new("apex-container".to_string())
1495 .cluster("compute".to_string())
1496 .code(ContainerCode::Image {
1497 image: "test:latest".to_string(),
1498 })
1499 .cpu(ResourceSpec {
1500 min: "1".to_string(),
1501 desired: "1".to_string(),
1502 })
1503 .memory(ResourceSpec {
1504 min: "1Gi".to_string(),
1505 desired: "1Gi".to_string(),
1506 })
1507 .port(8080)
1508 .public_endpoint(PublicEndpoint {
1509 name: "web".to_string(),
1510 port: 8080,
1511 protocol: ExposeProtocol::Http,
1512 host_label: Some(APEX_HOST_LABEL.to_string()),
1513 wildcard_subdomains: false,
1514 })
1515 .public_endpoint(PublicEndpoint {
1516 name: "admin".to_string(),
1517 port: 8080,
1518 protocol: ExposeProtocol::Http,
1519 host_label: Some(APEX_HOST_LABEL.to_string()),
1520 wildcard_subdomains: false,
1521 })
1522 .replicas(1)
1523 .permissions("test".to_string())
1524 .build();
1525
1526 assert!(container.validate_public_endpoints().is_err());
1527 }
1528
1529 #[test]
1530 fn test_container_empty_ports_validation() {
1531 let container = Container::new("no-ports".to_string())
1532 .cluster("compute".to_string())
1533 .code(ContainerCode::Image {
1534 image: "test:latest".to_string(),
1535 })
1536 .cpu(ResourceSpec {
1537 min: "1".to_string(),
1538 desired: "1".to_string(),
1539 })
1540 .memory(ResourceSpec {
1541 min: "1Gi".to_string(),
1542 desired: "1Gi".to_string(),
1543 })
1544 .replicas(1)
1545 .permissions("test".to_string())
1546 .build();
1547
1548 assert!(container.validate_public_endpoints().is_ok());
1549 }
1550
1551 #[test]
1552 fn test_container_commands_enabled_defaults_false() {
1553 let container = Container::new("no-commands".to_string())
1554 .cluster("compute".to_string())
1555 .code(ContainerCode::Image {
1556 image: "test:latest".to_string(),
1557 })
1558 .cpu(ResourceSpec {
1559 min: "0.5".to_string(),
1560 desired: "1".to_string(),
1561 })
1562 .memory(ResourceSpec {
1563 min: "512Mi".to_string(),
1564 desired: "1Gi".to_string(),
1565 })
1566 .port(8080)
1567 .permissions("test".to_string())
1568 .build();
1569
1570 assert!(!container.commands_enabled);
1571 }
1572
1573 #[test]
1574 fn test_container_commands_enabled_builder() {
1575 let container = Container::new("cmd-container".to_string())
1576 .cluster("compute".to_string())
1577 .code(ContainerCode::Image {
1578 image: "test:latest".to_string(),
1579 })
1580 .cpu(ResourceSpec {
1581 min: "0.5".to_string(),
1582 desired: "1".to_string(),
1583 })
1584 .memory(ResourceSpec {
1585 min: "512Mi".to_string(),
1586 desired: "1Gi".to_string(),
1587 })
1588 .port(8080)
1589 .permissions("test".to_string())
1590 .commands_enabled(true)
1591 .build();
1592
1593 assert!(container.commands_enabled);
1594 }
1595
1596 #[test]
1597 fn test_container_commands_enabled_serializes_camel_case() {
1598 let container = Container::new("cmd-container".to_string())
1599 .cluster("compute".to_string())
1600 .code(ContainerCode::Image {
1601 image: "test:latest".to_string(),
1602 })
1603 .cpu(ResourceSpec {
1604 min: "0.5".to_string(),
1605 desired: "1".to_string(),
1606 })
1607 .memory(ResourceSpec {
1608 min: "512Mi".to_string(),
1609 desired: "1Gi".to_string(),
1610 })
1611 .port(8080)
1612 .permissions("test".to_string())
1613 .commands_enabled(true)
1614 .build();
1615
1616 let json = serde_json::to_value(&container).expect("container should serialize");
1617 assert_eq!(json["commandsEnabled"], true);
1618
1619 let deserialized: Container =
1620 serde_json::from_value(json).expect("container should deserialize");
1621 assert_eq!(deserialized, container);
1622 }
1623}