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)]
271#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
272#[serde(rename_all = "camelCase")]
273pub enum ContainerSecurityProfile {
274 Restricted,
277 Unrestricted,
279}
280
281#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
297#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
298#[serde(
299 rename_all = "camelCase",
300 from = "ContainerSecurityWire",
301 into = "ContainerSecurityWire"
302)]
303pub struct ContainerSecurity {
304 pub profile: ContainerSecurityProfile,
306 pub run_as_user: Option<i64>,
309 pub run_as_group: Option<i64>,
311 pub read_only_root_filesystem: Option<bool>,
313 #[serde(default)]
315 pub writable_paths: Vec<String>,
316}
317
318const PREVIOUS_RELEASE_ID: i64 = 65532;
321
322#[derive(Serialize, Deserialize)]
324#[serde(rename_all = "camelCase")]
325struct ContainerSecurityWire {
326 profile: ContainerSecurityProfile,
327 #[serde(default)]
328 run_as_user: Option<i64>,
329 #[serde(default)]
330 run_as_group: Option<i64>,
331 #[serde(default)]
332 read_only_root_filesystem: Option<bool>,
333 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
335 unrestricted: bool,
336 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
337 run_as_user_unset: bool,
338 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
339 run_as_group_unset: bool,
340 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
341 read_only_root_filesystem_unset: bool,
342 #[serde(default, skip_serializing_if = "Vec::is_empty")]
343 writable_paths: Vec<String>,
344}
345
346impl From<ContainerSecurity> for ContainerSecurityWire {
347 fn from(security: ContainerSecurity) -> Self {
348 let unrestricted = security.profile == ContainerSecurityProfile::Unrestricted;
349 Self {
350 profile: ContainerSecurityProfile::Restricted,
351 unrestricted,
352 run_as_user_unset: security.run_as_user.is_none(),
353 run_as_user: Some(security.run_as_user.unwrap_or(PREVIOUS_RELEASE_ID)),
354 run_as_group_unset: security.run_as_group.is_none(),
355 run_as_group: Some(security.run_as_group.unwrap_or(PREVIOUS_RELEASE_ID)),
356 read_only_root_filesystem_unset: security.read_only_root_filesystem.is_none(),
357 read_only_root_filesystem: Some(
358 security.read_only_root_filesystem.unwrap_or(!unrestricted),
359 ),
360 writable_paths: security.writable_paths,
361 }
362 }
363}
364
365impl From<ContainerSecurityWire> for ContainerSecurity {
366 fn from(wire: ContainerSecurityWire) -> Self {
367 let profile = if wire.unrestricted {
368 ContainerSecurityProfile::Unrestricted
369 } else {
370 wire.profile
371 };
372 Self {
373 profile,
374 run_as_user: wire.run_as_user.filter(|_| !wire.run_as_user_unset),
375 run_as_group: wire.run_as_group.filter(|_| !wire.run_as_group_unset),
376 read_only_root_filesystem: wire
377 .read_only_root_filesystem
378 .filter(|_| !wire.read_only_root_filesystem_unset),
379 writable_paths: wire.writable_paths,
380 }
381 }
382}
383
384impl ContainerSecurity {
385 pub fn is_restricted(security: Option<&ContainerSecurity>) -> bool {
388 security.is_some_and(|security| security.profile == ContainerSecurityProfile::Restricted)
389 }
390}
391
392#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
394#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
395#[serde(rename_all = "camelCase")]
396pub struct ContainerAutoscaling {
397 pub min: u32,
399 pub desired: u32,
401 pub max: u32,
403 #[serde(skip_serializing_if = "Option::is_none")]
405 pub target_cpu_percent: Option<f64>,
406 #[serde(skip_serializing_if = "Option::is_none")]
408 pub target_memory_percent: Option<f64>,
409 #[serde(skip_serializing_if = "Option::is_none")]
411 pub target_http_in_flight_per_replica: Option<u32>,
412 #[serde(skip_serializing_if = "Option::is_none")]
414 pub max_http_p95_latency_ms: Option<f64>,
415}
416
417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
419#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
420#[serde(rename_all = "camelCase")]
421pub struct HealthCheck {
422 #[serde(default = "default_health_path")]
424 pub path: String,
425 #[serde(skip_serializing_if = "Option::is_none")]
427 pub port: Option<u16>,
428 #[serde(default = "default_health_method")]
430 pub method: String,
431 #[serde(default = "default_timeout_seconds")]
433 pub timeout_seconds: u32,
434 #[serde(default = "default_failure_threshold")]
436 pub failure_threshold: u32,
437 #[serde(default, skip_serializing_if = "Option::is_none")]
441 pub startup_timeout_seconds: Option<u32>,
442}
443
444impl Default for HealthCheck {
445 fn default() -> Self {
447 HealthCheck {
448 path: default_health_path(),
449 port: None,
450 method: default_health_method(),
451 timeout_seconds: default_timeout_seconds(),
452 failure_threshold: default_failure_threshold(),
453 startup_timeout_seconds: None,
454 }
455 }
456}
457
458fn default_health_path() -> String {
459 "/health".to_string()
460}
461
462fn default_health_method() -> String {
463 "GET".to_string()
464}
465
466fn default_timeout_seconds() -> u32 {
467 1
468}
469
470fn default_failure_threshold() -> u32 {
471 3
472}
473
474#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
477#[serde(rename_all = "camelCase")]
478pub struct ContainerPort {
479 pub port: u16,
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
488#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
489#[serde(rename_all = "camelCase")]
490pub enum ContainerEgress {
491 Internet,
495}
496
497#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
536#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
537#[serde(rename_all = "camelCase", deny_unknown_fields)]
538#[builder(start_fn = new)]
539pub struct Container {
540 #[builder(start_fn)]
543 pub id: String,
544
545 #[builder(field)]
547 pub links: Vec<ResourceRef>,
548
549 #[builder(field)]
551 pub ports: Vec<ContainerPort>,
552
553 #[builder(field)]
555 #[serde(default, skip_serializing_if = "Vec::is_empty")]
556 pub kubernetes_secret_mounts: Vec<KubernetesSecretMount>,
557
558 #[builder(field)]
560 #[serde(default, skip_serializing_if = "Vec::is_empty")]
561 pub public_endpoints: Vec<PublicEndpoint>,
562
563 #[serde(default, skip_serializing_if = "Option::is_none")]
565 pub egress: Option<ContainerEgress>,
566
567 #[serde(default, rename = "tunnel", skip_serializing)]
570 #[cfg_attr(feature = "openapi", schema(ignore))]
571 #[builder(skip)]
572 retired_tunnel: Option<serde_json::Value>,
573
574 #[serde(skip_serializing_if = "Option::is_none")]
576 pub kubernetes_liveness_probe: Option<KubernetesHttpProbe>,
577
578 #[serde(skip_serializing_if = "Option::is_none")]
580 pub kubernetes_readiness_probe: Option<KubernetesHttpProbe>,
581
582 #[serde(skip_serializing_if = "Option::is_none")]
586 pub security: Option<ContainerSecurity>,
587
588 #[serde(skip_serializing_if = "Option::is_none")]
591 pub cluster: Option<String>,
592
593 pub code: ContainerCode,
595
596 pub cpu: ResourceSpec,
598
599 pub memory: ResourceSpec,
601
602 #[serde(default, skip_serializing_if = "Option::is_none")]
604 pub resource_choices: Option<ContainerResourceChoices>,
605
606 #[serde(skip_serializing_if = "Option::is_none")]
608 pub gpu: Option<ContainerGpuSpec>,
609
610 #[serde(skip_serializing_if = "Option::is_none")]
612 pub ephemeral_storage: Option<String>,
613
614 #[serde(skip_serializing_if = "Option::is_none")]
616 pub persistent_storage: Option<PersistentStorage>,
617
618 #[serde(skip_serializing_if = "Option::is_none")]
620 pub replicas: Option<u32>,
621
622 #[serde(skip_serializing_if = "Option::is_none")]
624 pub autoscaling: Option<ContainerAutoscaling>,
625
626 #[builder(default = false)]
628 #[serde(default)]
629 pub stateful: bool,
630
631 #[builder(default)]
633 #[serde(default)]
634 pub environment: HashMap<String, String>,
635
636 #[serde(skip_serializing_if = "Option::is_none")]
639 pub pool: Option<String>,
640
641 pub permissions: String,
643
644 #[serde(skip_serializing_if = "Option::is_none")]
646 pub health_check: Option<HealthCheck>,
647
648 #[serde(skip_serializing_if = "Option::is_none")]
650 pub command: Option<Vec<String>>,
651
652 #[builder(default = default_commands_enabled())]
656 #[serde(default = "default_commands_enabled")]
657 #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
658 pub commands_enabled: bool,
659
660 #[builder(default)]
666 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
667 pub commands_capability_file: bool,
668
669 #[serde(skip_serializing_if = "Option::is_none")]
674 #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
675 pub stop_grace_period_seconds: Option<u32>,
676
677 #[serde(default, skip_serializing_if = "Option::is_none")]
681 pub priority: Option<WorkloadPriority>,
682}
683
684impl Container {
685 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
687
688 pub fn id(&self) -> &str {
690 &self.id
691 }
692
693 pub fn get_permissions(&self) -> &str {
695 &self.permissions
696 }
697
698 pub fn is_stateless(&self) -> bool {
700 !self.stateful
701 }
702
703 pub fn validate_network_settings(&self) -> Result<()> {
705 let invalid = |reason: String| {
706 AlienError::new(ErrorData::InvalidResourceUpdate {
707 resource_id: self.id.clone(),
708 reason,
709 })
710 };
711 if self.egress.is_some() && !ContainerSecurity::is_restricted(self.security.as_ref()) {
712 return Err(invalid(
713 "container egress internet requires security.profile restricted".into(),
714 ));
715 }
716 Ok(())
717 }
718
719 fn validate_public_endpoints(&self) -> Result<()> {
721 let mut endpoint_names = std::collections::HashSet::new();
722 let mut backend_ports = std::collections::HashSet::new();
723 let mut apex_endpoint_name: Option<&str> = None;
724
725 for endpoint in &self.public_endpoints {
726 endpoint.validate_for_resource(&self.id)?;
727
728 if !endpoint_names.insert(endpoint.name.as_str()) {
729 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
730 resource_id: self.id.clone(),
731 reason: format!("duplicate public endpoint name '{}'", endpoint.name),
732 }));
733 }
734
735 if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
736 if let Some(existing_name) = apex_endpoint_name {
737 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
738 resource_id: self.id.clone(),
739 reason: format!(
740 "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
741 existing_name
742 ),
743 }));
744 }
745 apex_endpoint_name = Some(endpoint.name.as_str());
746 }
747
748 backend_ports.insert(endpoint.port);
749
750 if !self.ports.iter().any(|port| port.port == endpoint.port) {
751 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
752 resource_id: self.id.clone(),
753 reason: format!(
754 "public endpoint '{}' references undeclared port {}",
755 endpoint.name, endpoint.port
756 ),
757 }));
758 }
759 }
760
761 if backend_ports.len() > 1 {
762 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
763 resource_id: self.id.clone(),
764 reason:
765 "public endpoints on one container must currently route to the same backend port"
766 .to_string(),
767 }));
768 }
769
770 Ok(())
771 }
772}
773
774fn default_commands_enabled() -> bool {
775 false
776}
777
778impl<S: container_builder::State> ContainerBuilder<S> {
779 pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
781 where
782 for<'a> &'a R: Into<ResourceRef>,
783 {
784 let resource_ref: ResourceRef = resource.into();
785 self.links.push(resource_ref);
786 self
787 }
788
789 pub fn port(mut self, port: u16) -> Self {
791 self.ports.push(ContainerPort { port });
792 self
793 }
794
795 pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
797 self.kubernetes_secret_mounts.push(mount);
798 self
799 }
800
801 pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
803 if !self.ports.iter().any(|p| p.port == endpoint.port) {
804 self.ports.push(ContainerPort {
805 port: endpoint.port,
806 });
807 }
808 self.public_endpoints.push(endpoint);
809 self
810 }
811}
812
813#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
815#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
816#[serde(rename_all = "camelCase")]
817pub enum ContainerStatus {
818 Pending,
820 Running,
822 Stopped,
824 Failing,
827}
828
829#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
831#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
832#[serde(rename_all = "camelCase")]
833pub struct ReplicaStatus {
834 pub replica_id: String,
836 pub ordinal: Option<u32>,
838 pub machine_id: Option<String>,
840 pub healthy: bool,
842 pub container_ip: Option<String>,
844}
845
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
848#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
849#[serde(rename_all = "camelCase")]
850pub struct ContainerOutputs {
851 pub name: String,
853 pub status: ContainerStatus,
855 pub current_replicas: u32,
857 pub desired_replicas: u32,
859 pub internal_dns: String,
864 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
866 pub public_endpoints: HashMap<String, PublicEndpointOutput>,
867 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
869 pub internal_urls: HashMap<u16, String>,
870 #[serde(default, skip_serializing_if = "Option::is_none")]
875 #[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
876 pub link_address: Option<std::net::Ipv4Addr>,
877 pub replicas: Vec<ReplicaStatus>,
879 #[serde(default, skip_serializing_if = "Vec::is_empty")]
881 pub volumes: Vec<VolumeOutput>,
882 #[serde(default, skip_serializing_if = "Option::is_none")]
884 pub volume_backups: Option<VolumeBackupsStatus>,
885}
886
887#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
889#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
890#[serde(rename_all = "camelCase")]
891pub struct VolumeBackupsStatus {
892 pub state: VolumeBackupsState,
894 #[serde(skip_serializing_if = "Option::is_none")]
896 pub message: Option<String>,
897}
898
899#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
901#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
902#[serde(rename_all = "camelCase")]
903pub enum VolumeBackupsState {
904 Active,
906 Disabled,
908 SetupRequired,
912}
913
914#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
916#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
917#[serde(rename_all = "camelCase")]
918pub struct VolumeOutput {
919 pub ordinal: u32,
921 pub volume_id: String,
923 pub zone: String,
925 #[serde(skip_serializing_if = "Option::is_none")]
927 pub last_snapshot_id: Option<String>,
928 #[serde(skip_serializing_if = "Option::is_none")]
930 pub last_snapshot_at: Option<String>,
931 #[serde(skip_serializing_if = "Option::is_none")]
933 pub last_restore: Option<VolumeRestoreOutput>,
934}
935
936#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
938#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
939#[serde(rename_all = "camelCase")]
940pub struct VolumeRestoreOutput {
941 pub request_id: String,
943 pub snapshot_id: String,
945 pub replaced_volume_snapshot_id: String,
947 pub completed_at: String,
949}
950
951impl ResourceOutputsDefinition for ContainerOutputs {
952 fn get_resource_type(&self) -> ResourceType {
953 Container::RESOURCE_TYPE.clone()
954 }
955
956 fn as_any(&self) -> &dyn Any {
957 self
958 }
959
960 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
961 Box::new(self.clone())
962 }
963
964 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
965 other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
966 }
967
968 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
969 serde_json::to_value(self)
970 }
971}
972
973impl ResourceDefinition for Container {
974 fn get_resource_type(&self) -> ResourceType {
975 Self::RESOURCE_TYPE
976 }
977
978 fn id(&self) -> &str {
979 &self.id
980 }
981
982 fn replace_after_failed_create_is_safe(&self) -> bool {
983 !(self.stateful && self.persistent_storage.is_some())
985 }
986
987 fn get_dependencies(&self) -> Vec<ResourceRef> {
988 let mut deps = self.links.clone();
989 if let Some(key) = self
990 .persistent_storage
991 .as_ref()
992 .and_then(|storage| storage.encryption_key.as_ref())
993 {
994 deps.push(key.clone());
995 }
996 if let Some(cluster) = &self.cluster {
999 deps.push(ResourceRef::new(
1000 ComputeCluster::RESOURCE_TYPE.clone(),
1001 cluster,
1002 ));
1003 }
1004 deps
1005 }
1006
1007 fn get_permissions(&self) -> Option<&str> {
1008 Some(&self.permissions)
1009 }
1010
1011 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1012 let new_container = new_config
1013 .as_any()
1014 .downcast_ref::<Container>()
1015 .ok_or_else(|| {
1016 AlienError::new(ErrorData::UnexpectedResourceType {
1017 resource_id: self.id.clone(),
1018 expected: Self::RESOURCE_TYPE,
1019 actual: new_config.get_resource_type(),
1020 })
1021 })?;
1022
1023 new_container.validate_public_endpoints()?;
1025 new_container.validate_network_settings()?;
1026
1027 if self.id != new_container.id {
1028 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1029 resource_id: self.id.clone(),
1030 reason: "the 'id' field is immutable".to_string(),
1031 }));
1032 }
1033
1034 if self.cluster != new_container.cluster {
1036 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1037 resource_id: self.id.clone(),
1038 reason: "the 'cluster' field is immutable".to_string(),
1039 }));
1040 }
1041
1042 if self.stateful != new_container.stateful {
1044 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1045 resource_id: self.id.clone(),
1046 reason: "the 'stateful' field is immutable".to_string(),
1047 }));
1048 }
1049
1050 let old_key = self
1051 .persistent_storage
1052 .as_ref()
1053 .and_then(|storage| storage.encryption_key.as_ref());
1054 let new_key = new_container
1055 .persistent_storage
1056 .as_ref()
1057 .and_then(|storage| storage.encryption_key.as_ref());
1058 if old_key != new_key {
1059 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1060 resource_id: self.id.clone(),
1061 reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
1062 }));
1063 }
1064
1065 if self.ports != new_container.ports {
1067 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1068 resource_id: self.id.clone(),
1069 reason: "the 'ports' field is immutable".to_string(),
1070 }));
1071 }
1072
1073 if self.public_endpoints != new_container.public_endpoints {
1074 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1075 resource_id: self.id.clone(),
1076 reason: "the 'publicEndpoints' field is immutable".to_string(),
1077 }));
1078 }
1079
1080 if self.pool != new_container.pool {
1082 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1083 resource_id: self.id.clone(),
1084 reason: "the 'pool' field is immutable".to_string(),
1085 }));
1086 }
1087
1088 Ok(())
1089 }
1090
1091 fn as_any(&self) -> &dyn Any {
1092 self
1093 }
1094
1095 fn as_any_mut(&mut self) -> &mut dyn Any {
1096 self
1097 }
1098
1099 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1100 Box::new(self.clone())
1101 }
1102
1103 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1104 other.as_any().downcast_ref::<Container>() == Some(self)
1105 }
1106
1107 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1108 serde_json::to_value(self)
1109 }
1110}
1111
1112#[cfg(test)]
1113mod tests {
1114 #[derive(Debug, serde::Deserialize)]
1115 #[serde(rename_all = "camelCase")]
1116 enum PreviousProfile {
1117 Restricted,
1118 }
1119
1120 #[derive(Debug, serde::Deserialize)]
1124 #[serde(rename_all = "camelCase")]
1125 #[allow(dead_code)]
1126 struct PreviousContainerSecurity {
1127 profile: PreviousProfile,
1128 run_as_user: i64,
1129 run_as_group: i64,
1130 read_only_root_filesystem: bool,
1131 }
1132
1133 #[test]
1134 fn written_security_parses_with_the_previous_release_struct() {
1135 let defaults = ContainerSecurity {
1136 profile: ContainerSecurityProfile::Restricted,
1137 run_as_user: None,
1138 run_as_group: None,
1139 read_only_root_filesystem: None,
1140 writable_paths: Vec::new(),
1141 };
1142 let explicit = ContainerSecurity {
1143 profile: ContainerSecurityProfile::Unrestricted,
1144 run_as_user: Some(70),
1145 run_as_group: Some(71),
1146 read_only_root_filesystem: Some(false),
1147 writable_paths: vec!["/data".to_string()],
1148 };
1149 let unrestricted_defaults = ContainerSecurity {
1150 profile: ContainerSecurityProfile::Unrestricted,
1151 ..defaults.clone()
1152 };
1153 let explicit_zero = ContainerSecurity {
1154 profile: ContainerSecurityProfile::Restricted,
1155 run_as_user: Some(0),
1156 run_as_group: None,
1157 read_only_root_filesystem: Some(false),
1158 writable_paths: Vec::new(),
1159 };
1160 for security in [defaults, explicit, unrestricted_defaults, explicit_zero] {
1161 let json = serde_json::to_value(&security).unwrap();
1162 serde_json::from_value::<PreviousContainerSecurity>(json.clone())
1163 .unwrap_or_else(|error| panic!("previous release cannot read {json}: {error}"));
1164 let back: ContainerSecurity = serde_json::from_value(json).unwrap();
1166 assert_eq!(back, security);
1167 }
1168 }
1169
1170 #[test]
1175 fn unrestricted_opt_out_reads_as_restricted_with_the_previous_release_struct() {
1176 let security = ContainerSecurity {
1177 profile: ContainerSecurityProfile::Unrestricted,
1178 run_as_user: Some(0),
1179 run_as_group: Some(0),
1180 read_only_root_filesystem: Some(false),
1181 writable_paths: Vec::new(),
1182 };
1183 let json = serde_json::to_value(&security).unwrap();
1184 assert_eq!(json["profile"], "restricted");
1185 assert_eq!(json["unrestricted"], true);
1186 let previous: PreviousContainerSecurity = serde_json::from_value(json.clone()).unwrap();
1187 assert!(matches!(previous.profile, PreviousProfile::Restricted));
1188 let back: ContainerSecurity = serde_json::from_value(json).unwrap();
1189 assert_eq!(back, security);
1190 }
1191
1192 #[test]
1195 fn security_without_a_profile_fails_to_parse() {
1196 assert!(
1197 serde_json::from_str::<ContainerSecurity>(r#"{"writablePaths":["/cache"]}"#).is_err()
1198 );
1199 assert!(serde_json::from_str::<ContainerSecurity>("{}").is_err());
1200 }
1201
1202 #[test]
1203 fn security_reads_accept_the_plain_unrestricted_profile() {
1204 let security: ContainerSecurity =
1205 serde_json::from_str(r#"{"profile":"unrestricted"}"#).unwrap();
1206 assert_eq!(security.profile, ContainerSecurityProfile::Unrestricted);
1207 }
1208
1209 #[test]
1210 fn security_reads_tolerate_omitted_fields() {
1211 let security: ContainerSecurity =
1212 serde_json::from_str(r#"{"profile":"restricted"}"#).unwrap();
1213 assert_eq!(security.run_as_user, None);
1214 assert_eq!(security.read_only_root_filesystem, None);
1215 }
1216
1217 use super::*;
1218 use crate::resources::ExposeProtocol;
1219
1220 fn network_container() -> Container {
1221 Container::new("api".to_string())
1222 .code(ContainerCode::Image {
1223 image: "example:latest".into(),
1224 })
1225 .cpu(ResourceSpec {
1226 min: "1".into(),
1227 desired: "1".into(),
1228 })
1229 .memory(ResourceSpec {
1230 min: "512Mi".into(),
1231 desired: "512Mi".into(),
1232 })
1233 .permissions("execution".into())
1234 .public_endpoint(PublicEndpoint {
1235 name: "web".into(),
1236 port: 8080,
1237 protocol: ExposeProtocol::Http,
1238 host_label: None,
1239 wildcard_subdomains: false,
1240 })
1241 .build()
1242 }
1243
1244 #[test]
1245 fn a_saved_container_with_the_retired_tunnel_field_still_loads() {
1246 let saved = serde_json::json!({
1247 "id": "api",
1248 "code": {"type": "image", "image": "example/api:1"},
1249 "cpu": {"min": "0.5", "desired": "0.5"},
1250 "memory": {"min": "256Mi", "desired": "256Mi"},
1251 "permissions": "execution",
1252 "links": [], "ports": [],
1253 "tunnel": {"port": 8080}
1254 });
1255 let container: Container = serde_json::from_value(saved).expect("saved container loads");
1256 assert!(serde_json::to_value(&container)
1257 .unwrap()
1258 .get("tunnel")
1259 .is_none());
1260 }
1261
1262 #[test]
1263 fn internet_egress_is_opt_in_and_refuses_the_unrestricted_profile() {
1264 let mut container = network_container();
1265 assert!(serde_json::to_value(&container)
1266 .unwrap()
1267 .get("egress")
1268 .is_none());
1269 container.egress = Some(ContainerEgress::Internet);
1272 assert!(container.validate_update(&container).is_err());
1273 container.security = Some(ContainerSecurity {
1274 profile: ContainerSecurityProfile::Unrestricted,
1275 run_as_user: None,
1276 run_as_group: None,
1277 read_only_root_filesystem: None,
1278 writable_paths: Vec::new(),
1279 });
1280 assert!(container.validate_update(&container).is_err());
1281 container.security = Some(ContainerSecurity {
1282 profile: ContainerSecurityProfile::Restricted,
1283 run_as_user: Some(65532),
1284 run_as_group: Some(65532),
1285 read_only_root_filesystem: Some(true),
1286 writable_paths: Vec::new(),
1287 });
1288 container.validate_update(&container).unwrap();
1289 assert_eq!(
1290 serde_json::to_value(&container).unwrap()["egress"],
1291 "internet"
1292 );
1293 }
1294
1295 #[test]
1296 fn test_container_creation_with_autoscaling() {
1297 let container = Container::new("api".to_string())
1298 .cluster("compute".to_string())
1299 .code(ContainerCode::Image {
1300 image: "myapp:latest".to_string(),
1301 })
1302 .cpu(ResourceSpec {
1303 min: "0.5".to_string(),
1304 desired: "1".to_string(),
1305 })
1306 .memory(ResourceSpec {
1307 min: "512Mi".to_string(),
1308 desired: "1Gi".to_string(),
1309 })
1310 .port(8080)
1311 .public_endpoint(PublicEndpoint {
1312 name: "api".to_string(),
1313 port: 8080,
1314 protocol: ExposeProtocol::Http,
1315 host_label: None,
1316 wildcard_subdomains: false,
1317 })
1318 .autoscaling(ContainerAutoscaling {
1319 min: 2,
1320 desired: 3,
1321 max: 10,
1322 target_cpu_percent: Some(70.0),
1323 target_memory_percent: None,
1324 target_http_in_flight_per_replica: Some(100),
1325 max_http_p95_latency_ms: None,
1326 })
1327 .permissions("container-execution".to_string())
1328 .build();
1329
1330 assert_eq!(container.id(), "api");
1331 assert_eq!(container.cluster, Some("compute".to_string()));
1332 assert!(!container.stateful);
1333 assert!(container.autoscaling.is_some());
1334 assert_eq!(container.ports.len(), 1);
1335 assert_eq!(container.ports[0].port, 8080);
1336 }
1337
1338 #[test]
1339 fn container_serializes_stop_grace_period_when_set() {
1340 let container = Container::new("api".to_string())
1341 .cluster("compute".to_string())
1342 .code(ContainerCode::Image {
1343 image: "myapp:latest".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 .permissions("container-execution".to_string())
1355 .stop_grace_period_seconds(21_600)
1356 .build();
1357
1358 let json = serde_json::to_value(&container).expect("container should serialize");
1359 assert_eq!(json["stopGracePeriodSeconds"], 21_600);
1360 }
1361
1362 #[test]
1363 fn container_omits_stop_grace_period_when_absent() {
1364 let container = Container::new("api".to_string())
1365 .cluster("compute".to_string())
1366 .code(ContainerCode::Image {
1367 image: "myapp:latest".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 .permissions("container-execution".to_string())
1379 .build();
1380
1381 let json = serde_json::to_value(&container).expect("container should serialize");
1382 assert!(json.get("stopGracePeriodSeconds").is_none());
1383 }
1384
1385 #[test]
1386 fn test_stateful_container_with_storage() {
1387 let container = Container::new("postgres".to_string())
1388 .cluster("compute".to_string())
1389 .code(ContainerCode::Image {
1390 image: "postgres:16".to_string(),
1391 })
1392 .cpu(ResourceSpec {
1393 min: "1".to_string(),
1394 desired: "2".to_string(),
1395 })
1396 .memory(ResourceSpec {
1397 min: "2Gi".to_string(),
1398 desired: "4Gi".to_string(),
1399 })
1400 .port(5432)
1401 .stateful(true)
1402 .replicas(1)
1403 .persistent_storage(PersistentStorage {
1404 encryption_key: None,
1405 size: "100Gi".to_string(),
1406 mount_path: "/var/lib/postgresql/data".to_string(),
1407 backups: VolumeBackups::default(),
1408 })
1409 .permissions("database".to_string())
1410 .build();
1411
1412 assert_eq!(container.id(), "postgres");
1413 assert!(container.stateful);
1414 assert!(container.replicas.is_some());
1415 assert!(container.persistent_storage.is_some());
1416 }
1417
1418 #[test]
1419 fn test_public_container() {
1420 let container = Container::new("frontend".to_string())
1421 .cluster("compute".to_string())
1422 .code(ContainerCode::Image {
1423 image: "frontend:latest".to_string(),
1424 })
1425 .cpu(ResourceSpec {
1426 min: "0.25".to_string(),
1427 desired: "0.5".to_string(),
1428 })
1429 .memory(ResourceSpec {
1430 min: "256Mi".to_string(),
1431 desired: "512Mi".to_string(),
1432 })
1433 .port(3000)
1434 .public_endpoint(PublicEndpoint {
1435 name: "web".to_string(),
1436 port: 3000,
1437 protocol: ExposeProtocol::Http,
1438 host_label: None,
1439 wildcard_subdomains: false,
1440 })
1441 .autoscaling(ContainerAutoscaling {
1442 min: 2,
1443 desired: 2,
1444 max: 20,
1445 target_cpu_percent: None,
1446 target_memory_percent: None,
1447 target_http_in_flight_per_replica: Some(50),
1448 max_http_p95_latency_ms: Some(100.0),
1449 })
1450 .health_check(HealthCheck {
1451 path: "/health".to_string(),
1452 port: None,
1453 method: "GET".to_string(),
1454 timeout_seconds: 1,
1455 failure_threshold: 3,
1456 startup_timeout_seconds: None,
1457 })
1458 .permissions("frontend".to_string())
1459 .build();
1460
1461 assert_eq!(container.ports[0].port, 3000);
1462 assert_eq!(container.public_endpoints[0].name, "web");
1463 assert!(container.health_check.is_some());
1464 }
1465
1466 #[test]
1467 fn test_public_container_endpoint_options() {
1468 let container = Container::new("router".to_string())
1469 .cluster("compute".to_string())
1470 .code(ContainerCode::Image {
1471 image: "router:latest".to_string(),
1472 })
1473 .cpu(ResourceSpec {
1474 min: "0.25".to_string(),
1475 desired: "0.5".to_string(),
1476 })
1477 .memory(ResourceSpec {
1478 min: "256Mi".to_string(),
1479 desired: "512Mi".to_string(),
1480 })
1481 .public_endpoint(PublicEndpoint {
1482 name: "gateway".to_string(),
1483 port: 8080,
1484 protocol: ExposeProtocol::Http,
1485 host_label: Some("gateway".to_string()),
1486 wildcard_subdomains: true,
1487 })
1488 .permissions("router".to_string())
1489 .build();
1490
1491 assert!(container.validate_public_endpoints().is_ok());
1492 assert_eq!(container.ports.len(), 1);
1493 assert_eq!(container.public_endpoints.len(), 1);
1494 assert_eq!(
1495 container.public_endpoints[0].host_label.as_deref(),
1496 Some("gateway")
1497 );
1498 assert!(container.public_endpoints[0].wildcard_subdomains);
1499 }
1500
1501 #[test]
1502 fn test_public_container_rejects_invalid_host_label() {
1503 let container = Container::new("router".to_string())
1504 .cluster("compute".to_string())
1505 .code(ContainerCode::Image {
1506 image: "router:latest".to_string(),
1507 })
1508 .cpu(ResourceSpec {
1509 min: "0.25".to_string(),
1510 desired: "0.5".to_string(),
1511 })
1512 .memory(ResourceSpec {
1513 min: "256Mi".to_string(),
1514 desired: "512Mi".to_string(),
1515 })
1516 .public_endpoint(PublicEndpoint {
1517 name: "gateway".to_string(),
1518 port: 8080,
1519 protocol: ExposeProtocol::Http,
1520 host_label: Some("bad.label".to_string()),
1521 wildcard_subdomains: true,
1522 })
1523 .permissions("router".to_string())
1524 .build();
1525
1526 assert!(container.validate_public_endpoints().is_err());
1527 }
1528
1529 #[test]
1530 fn test_container_with_links() {
1531 use crate::Storage;
1532
1533 let storage = Storage::new("data".to_string()).build();
1534
1535 let container = Container::new("worker".to_string())
1536 .cluster("compute".to_string())
1537 .code(ContainerCode::Image {
1538 image: "worker:latest".to_string(),
1539 })
1540 .cpu(ResourceSpec {
1541 min: "0.5".to_string(),
1542 desired: "1".to_string(),
1543 })
1544 .memory(ResourceSpec {
1545 min: "512Mi".to_string(),
1546 desired: "1Gi".to_string(),
1547 })
1548 .port(8080)
1549 .replicas(3)
1550 .link(&storage)
1551 .permissions("worker".to_string())
1552 .build();
1553
1554 let deps = container.get_dependencies();
1556 assert_eq!(deps.len(), 2);
1557 }
1558
1559 #[test]
1560 fn test_container_validate_update_immutable_cluster() {
1561 let container1 = Container::new("api".to_string())
1562 .cluster("cluster-1".to_string())
1563 .code(ContainerCode::Image {
1564 image: "myapp:v1".to_string(),
1565 })
1566 .cpu(ResourceSpec {
1567 min: "0.5".to_string(),
1568 desired: "1".to_string(),
1569 })
1570 .memory(ResourceSpec {
1571 min: "512Mi".to_string(),
1572 desired: "1Gi".to_string(),
1573 })
1574 .port(8080)
1575 .replicas(2)
1576 .permissions("execution".to_string())
1577 .build();
1578
1579 let container2 = Container::new("api".to_string())
1580 .cluster("cluster-2".to_string()) .code(ContainerCode::Image {
1582 image: "myapp:v2".to_string(),
1583 })
1584 .cpu(ResourceSpec {
1585 min: "0.5".to_string(),
1586 desired: "1".to_string(),
1587 })
1588 .memory(ResourceSpec {
1589 min: "512Mi".to_string(),
1590 desired: "1Gi".to_string(),
1591 })
1592 .port(8080)
1593 .replicas(2)
1594 .permissions("execution".to_string())
1595 .build();
1596
1597 let result = container1.validate_update(&container2);
1598 assert!(result.is_err());
1599 }
1600
1601 #[test]
1602 fn test_container_validate_update_allowed_changes() {
1603 let container1 = Container::new("api".to_string())
1604 .cluster("compute".to_string())
1605 .code(ContainerCode::Image {
1606 image: "myapp:v1".to_string(),
1607 })
1608 .cpu(ResourceSpec {
1609 min: "0.5".to_string(),
1610 desired: "1".to_string(),
1611 })
1612 .memory(ResourceSpec {
1613 min: "512Mi".to_string(),
1614 desired: "1Gi".to_string(),
1615 })
1616 .port(8080)
1617 .replicas(2)
1618 .permissions("execution".to_string())
1619 .build();
1620
1621 let container2 = Container::new("api".to_string())
1622 .cluster("compute".to_string())
1623 .code(ContainerCode::Image {
1624 image: "myapp:v2".to_string(), })
1626 .cpu(ResourceSpec {
1627 min: "1".to_string(), desired: "2".to_string(),
1629 })
1630 .memory(ResourceSpec {
1631 min: "1Gi".to_string(),
1632 desired: "2Gi".to_string(),
1633 })
1634 .port(8080)
1635 .replicas(5) .permissions("execution".to_string())
1637 .build();
1638
1639 let result = container1.validate_update(&container2);
1640 assert!(result.is_ok());
1641 }
1642
1643 #[test]
1644 fn test_container_serialization() {
1645 let container = Container::new("test".to_string())
1646 .cluster("compute".to_string())
1647 .code(ContainerCode::Image {
1648 image: "test:latest".to_string(),
1649 })
1650 .cpu(ResourceSpec {
1651 min: "0.5".to_string(),
1652 desired: "1".to_string(),
1653 })
1654 .memory(ResourceSpec {
1655 min: "512Mi".to_string(),
1656 desired: "1Gi".to_string(),
1657 })
1658 .port(8080)
1659 .replicas(1)
1660 .permissions("test".to_string())
1661 .build();
1662
1663 let json = serde_json::to_string(&container).unwrap();
1664 let deserialized: Container = serde_json::from_str(&json).unwrap();
1665 assert_eq!(container, deserialized);
1666 }
1667
1668 #[test]
1669 fn test_container_multi_endpoint_validation() {
1670 let container = Container::new("multi-tcp".to_string())
1671 .cluster("compute".to_string())
1672 .code(ContainerCode::Image {
1673 image: "test:latest".to_string(),
1674 })
1675 .cpu(ResourceSpec {
1676 min: "1".to_string(),
1677 desired: "1".to_string(),
1678 })
1679 .memory(ResourceSpec {
1680 min: "1Gi".to_string(),
1681 desired: "1Gi".to_string(),
1682 })
1683 .port(8080)
1684 .public_endpoint(PublicEndpoint {
1685 name: "api".to_string(),
1686 port: 8080,
1687 protocol: ExposeProtocol::Http,
1688 host_label: None,
1689 wildcard_subdomains: false,
1690 })
1691 .public_endpoint(PublicEndpoint {
1692 name: "wildcard".to_string(),
1693 port: 8080,
1694 protocol: ExposeProtocol::Http,
1695 host_label: Some("wildcard".to_string()),
1696 wildcard_subdomains: true,
1697 })
1698 .replicas(1)
1699 .permissions("test".to_string())
1700 .build();
1701
1702 assert!(container.validate_public_endpoints().is_ok());
1703
1704 let invalid_container = Container::new("multi-http".to_string())
1705 .cluster("compute".to_string())
1706 .code(ContainerCode::Image {
1707 image: "test:latest".to_string(),
1708 })
1709 .cpu(ResourceSpec {
1710 min: "1".to_string(),
1711 desired: "1".to_string(),
1712 })
1713 .memory(ResourceSpec {
1714 min: "1Gi".to_string(),
1715 desired: "1Gi".to_string(),
1716 })
1717 .port(8080)
1718 .port(9090)
1719 .public_endpoint(PublicEndpoint {
1720 name: "api".to_string(),
1721 port: 8080,
1722 protocol: ExposeProtocol::Http,
1723 host_label: None,
1724 wildcard_subdomains: false,
1725 })
1726 .public_endpoint(PublicEndpoint {
1727 name: "admin".to_string(),
1728 port: 9090,
1729 protocol: ExposeProtocol::Http,
1730 host_label: None,
1731 wildcard_subdomains: false,
1732 })
1733 .replicas(1)
1734 .permissions("test".to_string())
1735 .build();
1736
1737 assert!(invalid_container.validate_public_endpoints().is_err());
1738 }
1739
1740 #[test]
1741 fn container_rejects_multiple_apex_public_endpoints() {
1742 let container = Container::new("apex-container".to_string())
1743 .cluster("compute".to_string())
1744 .code(ContainerCode::Image {
1745 image: "test:latest".to_string(),
1746 })
1747 .cpu(ResourceSpec {
1748 min: "1".to_string(),
1749 desired: "1".to_string(),
1750 })
1751 .memory(ResourceSpec {
1752 min: "1Gi".to_string(),
1753 desired: "1Gi".to_string(),
1754 })
1755 .port(8080)
1756 .public_endpoint(PublicEndpoint {
1757 name: "web".to_string(),
1758 port: 8080,
1759 protocol: ExposeProtocol::Http,
1760 host_label: Some(APEX_HOST_LABEL.to_string()),
1761 wildcard_subdomains: false,
1762 })
1763 .public_endpoint(PublicEndpoint {
1764 name: "admin".to_string(),
1765 port: 8080,
1766 protocol: ExposeProtocol::Http,
1767 host_label: Some(APEX_HOST_LABEL.to_string()),
1768 wildcard_subdomains: false,
1769 })
1770 .replicas(1)
1771 .permissions("test".to_string())
1772 .build();
1773
1774 assert!(container.validate_public_endpoints().is_err());
1775 }
1776
1777 #[test]
1778 fn test_container_empty_ports_validation() {
1779 let container = Container::new("no-ports".to_string())
1780 .cluster("compute".to_string())
1781 .code(ContainerCode::Image {
1782 image: "test:latest".to_string(),
1783 })
1784 .cpu(ResourceSpec {
1785 min: "1".to_string(),
1786 desired: "1".to_string(),
1787 })
1788 .memory(ResourceSpec {
1789 min: "1Gi".to_string(),
1790 desired: "1Gi".to_string(),
1791 })
1792 .replicas(1)
1793 .permissions("test".to_string())
1794 .build();
1795
1796 assert!(container.validate_public_endpoints().is_ok());
1797 }
1798
1799 #[test]
1800 fn test_container_commands_enabled_defaults_false() {
1801 let container = Container::new("no-commands".to_string())
1802 .cluster("compute".to_string())
1803 .code(ContainerCode::Image {
1804 image: "test:latest".to_string(),
1805 })
1806 .cpu(ResourceSpec {
1807 min: "0.5".to_string(),
1808 desired: "1".to_string(),
1809 })
1810 .memory(ResourceSpec {
1811 min: "512Mi".to_string(),
1812 desired: "1Gi".to_string(),
1813 })
1814 .port(8080)
1815 .permissions("test".to_string())
1816 .build();
1817
1818 assert!(!container.commands_enabled);
1819 }
1820
1821 #[test]
1822 fn test_container_commands_enabled_builder() {
1823 let container = Container::new("cmd-container".to_string())
1824 .cluster("compute".to_string())
1825 .code(ContainerCode::Image {
1826 image: "test:latest".to_string(),
1827 })
1828 .cpu(ResourceSpec {
1829 min: "0.5".to_string(),
1830 desired: "1".to_string(),
1831 })
1832 .memory(ResourceSpec {
1833 min: "512Mi".to_string(),
1834 desired: "1Gi".to_string(),
1835 })
1836 .port(8080)
1837 .permissions("test".to_string())
1838 .commands_enabled(true)
1839 .build();
1840
1841 assert!(container.commands_enabled);
1842 }
1843
1844 #[test]
1845 fn test_container_commands_enabled_serializes_camel_case() {
1846 let container = Container::new("cmd-container".to_string())
1847 .cluster("compute".to_string())
1848 .code(ContainerCode::Image {
1849 image: "test:latest".to_string(),
1850 })
1851 .cpu(ResourceSpec {
1852 min: "0.5".to_string(),
1853 desired: "1".to_string(),
1854 })
1855 .memory(ResourceSpec {
1856 min: "512Mi".to_string(),
1857 desired: "1Gi".to_string(),
1858 })
1859 .port(8080)
1860 .permissions("test".to_string())
1861 .commands_enabled(true)
1862 .build();
1863
1864 let json = serde_json::to_value(&container).expect("container should serialize");
1865 assert_eq!(json["commandsEnabled"], true);
1866
1867 let deserialized: Container =
1868 serde_json::from_value(json).expect("container should deserialize");
1869 assert_eq!(deserialized, container);
1870 }
1871}