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")]
62pub struct ContainerGpuSpec {
63 #[serde(rename = "type")]
65 pub gpu_type: String,
66 pub count: u32,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
73#[serde(rename_all = "camelCase")]
74pub struct PersistentStorage {
75 pub size: String,
77 pub mount_path: String,
79 #[serde(default)]
81 pub backups: VolumeBackups,
82}
83
84pub const VOLUME_BACKUP_INTERVAL_HOURS: [u32; 7] = [1, 2, 4, 6, 8, 12, 24];
86
87pub const VOLUME_BACKUP_MAX_SNAPSHOTS: u32 = 450;
91
92pub const VOLUME_BACKUP_MAX_RETENTION_DAYS: u32 = 365;
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
109#[serde(rename_all = "camelCase")]
110pub struct VolumeBackups {
111 #[serde(default = "default_volume_backups_enabled")]
113 pub enabled: bool,
114 #[serde(default = "default_volume_backup_interval_hours")]
116 pub interval_hours: u32,
117 #[serde(default = "default_volume_backup_retention_days")]
119 pub retention_days: u32,
120}
121
122fn default_volume_backups_enabled() -> bool {
123 true
124}
125
126fn default_volume_backup_interval_hours() -> u32 {
127 24
128}
129
130fn default_volume_backup_retention_days() -> u32 {
131 7
132}
133
134impl Default for VolumeBackups {
135 fn default() -> Self {
136 Self {
137 enabled: default_volume_backups_enabled(),
138 interval_hours: default_volume_backup_interval_hours(),
139 retention_days: default_volume_backup_retention_days(),
140 }
141 }
142}
143
144impl VolumeBackups {
145 pub fn disabled() -> Self {
147 Self {
148 enabled: false,
149 ..Self::default()
150 }
151 }
152
153 pub fn validation_error(&self) -> Option<String> {
155 if !self.enabled {
156 return None;
157 }
158 if !VOLUME_BACKUP_INTERVAL_HOURS.contains(&self.interval_hours) {
159 return Some(format!(
160 "backup intervalHours must be one of {VOLUME_BACKUP_INTERVAL_HOURS:?}, got {}",
161 self.interval_hours
162 ));
163 }
164 if self.retention_days == 0 {
165 return Some("backup retentionDays must be at least 1".to_string());
166 }
167 if self.retention_days > VOLUME_BACKUP_MAX_RETENTION_DAYS {
168 return Some(format!(
169 "backup retentionDays must be at most {VOLUME_BACKUP_MAX_RETENTION_DAYS}, got {}",
170 self.retention_days
171 ));
172 }
173 let snapshots = self.retention_days * 24 / self.interval_hours;
174 if snapshots > VOLUME_BACKUP_MAX_SNAPSHOTS {
175 return Some(format!(
176 "backups every {} hours for {} days keep {snapshots} snapshots per volume; \
177 the most is {VOLUME_BACKUP_MAX_SNAPSHOTS}",
178 self.interval_hours, self.retention_days
179 ));
180 }
181 None
182 }
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
189#[serde(rename_all = "camelCase")]
190pub struct KubernetesSecretMount {
191 pub secret_name: String,
193 pub mount_path: String,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
200#[serde(rename_all = "camelCase")]
201pub struct KubernetesHttpProbe {
202 pub path: String,
204 pub port: u16,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
210#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
211#[serde(rename_all = "camelCase")]
212pub enum ContainerSecurityProfile {
213 Restricted,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
219#[serde(rename_all = "camelCase")]
220pub struct ContainerSecurity {
221 pub profile: ContainerSecurityProfile,
223 pub run_as_user: i64,
225 pub run_as_group: i64,
227 pub read_only_root_filesystem: bool,
229}
230
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
233#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
234#[serde(rename_all = "camelCase")]
235pub struct ContainerAutoscaling {
236 pub min: u32,
238 pub desired: u32,
240 pub max: u32,
242 #[serde(skip_serializing_if = "Option::is_none")]
244 pub target_cpu_percent: Option<f64>,
245 #[serde(skip_serializing_if = "Option::is_none")]
247 pub target_memory_percent: Option<f64>,
248 #[serde(skip_serializing_if = "Option::is_none")]
250 pub target_http_in_flight_per_replica: Option<u32>,
251 #[serde(skip_serializing_if = "Option::is_none")]
253 pub max_http_p95_latency_ms: Option<f64>,
254}
255
256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
259#[serde(rename_all = "camelCase")]
260pub struct HealthCheck {
261 #[serde(default = "default_health_path")]
263 pub path: String,
264 #[serde(skip_serializing_if = "Option::is_none")]
266 pub port: Option<u16>,
267 #[serde(default = "default_health_method")]
269 pub method: String,
270 #[serde(default = "default_timeout_seconds")]
272 pub timeout_seconds: u32,
273 #[serde(default = "default_failure_threshold")]
275 pub failure_threshold: u32,
276}
277
278fn default_health_path() -> String {
279 "/health".to_string()
280}
281
282fn default_health_method() -> String {
283 "GET".to_string()
284}
285
286fn default_timeout_seconds() -> u32 {
287 1
288}
289
290fn default_failure_threshold() -> u32 {
291 3
292}
293
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
296#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
297#[serde(rename_all = "camelCase")]
298pub struct ContainerPort {
299 pub port: u16,
301}
302
303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
342#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
343#[serde(rename_all = "camelCase", deny_unknown_fields)]
344#[builder(start_fn = new)]
345pub struct Container {
346 #[builder(start_fn)]
349 pub id: String,
350
351 #[builder(field)]
353 pub links: Vec<ResourceRef>,
354
355 #[builder(field)]
357 pub ports: Vec<ContainerPort>,
358
359 #[builder(field)]
361 #[serde(default, skip_serializing_if = "Vec::is_empty")]
362 pub kubernetes_secret_mounts: Vec<KubernetesSecretMount>,
363
364 #[builder(field)]
366 #[serde(default, skip_serializing_if = "Vec::is_empty")]
367 pub public_endpoints: Vec<PublicEndpoint>,
368
369 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub tunnel: Option<ContainerTunnel>,
374
375 #[serde(skip_serializing_if = "Option::is_none")]
377 pub kubernetes_liveness_probe: Option<KubernetesHttpProbe>,
378
379 #[serde(skip_serializing_if = "Option::is_none")]
381 pub kubernetes_readiness_probe: Option<KubernetesHttpProbe>,
382
383 #[serde(skip_serializing_if = "Option::is_none")]
385 pub security: Option<ContainerSecurity>,
386
387 #[serde(skip_serializing_if = "Option::is_none")]
390 pub cluster: Option<String>,
391
392 pub code: ContainerCode,
394
395 pub cpu: ResourceSpec,
397
398 pub memory: ResourceSpec,
400
401 #[serde(skip_serializing_if = "Option::is_none")]
403 pub gpu: Option<ContainerGpuSpec>,
404
405 #[serde(skip_serializing_if = "Option::is_none")]
407 pub ephemeral_storage: Option<String>,
408
409 #[serde(skip_serializing_if = "Option::is_none")]
411 pub persistent_storage: Option<PersistentStorage>,
412
413 #[serde(skip_serializing_if = "Option::is_none")]
415 pub replicas: Option<u32>,
416
417 #[serde(skip_serializing_if = "Option::is_none")]
419 pub autoscaling: Option<ContainerAutoscaling>,
420
421 #[builder(default = false)]
423 #[serde(default)]
424 pub stateful: bool,
425
426 #[builder(default)]
428 #[serde(default)]
429 pub environment: HashMap<String, String>,
430
431 #[serde(skip_serializing_if = "Option::is_none")]
434 pub pool: Option<String>,
435
436 pub permissions: String,
438
439 #[serde(skip_serializing_if = "Option::is_none")]
441 pub health_check: Option<HealthCheck>,
442
443 #[serde(skip_serializing_if = "Option::is_none")]
445 pub command: Option<Vec<String>>,
446
447 #[builder(default = default_commands_enabled())]
451 #[serde(default = "default_commands_enabled")]
452 #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
453 pub commands_enabled: bool,
454
455 #[serde(skip_serializing_if = "Option::is_none")]
460 #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
461 pub stop_grace_period_seconds: Option<u32>,
462}
463
464impl Container {
465 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
467
468 pub fn id(&self) -> &str {
470 &self.id
471 }
472
473 pub fn get_permissions(&self) -> &str {
475 &self.permissions
476 }
477
478 pub fn is_stateless(&self) -> bool {
480 !self.stateful
481 }
482
483 fn validate_public_endpoints(&self) -> Result<()> {
485 let mut endpoint_names = std::collections::HashSet::new();
486 let mut backend_ports = std::collections::HashSet::new();
487 let mut apex_endpoint_name: Option<&str> = None;
488
489 for endpoint in &self.public_endpoints {
490 endpoint.validate_for_resource(&self.id)?;
491
492 if !endpoint_names.insert(endpoint.name.as_str()) {
493 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
494 resource_id: self.id.clone(),
495 reason: format!("duplicate public endpoint name '{}'", endpoint.name),
496 }));
497 }
498
499 if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
500 if let Some(existing_name) = apex_endpoint_name {
501 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
502 resource_id: self.id.clone(),
503 reason: format!(
504 "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
505 existing_name
506 ),
507 }));
508 }
509 apex_endpoint_name = Some(endpoint.name.as_str());
510 }
511
512 backend_ports.insert(endpoint.port);
513
514 if !self.ports.iter().any(|port| port.port == endpoint.port) {
515 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
516 resource_id: self.id.clone(),
517 reason: format!(
518 "public endpoint '{}' references undeclared port {}",
519 endpoint.name, endpoint.port
520 ),
521 }));
522 }
523 }
524
525 if backend_ports.len() > 1 {
526 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
527 resource_id: self.id.clone(),
528 reason:
529 "public endpoints on one container must currently route to the same backend port"
530 .to_string(),
531 }));
532 }
533
534 Ok(())
535 }
536}
537
538fn default_commands_enabled() -> bool {
539 false
540}
541
542impl<S: container_builder::State> ContainerBuilder<S> {
543 pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
545 where
546 for<'a> &'a R: Into<ResourceRef>,
547 {
548 let resource_ref: ResourceRef = resource.into();
549 self.links.push(resource_ref);
550 self
551 }
552
553 pub fn port(mut self, port: u16) -> Self {
555 self.ports.push(ContainerPort { port });
556 self
557 }
558
559 pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
561 self.kubernetes_secret_mounts.push(mount);
562 self
563 }
564
565 pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
567 if !self.ports.iter().any(|p| p.port == endpoint.port) {
568 self.ports.push(ContainerPort {
569 port: endpoint.port,
570 });
571 }
572 self.public_endpoints.push(endpoint);
573 self
574 }
575}
576
577#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
579#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
580#[serde(rename_all = "camelCase")]
581pub enum ContainerStatus {
582 Pending,
584 Running,
586 Stopped,
588 Failing,
591}
592
593#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
595#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
596#[serde(rename_all = "camelCase")]
597pub struct ReplicaStatus {
598 pub replica_id: String,
600 pub ordinal: Option<u32>,
602 pub machine_id: Option<String>,
604 pub healthy: bool,
606 pub container_ip: Option<String>,
608}
609
610#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
617#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
618#[serde(rename_all = "camelCase", deny_unknown_fields)]
619pub struct ContainerTunnel {
620 pub port: u16,
622}
623
624#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
626#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
627#[serde(rename_all = "camelCase")]
628pub struct ContainerOutputs {
629 pub name: String,
631 pub status: ContainerStatus,
633 pub current_replicas: u32,
635 pub desired_replicas: u32,
637 pub internal_dns: String,
639 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
641 pub public_endpoints: HashMap<String, PublicEndpointOutput>,
642 pub replicas: Vec<ReplicaStatus>,
644 #[serde(default, skip_serializing_if = "Vec::is_empty")]
646 pub volumes: Vec<VolumeOutput>,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub volume_backups: Option<VolumeBackupsStatus>,
650}
651
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
654#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
655#[serde(rename_all = "camelCase")]
656pub struct VolumeBackupsStatus {
657 pub state: VolumeBackupsState,
659 #[serde(skip_serializing_if = "Option::is_none")]
661 pub message: Option<String>,
662}
663
664#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
666#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
667#[serde(rename_all = "camelCase")]
668pub enum VolumeBackupsState {
669 Active,
671 Disabled,
673 SetupRequired,
677}
678
679#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
681#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
682#[serde(rename_all = "camelCase")]
683pub struct VolumeOutput {
684 pub ordinal: u32,
686 pub volume_id: String,
688 pub zone: String,
690 #[serde(skip_serializing_if = "Option::is_none")]
692 pub last_snapshot_id: Option<String>,
693 #[serde(skip_serializing_if = "Option::is_none")]
695 pub last_snapshot_at: Option<String>,
696 #[serde(skip_serializing_if = "Option::is_none")]
698 pub last_restore: Option<VolumeRestoreOutput>,
699}
700
701#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
703#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
704#[serde(rename_all = "camelCase")]
705pub struct VolumeRestoreOutput {
706 pub request_id: String,
708 pub snapshot_id: String,
710 pub replaced_volume_snapshot_id: String,
712 pub completed_at: String,
714}
715
716impl ResourceOutputsDefinition for ContainerOutputs {
717 fn get_resource_type(&self) -> ResourceType {
718 Container::RESOURCE_TYPE.clone()
719 }
720
721 fn as_any(&self) -> &dyn Any {
722 self
723 }
724
725 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
726 Box::new(self.clone())
727 }
728
729 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
730 other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
731 }
732
733 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
734 serde_json::to_value(self)
735 }
736}
737
738impl ResourceDefinition for Container {
739 fn get_resource_type(&self) -> ResourceType {
740 Self::RESOURCE_TYPE
741 }
742
743 fn id(&self) -> &str {
744 &self.id
745 }
746
747 fn get_dependencies(&self) -> Vec<ResourceRef> {
748 let mut deps = self.links.clone();
749 if let Some(cluster) = &self.cluster {
752 deps.push(ResourceRef::new(
753 ComputeCluster::RESOURCE_TYPE.clone(),
754 cluster,
755 ));
756 }
757 deps
758 }
759
760 fn get_permissions(&self) -> Option<&str> {
761 Some(&self.permissions)
762 }
763
764 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
765 let new_container = new_config
766 .as_any()
767 .downcast_ref::<Container>()
768 .ok_or_else(|| {
769 AlienError::new(ErrorData::UnexpectedResourceType {
770 resource_id: self.id.clone(),
771 expected: Self::RESOURCE_TYPE,
772 actual: new_config.get_resource_type(),
773 })
774 })?;
775
776 new_container.validate_public_endpoints()?;
778
779 if self.id != new_container.id {
780 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
781 resource_id: self.id.clone(),
782 reason: "the 'id' field is immutable".to_string(),
783 }));
784 }
785
786 if self.cluster != new_container.cluster {
788 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
789 resource_id: self.id.clone(),
790 reason: "the 'cluster' field is immutable".to_string(),
791 }));
792 }
793
794 if self.stateful != new_container.stateful {
796 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
797 resource_id: self.id.clone(),
798 reason: "the 'stateful' field is immutable".to_string(),
799 }));
800 }
801
802 if self.ports != new_container.ports {
804 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
805 resource_id: self.id.clone(),
806 reason: "the 'ports' field is immutable".to_string(),
807 }));
808 }
809
810 if self.public_endpoints != new_container.public_endpoints {
811 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
812 resource_id: self.id.clone(),
813 reason: "the 'publicEndpoints' field is immutable".to_string(),
814 }));
815 }
816
817 if self.pool != new_container.pool {
819 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
820 resource_id: self.id.clone(),
821 reason: "the 'pool' field is immutable".to_string(),
822 }));
823 }
824
825 Ok(())
826 }
827
828 fn as_any(&self) -> &dyn Any {
829 self
830 }
831
832 fn as_any_mut(&mut self) -> &mut dyn Any {
833 self
834 }
835
836 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
837 Box::new(self.clone())
838 }
839
840 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
841 other.as_any().downcast_ref::<Container>() == Some(self)
842 }
843
844 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
845 serde_json::to_value(self)
846 }
847}
848
849#[cfg(test)]
850mod tests {
851 use super::*;
852 use crate::resources::ExposeProtocol;
853
854 #[test]
855 fn test_container_creation_with_autoscaling() {
856 let container = Container::new("api".to_string())
857 .cluster("compute".to_string())
858 .code(ContainerCode::Image {
859 image: "myapp:latest".to_string(),
860 })
861 .cpu(ResourceSpec {
862 min: "0.5".to_string(),
863 desired: "1".to_string(),
864 })
865 .memory(ResourceSpec {
866 min: "512Mi".to_string(),
867 desired: "1Gi".to_string(),
868 })
869 .port(8080)
870 .public_endpoint(PublicEndpoint {
871 name: "api".to_string(),
872 port: 8080,
873 protocol: ExposeProtocol::Http,
874 host_label: None,
875 wildcard_subdomains: false,
876 })
877 .autoscaling(ContainerAutoscaling {
878 min: 2,
879 desired: 3,
880 max: 10,
881 target_cpu_percent: Some(70.0),
882 target_memory_percent: None,
883 target_http_in_flight_per_replica: Some(100),
884 max_http_p95_latency_ms: None,
885 })
886 .permissions("container-execution".to_string())
887 .build();
888
889 assert_eq!(container.id(), "api");
890 assert_eq!(container.cluster, Some("compute".to_string()));
891 assert!(!container.stateful);
892 assert!(container.autoscaling.is_some());
893 assert_eq!(container.ports.len(), 1);
894 assert_eq!(container.ports[0].port, 8080);
895 }
896
897 #[test]
898 fn container_serializes_stop_grace_period_when_set() {
899 let container = Container::new("api".to_string())
900 .cluster("compute".to_string())
901 .code(ContainerCode::Image {
902 image: "myapp:latest".to_string(),
903 })
904 .cpu(ResourceSpec {
905 min: "0.5".to_string(),
906 desired: "1".to_string(),
907 })
908 .memory(ResourceSpec {
909 min: "512Mi".to_string(),
910 desired: "1Gi".to_string(),
911 })
912 .port(8080)
913 .permissions("container-execution".to_string())
914 .stop_grace_period_seconds(21_600)
915 .build();
916
917 let json = serde_json::to_value(&container).expect("container should serialize");
918 assert_eq!(json["stopGracePeriodSeconds"], 21_600);
919 }
920
921 #[test]
922 fn container_omits_stop_grace_period_when_absent() {
923 let container = Container::new("api".to_string())
924 .cluster("compute".to_string())
925 .code(ContainerCode::Image {
926 image: "myapp:latest".to_string(),
927 })
928 .cpu(ResourceSpec {
929 min: "0.5".to_string(),
930 desired: "1".to_string(),
931 })
932 .memory(ResourceSpec {
933 min: "512Mi".to_string(),
934 desired: "1Gi".to_string(),
935 })
936 .port(8080)
937 .permissions("container-execution".to_string())
938 .build();
939
940 let json = serde_json::to_value(&container).expect("container should serialize");
941 assert!(json.get("stopGracePeriodSeconds").is_none());
942 }
943
944 #[test]
945 fn test_stateful_container_with_storage() {
946 let container = Container::new("postgres".to_string())
947 .cluster("compute".to_string())
948 .code(ContainerCode::Image {
949 image: "postgres:16".to_string(),
950 })
951 .cpu(ResourceSpec {
952 min: "1".to_string(),
953 desired: "2".to_string(),
954 })
955 .memory(ResourceSpec {
956 min: "2Gi".to_string(),
957 desired: "4Gi".to_string(),
958 })
959 .port(5432)
960 .stateful(true)
961 .replicas(1)
962 .persistent_storage(PersistentStorage {
963 size: "100Gi".to_string(),
964 mount_path: "/var/lib/postgresql/data".to_string(),
965 backups: VolumeBackups::default(),
966 })
967 .permissions("database".to_string())
968 .build();
969
970 assert_eq!(container.id(), "postgres");
971 assert!(container.stateful);
972 assert!(container.replicas.is_some());
973 assert!(container.persistent_storage.is_some());
974 }
975
976 #[test]
977 fn test_public_container() {
978 let container = Container::new("frontend".to_string())
979 .cluster("compute".to_string())
980 .code(ContainerCode::Image {
981 image: "frontend:latest".to_string(),
982 })
983 .cpu(ResourceSpec {
984 min: "0.25".to_string(),
985 desired: "0.5".to_string(),
986 })
987 .memory(ResourceSpec {
988 min: "256Mi".to_string(),
989 desired: "512Mi".to_string(),
990 })
991 .port(3000)
992 .public_endpoint(PublicEndpoint {
993 name: "web".to_string(),
994 port: 3000,
995 protocol: ExposeProtocol::Http,
996 host_label: None,
997 wildcard_subdomains: false,
998 })
999 .autoscaling(ContainerAutoscaling {
1000 min: 2,
1001 desired: 2,
1002 max: 20,
1003 target_cpu_percent: None,
1004 target_memory_percent: None,
1005 target_http_in_flight_per_replica: Some(50),
1006 max_http_p95_latency_ms: Some(100.0),
1007 })
1008 .health_check(HealthCheck {
1009 path: "/health".to_string(),
1010 port: None,
1011 method: "GET".to_string(),
1012 timeout_seconds: 1,
1013 failure_threshold: 3,
1014 })
1015 .permissions("frontend".to_string())
1016 .build();
1017
1018 assert_eq!(container.ports[0].port, 3000);
1019 assert_eq!(container.public_endpoints[0].name, "web");
1020 assert!(container.health_check.is_some());
1021 }
1022
1023 #[test]
1024 fn test_public_container_endpoint_options() {
1025 let container = Container::new("router".to_string())
1026 .cluster("compute".to_string())
1027 .code(ContainerCode::Image {
1028 image: "router:latest".to_string(),
1029 })
1030 .cpu(ResourceSpec {
1031 min: "0.25".to_string(),
1032 desired: "0.5".to_string(),
1033 })
1034 .memory(ResourceSpec {
1035 min: "256Mi".to_string(),
1036 desired: "512Mi".to_string(),
1037 })
1038 .public_endpoint(PublicEndpoint {
1039 name: "gateway".to_string(),
1040 port: 8080,
1041 protocol: ExposeProtocol::Http,
1042 host_label: Some("gateway".to_string()),
1043 wildcard_subdomains: true,
1044 })
1045 .permissions("router".to_string())
1046 .build();
1047
1048 assert!(container.validate_public_endpoints().is_ok());
1049 assert_eq!(container.ports.len(), 1);
1050 assert_eq!(container.public_endpoints.len(), 1);
1051 assert_eq!(
1052 container.public_endpoints[0].host_label.as_deref(),
1053 Some("gateway")
1054 );
1055 assert!(container.public_endpoints[0].wildcard_subdomains);
1056 }
1057
1058 #[test]
1059 fn test_public_container_rejects_invalid_host_label() {
1060 let container = Container::new("router".to_string())
1061 .cluster("compute".to_string())
1062 .code(ContainerCode::Image {
1063 image: "router:latest".to_string(),
1064 })
1065 .cpu(ResourceSpec {
1066 min: "0.25".to_string(),
1067 desired: "0.5".to_string(),
1068 })
1069 .memory(ResourceSpec {
1070 min: "256Mi".to_string(),
1071 desired: "512Mi".to_string(),
1072 })
1073 .public_endpoint(PublicEndpoint {
1074 name: "gateway".to_string(),
1075 port: 8080,
1076 protocol: ExposeProtocol::Http,
1077 host_label: Some("bad.label".to_string()),
1078 wildcard_subdomains: true,
1079 })
1080 .permissions("router".to_string())
1081 .build();
1082
1083 assert!(container.validate_public_endpoints().is_err());
1084 }
1085
1086 #[test]
1087 fn test_container_with_links() {
1088 use crate::Storage;
1089
1090 let storage = Storage::new("data".to_string()).build();
1091
1092 let container = Container::new("worker".to_string())
1093 .cluster("compute".to_string())
1094 .code(ContainerCode::Image {
1095 image: "worker:latest".to_string(),
1096 })
1097 .cpu(ResourceSpec {
1098 min: "0.5".to_string(),
1099 desired: "1".to_string(),
1100 })
1101 .memory(ResourceSpec {
1102 min: "512Mi".to_string(),
1103 desired: "1Gi".to_string(),
1104 })
1105 .port(8080)
1106 .replicas(3)
1107 .link(&storage)
1108 .permissions("worker".to_string())
1109 .build();
1110
1111 let deps = container.get_dependencies();
1113 assert_eq!(deps.len(), 2);
1114 }
1115
1116 #[test]
1117 fn test_container_validate_update_immutable_cluster() {
1118 let container1 = Container::new("api".to_string())
1119 .cluster("cluster-1".to_string())
1120 .code(ContainerCode::Image {
1121 image: "myapp:v1".to_string(),
1122 })
1123 .cpu(ResourceSpec {
1124 min: "0.5".to_string(),
1125 desired: "1".to_string(),
1126 })
1127 .memory(ResourceSpec {
1128 min: "512Mi".to_string(),
1129 desired: "1Gi".to_string(),
1130 })
1131 .port(8080)
1132 .replicas(2)
1133 .permissions("execution".to_string())
1134 .build();
1135
1136 let container2 = Container::new("api".to_string())
1137 .cluster("cluster-2".to_string()) .code(ContainerCode::Image {
1139 image: "myapp:v2".to_string(),
1140 })
1141 .cpu(ResourceSpec {
1142 min: "0.5".to_string(),
1143 desired: "1".to_string(),
1144 })
1145 .memory(ResourceSpec {
1146 min: "512Mi".to_string(),
1147 desired: "1Gi".to_string(),
1148 })
1149 .port(8080)
1150 .replicas(2)
1151 .permissions("execution".to_string())
1152 .build();
1153
1154 let result = container1.validate_update(&container2);
1155 assert!(result.is_err());
1156 }
1157
1158 #[test]
1159 fn test_container_validate_update_allowed_changes() {
1160 let container1 = Container::new("api".to_string())
1161 .cluster("compute".to_string())
1162 .code(ContainerCode::Image {
1163 image: "myapp:v1".to_string(),
1164 })
1165 .cpu(ResourceSpec {
1166 min: "0.5".to_string(),
1167 desired: "1".to_string(),
1168 })
1169 .memory(ResourceSpec {
1170 min: "512Mi".to_string(),
1171 desired: "1Gi".to_string(),
1172 })
1173 .port(8080)
1174 .replicas(2)
1175 .permissions("execution".to_string())
1176 .build();
1177
1178 let container2 = Container::new("api".to_string())
1179 .cluster("compute".to_string())
1180 .code(ContainerCode::Image {
1181 image: "myapp:v2".to_string(), })
1183 .cpu(ResourceSpec {
1184 min: "1".to_string(), desired: "2".to_string(),
1186 })
1187 .memory(ResourceSpec {
1188 min: "1Gi".to_string(),
1189 desired: "2Gi".to_string(),
1190 })
1191 .port(8080)
1192 .replicas(5) .permissions("execution".to_string())
1194 .build();
1195
1196 let result = container1.validate_update(&container2);
1197 assert!(result.is_ok());
1198 }
1199
1200 #[test]
1201 fn test_container_serialization() {
1202 let container = Container::new("test".to_string())
1203 .cluster("compute".to_string())
1204 .code(ContainerCode::Image {
1205 image: "test:latest".to_string(),
1206 })
1207 .cpu(ResourceSpec {
1208 min: "0.5".to_string(),
1209 desired: "1".to_string(),
1210 })
1211 .memory(ResourceSpec {
1212 min: "512Mi".to_string(),
1213 desired: "1Gi".to_string(),
1214 })
1215 .port(8080)
1216 .replicas(1)
1217 .permissions("test".to_string())
1218 .build();
1219
1220 let json = serde_json::to_string(&container).unwrap();
1221 let deserialized: Container = serde_json::from_str(&json).unwrap();
1222 assert_eq!(container, deserialized);
1223 }
1224
1225 #[test]
1226 fn test_container_multi_endpoint_validation() {
1227 let container = Container::new("multi-tcp".to_string())
1228 .cluster("compute".to_string())
1229 .code(ContainerCode::Image {
1230 image: "test:latest".to_string(),
1231 })
1232 .cpu(ResourceSpec {
1233 min: "1".to_string(),
1234 desired: "1".to_string(),
1235 })
1236 .memory(ResourceSpec {
1237 min: "1Gi".to_string(),
1238 desired: "1Gi".to_string(),
1239 })
1240 .port(8080)
1241 .public_endpoint(PublicEndpoint {
1242 name: "api".to_string(),
1243 port: 8080,
1244 protocol: ExposeProtocol::Http,
1245 host_label: None,
1246 wildcard_subdomains: false,
1247 })
1248 .public_endpoint(PublicEndpoint {
1249 name: "wildcard".to_string(),
1250 port: 8080,
1251 protocol: ExposeProtocol::Http,
1252 host_label: Some("wildcard".to_string()),
1253 wildcard_subdomains: true,
1254 })
1255 .replicas(1)
1256 .permissions("test".to_string())
1257 .build();
1258
1259 assert!(container.validate_public_endpoints().is_ok());
1260
1261 let invalid_container = Container::new("multi-http".to_string())
1262 .cluster("compute".to_string())
1263 .code(ContainerCode::Image {
1264 image: "test:latest".to_string(),
1265 })
1266 .cpu(ResourceSpec {
1267 min: "1".to_string(),
1268 desired: "1".to_string(),
1269 })
1270 .memory(ResourceSpec {
1271 min: "1Gi".to_string(),
1272 desired: "1Gi".to_string(),
1273 })
1274 .port(8080)
1275 .port(9090)
1276 .public_endpoint(PublicEndpoint {
1277 name: "api".to_string(),
1278 port: 8080,
1279 protocol: ExposeProtocol::Http,
1280 host_label: None,
1281 wildcard_subdomains: false,
1282 })
1283 .public_endpoint(PublicEndpoint {
1284 name: "admin".to_string(),
1285 port: 9090,
1286 protocol: ExposeProtocol::Http,
1287 host_label: None,
1288 wildcard_subdomains: false,
1289 })
1290 .replicas(1)
1291 .permissions("test".to_string())
1292 .build();
1293
1294 assert!(invalid_container.validate_public_endpoints().is_err());
1295 }
1296
1297 #[test]
1298 fn container_rejects_multiple_apex_public_endpoints() {
1299 let container = Container::new("apex-container".to_string())
1300 .cluster("compute".to_string())
1301 .code(ContainerCode::Image {
1302 image: "test:latest".to_string(),
1303 })
1304 .cpu(ResourceSpec {
1305 min: "1".to_string(),
1306 desired: "1".to_string(),
1307 })
1308 .memory(ResourceSpec {
1309 min: "1Gi".to_string(),
1310 desired: "1Gi".to_string(),
1311 })
1312 .port(8080)
1313 .public_endpoint(PublicEndpoint {
1314 name: "web".to_string(),
1315 port: 8080,
1316 protocol: ExposeProtocol::Http,
1317 host_label: Some(APEX_HOST_LABEL.to_string()),
1318 wildcard_subdomains: false,
1319 })
1320 .public_endpoint(PublicEndpoint {
1321 name: "admin".to_string(),
1322 port: 8080,
1323 protocol: ExposeProtocol::Http,
1324 host_label: Some(APEX_HOST_LABEL.to_string()),
1325 wildcard_subdomains: false,
1326 })
1327 .replicas(1)
1328 .permissions("test".to_string())
1329 .build();
1330
1331 assert!(container.validate_public_endpoints().is_err());
1332 }
1333
1334 #[test]
1335 fn test_container_empty_ports_validation() {
1336 let container = Container::new("no-ports".to_string())
1337 .cluster("compute".to_string())
1338 .code(ContainerCode::Image {
1339 image: "test:latest".to_string(),
1340 })
1341 .cpu(ResourceSpec {
1342 min: "1".to_string(),
1343 desired: "1".to_string(),
1344 })
1345 .memory(ResourceSpec {
1346 min: "1Gi".to_string(),
1347 desired: "1Gi".to_string(),
1348 })
1349 .replicas(1)
1350 .permissions("test".to_string())
1351 .build();
1352
1353 assert!(container.validate_public_endpoints().is_ok());
1354 }
1355
1356 #[test]
1357 fn test_container_commands_enabled_defaults_false() {
1358 let container = Container::new("no-commands".to_string())
1359 .cluster("compute".to_string())
1360 .code(ContainerCode::Image {
1361 image: "test:latest".to_string(),
1362 })
1363 .cpu(ResourceSpec {
1364 min: "0.5".to_string(),
1365 desired: "1".to_string(),
1366 })
1367 .memory(ResourceSpec {
1368 min: "512Mi".to_string(),
1369 desired: "1Gi".to_string(),
1370 })
1371 .port(8080)
1372 .permissions("test".to_string())
1373 .build();
1374
1375 assert!(!container.commands_enabled);
1376 }
1377
1378 #[test]
1379 fn test_container_commands_enabled_builder() {
1380 let container = Container::new("cmd-container".to_string())
1381 .cluster("compute".to_string())
1382 .code(ContainerCode::Image {
1383 image: "test:latest".to_string(),
1384 })
1385 .cpu(ResourceSpec {
1386 min: "0.5".to_string(),
1387 desired: "1".to_string(),
1388 })
1389 .memory(ResourceSpec {
1390 min: "512Mi".to_string(),
1391 desired: "1Gi".to_string(),
1392 })
1393 .port(8080)
1394 .permissions("test".to_string())
1395 .commands_enabled(true)
1396 .build();
1397
1398 assert!(container.commands_enabled);
1399 }
1400
1401 #[test]
1402 fn test_container_commands_enabled_serializes_camel_case() {
1403 let container = Container::new("cmd-container".to_string())
1404 .cluster("compute".to_string())
1405 .code(ContainerCode::Image {
1406 image: "test:latest".to_string(),
1407 })
1408 .cpu(ResourceSpec {
1409 min: "0.5".to_string(),
1410 desired: "1".to_string(),
1411 })
1412 .memory(ResourceSpec {
1413 min: "512Mi".to_string(),
1414 desired: "1Gi".to_string(),
1415 })
1416 .port(8080)
1417 .permissions("test".to_string())
1418 .commands_enabled(true)
1419 .build();
1420
1421 let json = serde_json::to_value(&container).expect("container should serialize");
1422 assert_eq!(json["commandsEnabled"], true);
1423
1424 let deserialized: Container =
1425 serde_json::from_value(json).expect("container should deserialize");
1426 assert_eq!(deserialized, container);
1427 }
1428}