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 pub replicas: Vec<ReplicaStatus>,
872 #[serde(default, skip_serializing_if = "Vec::is_empty")]
874 pub volumes: Vec<VolumeOutput>,
875 #[serde(default, skip_serializing_if = "Option::is_none")]
877 pub volume_backups: Option<VolumeBackupsStatus>,
878}
879
880#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
882#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
883#[serde(rename_all = "camelCase")]
884pub struct VolumeBackupsStatus {
885 pub state: VolumeBackupsState,
887 #[serde(skip_serializing_if = "Option::is_none")]
889 pub message: Option<String>,
890}
891
892#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
894#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
895#[serde(rename_all = "camelCase")]
896pub enum VolumeBackupsState {
897 Active,
899 Disabled,
901 SetupRequired,
905}
906
907#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
909#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
910#[serde(rename_all = "camelCase")]
911pub struct VolumeOutput {
912 pub ordinal: u32,
914 pub volume_id: String,
916 pub zone: String,
918 #[serde(skip_serializing_if = "Option::is_none")]
920 pub last_snapshot_id: Option<String>,
921 #[serde(skip_serializing_if = "Option::is_none")]
923 pub last_snapshot_at: Option<String>,
924 #[serde(skip_serializing_if = "Option::is_none")]
926 pub last_restore: Option<VolumeRestoreOutput>,
927}
928
929#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
931#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
932#[serde(rename_all = "camelCase")]
933pub struct VolumeRestoreOutput {
934 pub request_id: String,
936 pub snapshot_id: String,
938 pub replaced_volume_snapshot_id: String,
940 pub completed_at: String,
942}
943
944impl ResourceOutputsDefinition for ContainerOutputs {
945 fn get_resource_type(&self) -> ResourceType {
946 Container::RESOURCE_TYPE.clone()
947 }
948
949 fn as_any(&self) -> &dyn Any {
950 self
951 }
952
953 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
954 Box::new(self.clone())
955 }
956
957 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
958 other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
959 }
960
961 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
962 serde_json::to_value(self)
963 }
964}
965
966impl ResourceDefinition for Container {
967 fn get_resource_type(&self) -> ResourceType {
968 Self::RESOURCE_TYPE
969 }
970
971 fn id(&self) -> &str {
972 &self.id
973 }
974
975 fn replace_after_failed_create_is_safe(&self) -> bool {
976 !(self.stateful && self.persistent_storage.is_some())
978 }
979
980 fn get_dependencies(&self) -> Vec<ResourceRef> {
981 let mut deps = self.links.clone();
982 if let Some(key) = self
983 .persistent_storage
984 .as_ref()
985 .and_then(|storage| storage.encryption_key.as_ref())
986 {
987 deps.push(key.clone());
988 }
989 if let Some(cluster) = &self.cluster {
992 deps.push(ResourceRef::new(
993 ComputeCluster::RESOURCE_TYPE.clone(),
994 cluster,
995 ));
996 }
997 deps
998 }
999
1000 fn get_permissions(&self) -> Option<&str> {
1001 Some(&self.permissions)
1002 }
1003
1004 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1005 let new_container = new_config
1006 .as_any()
1007 .downcast_ref::<Container>()
1008 .ok_or_else(|| {
1009 AlienError::new(ErrorData::UnexpectedResourceType {
1010 resource_id: self.id.clone(),
1011 expected: Self::RESOURCE_TYPE,
1012 actual: new_config.get_resource_type(),
1013 })
1014 })?;
1015
1016 new_container.validate_public_endpoints()?;
1018 new_container.validate_network_settings()?;
1019
1020 if self.id != new_container.id {
1021 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1022 resource_id: self.id.clone(),
1023 reason: "the 'id' field is immutable".to_string(),
1024 }));
1025 }
1026
1027 if self.cluster != new_container.cluster {
1029 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1030 resource_id: self.id.clone(),
1031 reason: "the 'cluster' field is immutable".to_string(),
1032 }));
1033 }
1034
1035 if self.stateful != new_container.stateful {
1037 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1038 resource_id: self.id.clone(),
1039 reason: "the 'stateful' field is immutable".to_string(),
1040 }));
1041 }
1042
1043 let old_key = self
1044 .persistent_storage
1045 .as_ref()
1046 .and_then(|storage| storage.encryption_key.as_ref());
1047 let new_key = new_container
1048 .persistent_storage
1049 .as_ref()
1050 .and_then(|storage| storage.encryption_key.as_ref());
1051 if old_key != new_key {
1052 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1053 resource_id: self.id.clone(),
1054 reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
1055 }));
1056 }
1057
1058 if self.ports != new_container.ports {
1060 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1061 resource_id: self.id.clone(),
1062 reason: "the 'ports' field is immutable".to_string(),
1063 }));
1064 }
1065
1066 if self.public_endpoints != new_container.public_endpoints {
1067 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1068 resource_id: self.id.clone(),
1069 reason: "the 'publicEndpoints' field is immutable".to_string(),
1070 }));
1071 }
1072
1073 if self.pool != new_container.pool {
1075 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1076 resource_id: self.id.clone(),
1077 reason: "the 'pool' field is immutable".to_string(),
1078 }));
1079 }
1080
1081 Ok(())
1082 }
1083
1084 fn as_any(&self) -> &dyn Any {
1085 self
1086 }
1087
1088 fn as_any_mut(&mut self) -> &mut dyn Any {
1089 self
1090 }
1091
1092 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1093 Box::new(self.clone())
1094 }
1095
1096 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1097 other.as_any().downcast_ref::<Container>() == Some(self)
1098 }
1099
1100 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1101 serde_json::to_value(self)
1102 }
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107 #[derive(Debug, serde::Deserialize)]
1108 #[serde(rename_all = "camelCase")]
1109 enum PreviousProfile {
1110 Restricted,
1111 }
1112
1113 #[derive(Debug, serde::Deserialize)]
1117 #[serde(rename_all = "camelCase")]
1118 #[allow(dead_code)]
1119 struct PreviousContainerSecurity {
1120 profile: PreviousProfile,
1121 run_as_user: i64,
1122 run_as_group: i64,
1123 read_only_root_filesystem: bool,
1124 }
1125
1126 #[test]
1127 fn written_security_parses_with_the_previous_release_struct() {
1128 let defaults = ContainerSecurity {
1129 profile: ContainerSecurityProfile::Restricted,
1130 run_as_user: None,
1131 run_as_group: None,
1132 read_only_root_filesystem: None,
1133 writable_paths: Vec::new(),
1134 };
1135 let explicit = ContainerSecurity {
1136 profile: ContainerSecurityProfile::Unrestricted,
1137 run_as_user: Some(70),
1138 run_as_group: Some(71),
1139 read_only_root_filesystem: Some(false),
1140 writable_paths: vec!["/data".to_string()],
1141 };
1142 let unrestricted_defaults = ContainerSecurity {
1143 profile: ContainerSecurityProfile::Unrestricted,
1144 ..defaults.clone()
1145 };
1146 let explicit_zero = ContainerSecurity {
1147 profile: ContainerSecurityProfile::Restricted,
1148 run_as_user: Some(0),
1149 run_as_group: None,
1150 read_only_root_filesystem: Some(false),
1151 writable_paths: Vec::new(),
1152 };
1153 for security in [defaults, explicit, unrestricted_defaults, explicit_zero] {
1154 let json = serde_json::to_value(&security).unwrap();
1155 serde_json::from_value::<PreviousContainerSecurity>(json.clone())
1156 .unwrap_or_else(|error| panic!("previous release cannot read {json}: {error}"));
1157 let back: ContainerSecurity = serde_json::from_value(json).unwrap();
1159 assert_eq!(back, security);
1160 }
1161 }
1162
1163 #[test]
1168 fn unrestricted_opt_out_reads_as_restricted_with_the_previous_release_struct() {
1169 let security = ContainerSecurity {
1170 profile: ContainerSecurityProfile::Unrestricted,
1171 run_as_user: Some(0),
1172 run_as_group: Some(0),
1173 read_only_root_filesystem: Some(false),
1174 writable_paths: Vec::new(),
1175 };
1176 let json = serde_json::to_value(&security).unwrap();
1177 assert_eq!(json["profile"], "restricted");
1178 assert_eq!(json["unrestricted"], true);
1179 let previous: PreviousContainerSecurity = serde_json::from_value(json.clone()).unwrap();
1180 assert!(matches!(previous.profile, PreviousProfile::Restricted));
1181 let back: ContainerSecurity = serde_json::from_value(json).unwrap();
1182 assert_eq!(back, security);
1183 }
1184
1185 #[test]
1188 fn security_without_a_profile_fails_to_parse() {
1189 assert!(
1190 serde_json::from_str::<ContainerSecurity>(r#"{"writablePaths":["/cache"]}"#).is_err()
1191 );
1192 assert!(serde_json::from_str::<ContainerSecurity>("{}").is_err());
1193 }
1194
1195 #[test]
1196 fn security_reads_accept_the_plain_unrestricted_profile() {
1197 let security: ContainerSecurity =
1198 serde_json::from_str(r#"{"profile":"unrestricted"}"#).unwrap();
1199 assert_eq!(security.profile, ContainerSecurityProfile::Unrestricted);
1200 }
1201
1202 #[test]
1203 fn security_reads_tolerate_omitted_fields() {
1204 let security: ContainerSecurity =
1205 serde_json::from_str(r#"{"profile":"restricted"}"#).unwrap();
1206 assert_eq!(security.run_as_user, None);
1207 assert_eq!(security.read_only_root_filesystem, None);
1208 }
1209
1210 use super::*;
1211 use crate::resources::ExposeProtocol;
1212
1213 fn network_container() -> Container {
1214 Container::new("api".to_string())
1215 .code(ContainerCode::Image {
1216 image: "example:latest".into(),
1217 })
1218 .cpu(ResourceSpec {
1219 min: "1".into(),
1220 desired: "1".into(),
1221 })
1222 .memory(ResourceSpec {
1223 min: "512Mi".into(),
1224 desired: "512Mi".into(),
1225 })
1226 .permissions("execution".into())
1227 .public_endpoint(PublicEndpoint {
1228 name: "web".into(),
1229 port: 8080,
1230 protocol: ExposeProtocol::Http,
1231 host_label: None,
1232 wildcard_subdomains: false,
1233 })
1234 .build()
1235 }
1236
1237 #[test]
1238 fn a_saved_container_with_the_retired_tunnel_field_still_loads() {
1239 let saved = serde_json::json!({
1240 "id": "api",
1241 "code": {"type": "image", "image": "example/api:1"},
1242 "cpu": {"min": "0.5", "desired": "0.5"},
1243 "memory": {"min": "256Mi", "desired": "256Mi"},
1244 "permissions": "execution",
1245 "links": [], "ports": [],
1246 "tunnel": {"port": 8080}
1247 });
1248 let container: Container = serde_json::from_value(saved).expect("saved container loads");
1249 assert!(serde_json::to_value(&container)
1250 .unwrap()
1251 .get("tunnel")
1252 .is_none());
1253 }
1254
1255 #[test]
1256 fn internet_egress_is_opt_in_and_refuses_the_unrestricted_profile() {
1257 let mut container = network_container();
1258 assert!(serde_json::to_value(&container)
1259 .unwrap()
1260 .get("egress")
1261 .is_none());
1262 container.egress = Some(ContainerEgress::Internet);
1265 assert!(container.validate_update(&container).is_err());
1266 container.security = Some(ContainerSecurity {
1267 profile: ContainerSecurityProfile::Unrestricted,
1268 run_as_user: None,
1269 run_as_group: None,
1270 read_only_root_filesystem: None,
1271 writable_paths: Vec::new(),
1272 });
1273 assert!(container.validate_update(&container).is_err());
1274 container.security = Some(ContainerSecurity {
1275 profile: ContainerSecurityProfile::Restricted,
1276 run_as_user: Some(65532),
1277 run_as_group: Some(65532),
1278 read_only_root_filesystem: Some(true),
1279 writable_paths: Vec::new(),
1280 });
1281 container.validate_update(&container).unwrap();
1282 assert_eq!(
1283 serde_json::to_value(&container).unwrap()["egress"],
1284 "internet"
1285 );
1286 }
1287
1288 #[test]
1289 fn test_container_creation_with_autoscaling() {
1290 let container = Container::new("api".to_string())
1291 .cluster("compute".to_string())
1292 .code(ContainerCode::Image {
1293 image: "myapp:latest".to_string(),
1294 })
1295 .cpu(ResourceSpec {
1296 min: "0.5".to_string(),
1297 desired: "1".to_string(),
1298 })
1299 .memory(ResourceSpec {
1300 min: "512Mi".to_string(),
1301 desired: "1Gi".to_string(),
1302 })
1303 .port(8080)
1304 .public_endpoint(PublicEndpoint {
1305 name: "api".to_string(),
1306 port: 8080,
1307 protocol: ExposeProtocol::Http,
1308 host_label: None,
1309 wildcard_subdomains: false,
1310 })
1311 .autoscaling(ContainerAutoscaling {
1312 min: 2,
1313 desired: 3,
1314 max: 10,
1315 target_cpu_percent: Some(70.0),
1316 target_memory_percent: None,
1317 target_http_in_flight_per_replica: Some(100),
1318 max_http_p95_latency_ms: None,
1319 })
1320 .permissions("container-execution".to_string())
1321 .build();
1322
1323 assert_eq!(container.id(), "api");
1324 assert_eq!(container.cluster, Some("compute".to_string()));
1325 assert!(!container.stateful);
1326 assert!(container.autoscaling.is_some());
1327 assert_eq!(container.ports.len(), 1);
1328 assert_eq!(container.ports[0].port, 8080);
1329 }
1330
1331 #[test]
1332 fn container_serializes_stop_grace_period_when_set() {
1333 let container = Container::new("api".to_string())
1334 .cluster("compute".to_string())
1335 .code(ContainerCode::Image {
1336 image: "myapp:latest".to_string(),
1337 })
1338 .cpu(ResourceSpec {
1339 min: "0.5".to_string(),
1340 desired: "1".to_string(),
1341 })
1342 .memory(ResourceSpec {
1343 min: "512Mi".to_string(),
1344 desired: "1Gi".to_string(),
1345 })
1346 .port(8080)
1347 .permissions("container-execution".to_string())
1348 .stop_grace_period_seconds(21_600)
1349 .build();
1350
1351 let json = serde_json::to_value(&container).expect("container should serialize");
1352 assert_eq!(json["stopGracePeriodSeconds"], 21_600);
1353 }
1354
1355 #[test]
1356 fn container_omits_stop_grace_period_when_absent() {
1357 let container = Container::new("api".to_string())
1358 .cluster("compute".to_string())
1359 .code(ContainerCode::Image {
1360 image: "myapp:latest".to_string(),
1361 })
1362 .cpu(ResourceSpec {
1363 min: "0.5".to_string(),
1364 desired: "1".to_string(),
1365 })
1366 .memory(ResourceSpec {
1367 min: "512Mi".to_string(),
1368 desired: "1Gi".to_string(),
1369 })
1370 .port(8080)
1371 .permissions("container-execution".to_string())
1372 .build();
1373
1374 let json = serde_json::to_value(&container).expect("container should serialize");
1375 assert!(json.get("stopGracePeriodSeconds").is_none());
1376 }
1377
1378 #[test]
1379 fn test_stateful_container_with_storage() {
1380 let container = Container::new("postgres".to_string())
1381 .cluster("compute".to_string())
1382 .code(ContainerCode::Image {
1383 image: "postgres:16".to_string(),
1384 })
1385 .cpu(ResourceSpec {
1386 min: "1".to_string(),
1387 desired: "2".to_string(),
1388 })
1389 .memory(ResourceSpec {
1390 min: "2Gi".to_string(),
1391 desired: "4Gi".to_string(),
1392 })
1393 .port(5432)
1394 .stateful(true)
1395 .replicas(1)
1396 .persistent_storage(PersistentStorage {
1397 encryption_key: None,
1398 size: "100Gi".to_string(),
1399 mount_path: "/var/lib/postgresql/data".to_string(),
1400 backups: VolumeBackups::default(),
1401 })
1402 .permissions("database".to_string())
1403 .build();
1404
1405 assert_eq!(container.id(), "postgres");
1406 assert!(container.stateful);
1407 assert!(container.replicas.is_some());
1408 assert!(container.persistent_storage.is_some());
1409 }
1410
1411 #[test]
1412 fn test_public_container() {
1413 let container = Container::new("frontend".to_string())
1414 .cluster("compute".to_string())
1415 .code(ContainerCode::Image {
1416 image: "frontend:latest".to_string(),
1417 })
1418 .cpu(ResourceSpec {
1419 min: "0.25".to_string(),
1420 desired: "0.5".to_string(),
1421 })
1422 .memory(ResourceSpec {
1423 min: "256Mi".to_string(),
1424 desired: "512Mi".to_string(),
1425 })
1426 .port(3000)
1427 .public_endpoint(PublicEndpoint {
1428 name: "web".to_string(),
1429 port: 3000,
1430 protocol: ExposeProtocol::Http,
1431 host_label: None,
1432 wildcard_subdomains: false,
1433 })
1434 .autoscaling(ContainerAutoscaling {
1435 min: 2,
1436 desired: 2,
1437 max: 20,
1438 target_cpu_percent: None,
1439 target_memory_percent: None,
1440 target_http_in_flight_per_replica: Some(50),
1441 max_http_p95_latency_ms: Some(100.0),
1442 })
1443 .health_check(HealthCheck {
1444 path: "/health".to_string(),
1445 port: None,
1446 method: "GET".to_string(),
1447 timeout_seconds: 1,
1448 failure_threshold: 3,
1449 startup_timeout_seconds: None,
1450 })
1451 .permissions("frontend".to_string())
1452 .build();
1453
1454 assert_eq!(container.ports[0].port, 3000);
1455 assert_eq!(container.public_endpoints[0].name, "web");
1456 assert!(container.health_check.is_some());
1457 }
1458
1459 #[test]
1460 fn test_public_container_endpoint_options() {
1461 let container = Container::new("router".to_string())
1462 .cluster("compute".to_string())
1463 .code(ContainerCode::Image {
1464 image: "router:latest".to_string(),
1465 })
1466 .cpu(ResourceSpec {
1467 min: "0.25".to_string(),
1468 desired: "0.5".to_string(),
1469 })
1470 .memory(ResourceSpec {
1471 min: "256Mi".to_string(),
1472 desired: "512Mi".to_string(),
1473 })
1474 .public_endpoint(PublicEndpoint {
1475 name: "gateway".to_string(),
1476 port: 8080,
1477 protocol: ExposeProtocol::Http,
1478 host_label: Some("gateway".to_string()),
1479 wildcard_subdomains: true,
1480 })
1481 .permissions("router".to_string())
1482 .build();
1483
1484 assert!(container.validate_public_endpoints().is_ok());
1485 assert_eq!(container.ports.len(), 1);
1486 assert_eq!(container.public_endpoints.len(), 1);
1487 assert_eq!(
1488 container.public_endpoints[0].host_label.as_deref(),
1489 Some("gateway")
1490 );
1491 assert!(container.public_endpoints[0].wildcard_subdomains);
1492 }
1493
1494 #[test]
1495 fn test_public_container_rejects_invalid_host_label() {
1496 let container = Container::new("router".to_string())
1497 .cluster("compute".to_string())
1498 .code(ContainerCode::Image {
1499 image: "router:latest".to_string(),
1500 })
1501 .cpu(ResourceSpec {
1502 min: "0.25".to_string(),
1503 desired: "0.5".to_string(),
1504 })
1505 .memory(ResourceSpec {
1506 min: "256Mi".to_string(),
1507 desired: "512Mi".to_string(),
1508 })
1509 .public_endpoint(PublicEndpoint {
1510 name: "gateway".to_string(),
1511 port: 8080,
1512 protocol: ExposeProtocol::Http,
1513 host_label: Some("bad.label".to_string()),
1514 wildcard_subdomains: true,
1515 })
1516 .permissions("router".to_string())
1517 .build();
1518
1519 assert!(container.validate_public_endpoints().is_err());
1520 }
1521
1522 #[test]
1523 fn test_container_with_links() {
1524 use crate::Storage;
1525
1526 let storage = Storage::new("data".to_string()).build();
1527
1528 let container = Container::new("worker".to_string())
1529 .cluster("compute".to_string())
1530 .code(ContainerCode::Image {
1531 image: "worker:latest".to_string(),
1532 })
1533 .cpu(ResourceSpec {
1534 min: "0.5".to_string(),
1535 desired: "1".to_string(),
1536 })
1537 .memory(ResourceSpec {
1538 min: "512Mi".to_string(),
1539 desired: "1Gi".to_string(),
1540 })
1541 .port(8080)
1542 .replicas(3)
1543 .link(&storage)
1544 .permissions("worker".to_string())
1545 .build();
1546
1547 let deps = container.get_dependencies();
1549 assert_eq!(deps.len(), 2);
1550 }
1551
1552 #[test]
1553 fn test_container_validate_update_immutable_cluster() {
1554 let container1 = Container::new("api".to_string())
1555 .cluster("cluster-1".to_string())
1556 .code(ContainerCode::Image {
1557 image: "myapp:v1".to_string(),
1558 })
1559 .cpu(ResourceSpec {
1560 min: "0.5".to_string(),
1561 desired: "1".to_string(),
1562 })
1563 .memory(ResourceSpec {
1564 min: "512Mi".to_string(),
1565 desired: "1Gi".to_string(),
1566 })
1567 .port(8080)
1568 .replicas(2)
1569 .permissions("execution".to_string())
1570 .build();
1571
1572 let container2 = Container::new("api".to_string())
1573 .cluster("cluster-2".to_string()) .code(ContainerCode::Image {
1575 image: "myapp:v2".to_string(),
1576 })
1577 .cpu(ResourceSpec {
1578 min: "0.5".to_string(),
1579 desired: "1".to_string(),
1580 })
1581 .memory(ResourceSpec {
1582 min: "512Mi".to_string(),
1583 desired: "1Gi".to_string(),
1584 })
1585 .port(8080)
1586 .replicas(2)
1587 .permissions("execution".to_string())
1588 .build();
1589
1590 let result = container1.validate_update(&container2);
1591 assert!(result.is_err());
1592 }
1593
1594 #[test]
1595 fn test_container_validate_update_allowed_changes() {
1596 let container1 = Container::new("api".to_string())
1597 .cluster("compute".to_string())
1598 .code(ContainerCode::Image {
1599 image: "myapp:v1".to_string(),
1600 })
1601 .cpu(ResourceSpec {
1602 min: "0.5".to_string(),
1603 desired: "1".to_string(),
1604 })
1605 .memory(ResourceSpec {
1606 min: "512Mi".to_string(),
1607 desired: "1Gi".to_string(),
1608 })
1609 .port(8080)
1610 .replicas(2)
1611 .permissions("execution".to_string())
1612 .build();
1613
1614 let container2 = Container::new("api".to_string())
1615 .cluster("compute".to_string())
1616 .code(ContainerCode::Image {
1617 image: "myapp:v2".to_string(), })
1619 .cpu(ResourceSpec {
1620 min: "1".to_string(), desired: "2".to_string(),
1622 })
1623 .memory(ResourceSpec {
1624 min: "1Gi".to_string(),
1625 desired: "2Gi".to_string(),
1626 })
1627 .port(8080)
1628 .replicas(5) .permissions("execution".to_string())
1630 .build();
1631
1632 let result = container1.validate_update(&container2);
1633 assert!(result.is_ok());
1634 }
1635
1636 #[test]
1637 fn test_container_serialization() {
1638 let container = Container::new("test".to_string())
1639 .cluster("compute".to_string())
1640 .code(ContainerCode::Image {
1641 image: "test:latest".to_string(),
1642 })
1643 .cpu(ResourceSpec {
1644 min: "0.5".to_string(),
1645 desired: "1".to_string(),
1646 })
1647 .memory(ResourceSpec {
1648 min: "512Mi".to_string(),
1649 desired: "1Gi".to_string(),
1650 })
1651 .port(8080)
1652 .replicas(1)
1653 .permissions("test".to_string())
1654 .build();
1655
1656 let json = serde_json::to_string(&container).unwrap();
1657 let deserialized: Container = serde_json::from_str(&json).unwrap();
1658 assert_eq!(container, deserialized);
1659 }
1660
1661 #[test]
1662 fn test_container_multi_endpoint_validation() {
1663 let container = Container::new("multi-tcp".to_string())
1664 .cluster("compute".to_string())
1665 .code(ContainerCode::Image {
1666 image: "test:latest".to_string(),
1667 })
1668 .cpu(ResourceSpec {
1669 min: "1".to_string(),
1670 desired: "1".to_string(),
1671 })
1672 .memory(ResourceSpec {
1673 min: "1Gi".to_string(),
1674 desired: "1Gi".to_string(),
1675 })
1676 .port(8080)
1677 .public_endpoint(PublicEndpoint {
1678 name: "api".to_string(),
1679 port: 8080,
1680 protocol: ExposeProtocol::Http,
1681 host_label: None,
1682 wildcard_subdomains: false,
1683 })
1684 .public_endpoint(PublicEndpoint {
1685 name: "wildcard".to_string(),
1686 port: 8080,
1687 protocol: ExposeProtocol::Http,
1688 host_label: Some("wildcard".to_string()),
1689 wildcard_subdomains: true,
1690 })
1691 .replicas(1)
1692 .permissions("test".to_string())
1693 .build();
1694
1695 assert!(container.validate_public_endpoints().is_ok());
1696
1697 let invalid_container = Container::new("multi-http".to_string())
1698 .cluster("compute".to_string())
1699 .code(ContainerCode::Image {
1700 image: "test:latest".to_string(),
1701 })
1702 .cpu(ResourceSpec {
1703 min: "1".to_string(),
1704 desired: "1".to_string(),
1705 })
1706 .memory(ResourceSpec {
1707 min: "1Gi".to_string(),
1708 desired: "1Gi".to_string(),
1709 })
1710 .port(8080)
1711 .port(9090)
1712 .public_endpoint(PublicEndpoint {
1713 name: "api".to_string(),
1714 port: 8080,
1715 protocol: ExposeProtocol::Http,
1716 host_label: None,
1717 wildcard_subdomains: false,
1718 })
1719 .public_endpoint(PublicEndpoint {
1720 name: "admin".to_string(),
1721 port: 9090,
1722 protocol: ExposeProtocol::Http,
1723 host_label: None,
1724 wildcard_subdomains: false,
1725 })
1726 .replicas(1)
1727 .permissions("test".to_string())
1728 .build();
1729
1730 assert!(invalid_container.validate_public_endpoints().is_err());
1731 }
1732
1733 #[test]
1734 fn container_rejects_multiple_apex_public_endpoints() {
1735 let container = Container::new("apex-container".to_string())
1736 .cluster("compute".to_string())
1737 .code(ContainerCode::Image {
1738 image: "test:latest".to_string(),
1739 })
1740 .cpu(ResourceSpec {
1741 min: "1".to_string(),
1742 desired: "1".to_string(),
1743 })
1744 .memory(ResourceSpec {
1745 min: "1Gi".to_string(),
1746 desired: "1Gi".to_string(),
1747 })
1748 .port(8080)
1749 .public_endpoint(PublicEndpoint {
1750 name: "web".to_string(),
1751 port: 8080,
1752 protocol: ExposeProtocol::Http,
1753 host_label: Some(APEX_HOST_LABEL.to_string()),
1754 wildcard_subdomains: false,
1755 })
1756 .public_endpoint(PublicEndpoint {
1757 name: "admin".to_string(),
1758 port: 8080,
1759 protocol: ExposeProtocol::Http,
1760 host_label: Some(APEX_HOST_LABEL.to_string()),
1761 wildcard_subdomains: false,
1762 })
1763 .replicas(1)
1764 .permissions("test".to_string())
1765 .build();
1766
1767 assert!(container.validate_public_endpoints().is_err());
1768 }
1769
1770 #[test]
1771 fn test_container_empty_ports_validation() {
1772 let container = Container::new("no-ports".to_string())
1773 .cluster("compute".to_string())
1774 .code(ContainerCode::Image {
1775 image: "test:latest".to_string(),
1776 })
1777 .cpu(ResourceSpec {
1778 min: "1".to_string(),
1779 desired: "1".to_string(),
1780 })
1781 .memory(ResourceSpec {
1782 min: "1Gi".to_string(),
1783 desired: "1Gi".to_string(),
1784 })
1785 .replicas(1)
1786 .permissions("test".to_string())
1787 .build();
1788
1789 assert!(container.validate_public_endpoints().is_ok());
1790 }
1791
1792 #[test]
1793 fn test_container_commands_enabled_defaults_false() {
1794 let container = Container::new("no-commands".to_string())
1795 .cluster("compute".to_string())
1796 .code(ContainerCode::Image {
1797 image: "test:latest".to_string(),
1798 })
1799 .cpu(ResourceSpec {
1800 min: "0.5".to_string(),
1801 desired: "1".to_string(),
1802 })
1803 .memory(ResourceSpec {
1804 min: "512Mi".to_string(),
1805 desired: "1Gi".to_string(),
1806 })
1807 .port(8080)
1808 .permissions("test".to_string())
1809 .build();
1810
1811 assert!(!container.commands_enabled);
1812 }
1813
1814 #[test]
1815 fn test_container_commands_enabled_builder() {
1816 let container = Container::new("cmd-container".to_string())
1817 .cluster("compute".to_string())
1818 .code(ContainerCode::Image {
1819 image: "test:latest".to_string(),
1820 })
1821 .cpu(ResourceSpec {
1822 min: "0.5".to_string(),
1823 desired: "1".to_string(),
1824 })
1825 .memory(ResourceSpec {
1826 min: "512Mi".to_string(),
1827 desired: "1Gi".to_string(),
1828 })
1829 .port(8080)
1830 .permissions("test".to_string())
1831 .commands_enabled(true)
1832 .build();
1833
1834 assert!(container.commands_enabled);
1835 }
1836
1837 #[test]
1838 fn test_container_commands_enabled_serializes_camel_case() {
1839 let container = Container::new("cmd-container".to_string())
1840 .cluster("compute".to_string())
1841 .code(ContainerCode::Image {
1842 image: "test:latest".to_string(),
1843 })
1844 .cpu(ResourceSpec {
1845 min: "0.5".to_string(),
1846 desired: "1".to_string(),
1847 })
1848 .memory(ResourceSpec {
1849 min: "512Mi".to_string(),
1850 desired: "1Gi".to_string(),
1851 })
1852 .port(8080)
1853 .permissions("test".to_string())
1854 .commands_enabled(true)
1855 .build();
1856
1857 let json = serde_json::to_value(&container).expect("container should serialize");
1858 assert_eq!(json["commandsEnabled"], true);
1859
1860 let deserialized: Container =
1861 serde_json::from_value(json).expect("container should deserialize");
1862 assert_eq!(deserialized, container);
1863 }
1864}