Skip to main content

alien_core/resources/
container.rs

1//! Container resource for long-running container workloads.
2//!
3//! A Container represents a deployable unit that runs on a ComputeCluster.
4//! It defines the container image, resource requirements, scaling configuration,
5//! and networking settings.
6//!
7//! Containers are orchestrated by the managed container backend, which handles:
8//! - Replica scheduling across machines
9//! - Autoscaling based on CPU, memory, or HTTP metrics
10//! - Health checking and crash recovery
11//! - Service discovery and internal networking
12//! - Load balancer registration for public-facing containers
13
14use 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/// Specifies the source of the container's executable code.
27#[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    /// Container image reference
32    #[serde(rename_all = "camelCase")]
33    Image {
34        /// Container image (e.g., `postgres:16`, `ghcr.io/myorg/myimage:latest`)
35        image: String,
36    },
37    /// Source code to be built
38    #[serde(rename_all = "camelCase")]
39    Source {
40        /// The source directory to build from
41        src: String,
42        /// Toolchain configuration with type-safe options
43        toolchain: ToolchainConfig,
44    },
45}
46
47/// Resource specification with min/desired values.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
50#[serde(rename_all = "camelCase")]
51pub struct ResourceSpec {
52    /// Minimum resource allocation
53    pub min: String,
54    /// Desired resource allocation (used by scheduler)
55    pub desired: String,
56}
57
58/// Allowed deployment-time resource quantities. These are choices, not autoscaling targets.
59#[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    /// Smallest permitted allocation.
64    pub min: String,
65    /// Largest permitted allocation.
66    pub max: String,
67    /// Allocation used when deployment settings omit a selection.
68    pub default: String,
69}
70
71/// Release-declared choices for each container resource dimension.
72#[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    /// Allowed CPU allocation in vCPUs or millicores.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub cpu: Option<ResourceChoiceRange>,
79    /// Allowed memory allocation in binary units.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub memory: Option<ResourceChoiceRange>,
82}
83
84/// GPU specification for a container.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
87#[serde(rename_all = "camelCase")]
88pub struct ContainerGpuSpec {
89    /// GPU type identifier (e.g., "nvidia-a100", "nvidia-t4")
90    #[serde(rename = "type")]
91    pub gpu_type: String,
92    /// Number of GPUs required (1-8)
93    pub count: u32,
94}
95
96/// Persistent storage configuration for stateful containers.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
99#[serde(rename_all = "camelCase")]
100pub struct PersistentStorage {
101    /// Storage size (e.g., "100Gi", "500Gi")
102    pub size: String,
103    /// Mount path inside the container
104    pub mount_path: String,
105    /// Key used to encrypt this volume and its snapshots. Cannot be changed after creation.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub encryption_key: Option<ResourceRef>,
108    /// Scheduled snapshots of each replica's volume. On by default.
109    #[serde(default)]
110    pub backups: VolumeBackups,
111}
112
113/// Hours between snapshots that every cloud's native snapshot scheduler supports.
114pub const VOLUME_BACKUP_INTERVAL_HOURS: [u32; 7] = [1, 2, 4, 6, 8, 12, 24];
115
116/// Most snapshots a volume may hold at once. Azure Disk Backup keeps at most 450
117/// scheduled snapshots per disk; the same limit applies everywhere so a stack is
118/// portable across clouds.
119pub const VOLUME_BACKUP_MAX_SNAPSHOTS: u32 = 450;
120
121/// Longest a snapshot may be kept. Azure Disk Backup keeps operational snapshots
122/// for at most a year; the same limit applies everywhere for portability.
123pub const VOLUME_BACKUP_MAX_RETENTION_DAYS: u32 = 365;
124
125/// Scheduled snapshots of a persistent volume.
126///
127/// The cloud's own scheduler takes the snapshots (AWS Data Lifecycle Manager,
128/// a Compute Engine snapshot schedule, or Azure Disk Backup), so they keep being
129/// taken while the deployment is unreachable. Snapshots are crash-consistent:
130/// the volume as it would be after a sudden power loss. When a container is
131/// deleted, Alien keeps one final snapshot of each volume.
132///
133/// Kubernetes deployments leave volume backups to the cluster's own tooling,
134/// and local deployments don't snapshot volumes. Neither reports volumes in
135/// `ContainerOutputs.volumes` or a `volumeBackups` status.
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
138#[serde(rename_all = "camelCase")]
139pub struct VolumeBackups {
140    /// Whether snapshots are taken. Defaults to true.
141    #[serde(default = "default_volume_backups_enabled")]
142    pub enabled: bool,
143    /// Hours between snapshots: 1, 2, 4, 6, 8, 12 or 24. Defaults to 24.
144    #[serde(default = "default_volume_backup_interval_hours")]
145    pub interval_hours: u32,
146    /// Days each snapshot is kept, at most 365. Defaults to 7.
147    #[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    /// Backups switched off.
175    pub fn disabled() -> Self {
176        Self {
177            enabled: false,
178            ..Self::default()
179        }
180    }
181
182    /// Explains why this schedule can't run on every cloud, or `None` when it can.
183    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/// Mounts an existing, setup-owned Kubernetes Secret into a Container pod.
215/// The Secret must exist in the deployment namespace before the workload starts.
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
218#[serde(rename_all = "camelCase")]
219pub struct KubernetesSecretMount {
220    /// Name of the existing Secret in the deployment namespace.
221    pub secret_name: String,
222    /// Directory where Kubernetes mounts the Secret's keys as read-only files.
223    pub mount_path: String,
224}
225
226/// HTTP probe used by Kubernetes for workload liveness or readiness.
227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
228#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
229#[serde(rename_all = "camelCase")]
230pub struct KubernetesHttpProbe {
231    /// Absolute HTTP path served by the container.
232    pub path: String,
233    /// Container port to check.
234    pub port: u16,
235}
236
237/// Relative scheduling importance of a workload.
238///
239/// On Kubernetes the deployment's cluster administrator maps each level to a
240/// PriorityClass at install time. Other platforms ignore it.
241#[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    /// The level name used in chart values and the Operator's class map.
253    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/// Security profile shared by container runtimes.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
266#[serde(rename_all = "camelCase")]
267pub enum ContainerSecurityProfile {
268    Restricted,
269}
270
271/// Container process identity and filesystem security.
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
274#[serde(rename_all = "camelCase")]
275pub struct ContainerSecurity {
276    /// Runtime security profile.
277    pub profile: ContainerSecurityProfile,
278    /// Numeric UID for the container process.
279    pub run_as_user: i64,
280    /// Numeric GID for the container process.
281    pub run_as_group: i64,
282    /// Mount the root filesystem read-only.
283    pub read_only_root_filesystem: bool,
284}
285
286/// Autoscaling configuration for stateless containers.
287#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
288#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
289#[serde(rename_all = "camelCase")]
290pub struct ContainerAutoscaling {
291    /// Minimum replicas (always running)
292    pub min: u32,
293    /// Initial desired replicas at container creation
294    pub desired: u32,
295    /// Maximum replicas under load
296    pub max: u32,
297    /// Target CPU utilization percentage for scaling (default: 70%)
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub target_cpu_percent: Option<f64>,
300    /// Target memory utilization percentage for scaling (default: 80%)
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub target_memory_percent: Option<f64>,
303    /// Target in-flight HTTP requests per replica
304    #[serde(skip_serializing_if = "Option::is_none")]
305    pub target_http_in_flight_per_replica: Option<u32>,
306    /// Maximum acceptable p95 HTTP latency in milliseconds
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub max_http_p95_latency_ms: Option<f64>,
309}
310
311/// HTTP health check configuration.
312#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
313#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
314#[serde(rename_all = "camelCase")]
315pub struct HealthCheck {
316    /// HTTP endpoint path to check (e.g., "/health", "/ready")
317    #[serde(default = "default_health_path")]
318    pub path: String,
319    /// Port to check (defaults to container port if not specified)
320    #[serde(skip_serializing_if = "Option::is_none")]
321    pub port: Option<u16>,
322    /// HTTP method to use for health check
323    #[serde(default = "default_health_method")]
324    pub method: String,
325    /// Request timeout in seconds (1-5)
326    #[serde(default = "default_timeout_seconds")]
327    pub timeout_seconds: u32,
328    /// Number of consecutive failures before marking replica unhealthy
329    #[serde(default = "default_failure_threshold")]
330    pub failure_threshold: u32,
331}
332
333impl Default for HealthCheck {
334    /// The values a health check takes for every field it leaves out; no port.
335    fn default() -> Self {
336        HealthCheck {
337            path: default_health_path(),
338            port: None,
339            method: default_health_method(),
340            timeout_seconds: default_timeout_seconds(),
341            failure_threshold: default_failure_threshold(),
342        }
343    }
344}
345
346fn default_health_path() -> String {
347    "/health".to_string()
348}
349
350fn default_health_method() -> String {
351    "GET".to_string()
352}
353
354fn default_timeout_seconds() -> u32 {
355    1
356}
357
358fn default_failure_threshold() -> u32 {
359    3
360}
361
362/// Container port configuration.
363#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
364#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
365#[serde(rename_all = "camelCase")]
366pub struct ContainerPort {
367    /// Port number
368    pub port: u16,
369}
370
371/// Outbound network restriction enforced outside the container.
372/// Internet access also permits this container's own replicas on declared TCP ports,
373/// own-service discovery, and the credential proxy for its own identity.
374/// Absence preserves the runtime's existing full-network behavior.
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
376#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
377#[serde(rename_all = "camelCase")]
378pub enum ContainerEgress {
379    /// Public addresses and DNS, plus own replicas on declared TCP ports and
380    /// the platform credential proxy for this identity.
381    /// Requires the restricted security profile and backend enforcement.
382    Internet,
383}
384
385/// Container resource for running long-running container workloads.
386///
387/// A Container defines a deployable unit that runs on a ComputeCluster.
388/// The managed container backend handles scheduling replicas across machines,
389/// autoscaling based on various metrics, and service discovery.
390///
391/// ## Example
392///
393/// ```rust
394/// use alien_core::{Container, ContainerCode, ResourceSpec, ContainerAutoscaling, PublicEndpoint, ExposeProtocol};
395///
396/// let container = Container::new("api".to_string())
397///     .cluster("compute".to_string())
398///     .code(ContainerCode::Image {
399///         image: "myapp:latest".to_string(),
400///     })
401///     .cpu(ResourceSpec { min: "0.5".to_string(), desired: "1".to_string() })
402///     .memory(ResourceSpec { min: "512Mi".to_string(), desired: "1Gi".to_string() })
403///     .port(8080)
404///     .public_endpoint(PublicEndpoint {
405///         name: "api".to_string(),
406///         port: 8080,
407///         protocol: ExposeProtocol::Http,
408///         host_label: None,
409///         wildcard_subdomains: false,
410///     })
411///     .autoscaling(ContainerAutoscaling {
412///         min: 2,
413///         desired: 3,
414///         max: 10,
415///         target_cpu_percent: Some(70.0),
416///         target_memory_percent: None,
417///         target_http_in_flight_per_replica: Some(100),
418///         max_http_p95_latency_ms: None,
419///     })
420///     .permissions("container-execution".to_string())
421///     .build();
422/// ```
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
424#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
425#[serde(rename_all = "camelCase", deny_unknown_fields)]
426#[builder(start_fn = new)]
427pub struct Container {
428    /// Unique identifier for the container.
429    /// Must be DNS-compatible: lowercase alphanumeric with hyphens.
430    #[builder(start_fn)]
431    pub id: String,
432
433    /// Resource links (dependencies)
434    #[builder(field)]
435    pub links: Vec<ResourceRef>,
436
437    /// Ports reachable by compute-cluster members and resources that link to this container.
438    #[builder(field)]
439    pub ports: Vec<ContainerPort>,
440
441    /// Existing Kubernetes Secrets mounted as read-only directories.
442    #[builder(field)]
443    #[serde(default, skip_serializing_if = "Vec::is_empty")]
444    pub kubernetes_secret_mounts: Vec<KubernetesSecretMount>,
445
446    /// Public endpoints exposed by the container.
447    #[builder(field)]
448    #[serde(default, skip_serializing_if = "Vec::is_empty")]
449    pub public_endpoints: Vec<PublicEndpoint>,
450
451    /// Optional public-internet-only egress. Requires restricted security and backend support.
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub egress: Option<ContainerEgress>,
454
455    /// Makes one HTTP port reachable from the control plane through the
456    /// manager's tunnel, over the operator's outbound connection. Nothing is
457    /// exposed on the deployment's network.
458    #[serde(default, skip_serializing_if = "Option::is_none")]
459    pub tunnel: Option<ContainerTunnel>,
460
461    /// Kubernetes liveness probe. Restarts an unhealthy container.
462    #[serde(skip_serializing_if = "Option::is_none")]
463    pub kubernetes_liveness_probe: Option<KubernetesHttpProbe>,
464
465    /// Kubernetes readiness probe. Removes an unready pod from Service endpoints.
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub kubernetes_readiness_probe: Option<KubernetesHttpProbe>,
468
469    /// Security settings shared by supported container runtimes.
470    #[serde(skip_serializing_if = "Option::is_none")]
471    pub security: Option<ContainerSecurity>,
472
473    /// ComputeCluster resource ID that this container runs on.
474    /// If None, will be auto-assigned by ComputeClusterMutation at deployment time.
475    #[serde(skip_serializing_if = "Option::is_none")]
476    pub cluster: Option<String>,
477
478    /// Container code (image or source)
479    pub code: ContainerCode,
480
481    /// CPU resource requirements
482    pub cpu: ResourceSpec,
483
484    /// Memory resource requirements (must use Ki/Mi/Gi/Ti suffix)
485    pub memory: ResourceSpec,
486
487    /// Optional deployment-time CPU and memory choices. Fixed declarations stay fixed.
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub resource_choices: Option<ContainerResourceChoices>,
490
491    /// GPU requirements (optional)
492    #[serde(skip_serializing_if = "Option::is_none")]
493    pub gpu: Option<ContainerGpuSpec>,
494
495    /// Ephemeral storage requirement (e.g., "10Gi")
496    #[serde(skip_serializing_if = "Option::is_none")]
497    pub ephemeral_storage: Option<String>,
498
499    /// Persistent storage configuration (only for stateful containers)
500    #[serde(skip_serializing_if = "Option::is_none")]
501    pub persistent_storage: Option<PersistentStorage>,
502
503    /// Fixed replica count (for stateful containers or stateless without autoscaling)
504    #[serde(skip_serializing_if = "Option::is_none")]
505    pub replicas: Option<u32>,
506
507    /// Autoscaling configuration (only for stateless containers)
508    #[serde(skip_serializing_if = "Option::is_none")]
509    pub autoscaling: Option<ContainerAutoscaling>,
510
511    /// Whether container is stateful (gets stable ordinals, optional persistent volumes)
512    #[builder(default = false)]
513    #[serde(default)]
514    pub stateful: bool,
515
516    /// Environment variables
517    #[builder(default)]
518    #[serde(default)]
519    pub environment: HashMap<String, String>,
520
521    /// Capacity group to run on (must exist in the cluster)
522    /// If not specified, containers are scheduled to any available group.
523    #[serde(skip_serializing_if = "Option::is_none")]
524    pub pool: Option<String>,
525
526    /// Permission profile name
527    pub permissions: String,
528
529    /// Health check configuration
530    #[serde(skip_serializing_if = "Option::is_none")]
531    pub health_check: Option<HealthCheck>,
532
533    /// Command to override image default
534    #[serde(skip_serializing_if = "Option::is_none")]
535    pub command: Option<Vec<String>>,
536
537    /// Whether the container can receive remote commands via the Commands protocol.
538    /// When enabled, an app-owned command receiver can lease pending commands
539    /// for this Container and execute registered handlers.
540    #[builder(default = default_commands_enabled())]
541    #[serde(default = "default_commands_enabled")]
542    #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
543    pub commands_enabled: bool,
544
545    /// Grace period in seconds for stopping replicas during updates, drains, and deletes.
546    ///
547    /// When omitted, the runtime backend applies its default. Valid values are
548    /// 1 second through 24 hours.
549    #[serde(skip_serializing_if = "Option::is_none")]
550    #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
551    pub stop_grace_period_seconds: Option<u32>,
552
553    /// Relative scheduling importance. On Kubernetes the cluster administrator maps each
554    /// level to a PriorityClass at install time; unset leaves the pod without one. Other
555    /// platforms ignore it.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub priority: Option<WorkloadPriority>,
558}
559
560impl Container {
561    /// The resource type identifier for Container
562    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
563
564    /// Returns the container's unique identifier.
565    pub fn id(&self) -> &str {
566        &self.id
567    }
568
569    /// Returns the permission profile name for this container.
570    pub fn get_permissions(&self) -> &str {
571        &self.permissions
572    }
573
574    /// Returns true if this container is stateless (not stateful).
575    pub fn is_stateless(&self) -> bool {
576        !self.stateful
577    }
578
579    /// Validate resource-local network options; preflight also checks source existence and backend support.
580    pub fn validate_network_settings(&self) -> Result<()> {
581        let invalid = |reason: String| {
582            AlienError::new(ErrorData::InvalidResourceUpdate {
583                resource_id: self.id.clone(),
584                reason,
585            })
586        };
587        if self.egress.is_some()
588            && !self
589                .security
590                .as_ref()
591                .is_some_and(|security| security.profile == ContainerSecurityProfile::Restricted)
592        {
593            return Err(invalid(
594                "container egress internet requires security.profile restricted".into(),
595            ));
596        }
597        Ok(())
598    }
599
600    /// Validates the public endpoint configuration.
601    fn validate_public_endpoints(&self) -> Result<()> {
602        let mut endpoint_names = std::collections::HashSet::new();
603        let mut backend_ports = std::collections::HashSet::new();
604        let mut apex_endpoint_name: Option<&str> = None;
605
606        for endpoint in &self.public_endpoints {
607            endpoint.validate_for_resource(&self.id)?;
608
609            if !endpoint_names.insert(endpoint.name.as_str()) {
610                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
611                    resource_id: self.id.clone(),
612                    reason: format!("duplicate public endpoint name '{}'", endpoint.name),
613                }));
614            }
615
616            if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
617                if let Some(existing_name) = apex_endpoint_name {
618                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
619                        resource_id: self.id.clone(),
620                        reason: format!(
621                            "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
622                            existing_name
623                        ),
624                    }));
625                }
626                apex_endpoint_name = Some(endpoint.name.as_str());
627            }
628
629            backend_ports.insert(endpoint.port);
630
631            if !self.ports.iter().any(|port| port.port == endpoint.port) {
632                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
633                    resource_id: self.id.clone(),
634                    reason: format!(
635                        "public endpoint '{}' references undeclared port {}",
636                        endpoint.name, endpoint.port
637                    ),
638                }));
639            }
640        }
641
642        if backend_ports.len() > 1 {
643            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
644                resource_id: self.id.clone(),
645                reason:
646                    "public endpoints on one container must currently route to the same backend port"
647                        .to_string(),
648            }));
649        }
650
651        Ok(())
652    }
653}
654
655fn default_commands_enabled() -> bool {
656    false
657}
658
659impl<S: container_builder::State> ContainerBuilder<S> {
660    /// Links the container to another resource with specified permissions.
661    pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
662    where
663        for<'a> &'a R: Into<ResourceRef>,
664    {
665        let resource_ref: ResourceRef = resource.into();
666        self.links.push(resource_ref);
667        self
668    }
669
670    /// Adds an internal-only port to the container.
671    pub fn port(mut self, port: u16) -> Self {
672        self.ports.push(ContainerPort { port });
673        self
674    }
675
676    /// Mounts an existing Kubernetes Secret without copying its value into the stack.
677    pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
678        self.kubernetes_secret_mounts.push(mount);
679        self
680    }
681
682    /// Exposes a named public endpoint.
683    pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
684        if !self.ports.iter().any(|p| p.port == endpoint.port) {
685            self.ports.push(ContainerPort {
686                port: endpoint.port,
687            });
688        }
689        self.public_endpoints.push(endpoint);
690        self
691    }
692}
693
694/// Container status in the managed container backend.
695#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
696#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
697#[serde(rename_all = "camelCase")]
698pub enum ContainerStatus {
699    /// Waiting for replicas to start
700    Pending,
701    /// Min replicas healthy and serving
702    Running,
703    /// Manually stopped
704    Stopped,
705    /// Something is wrong — see statusReason/statusMessage; scheduler keeps retrying.
706    /// Covers all failure modes: crash-looping, unschedulable, replica failures, etc.
707    Failing,
708}
709
710/// Status of a single container replica.
711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
712#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
713#[serde(rename_all = "camelCase")]
714pub struct ReplicaStatus {
715    /// Replica ID (e.g., "api-0", "api-1")
716    pub replica_id: String,
717    /// Ordinal (for stateful containers)
718    pub ordinal: Option<u32>,
719    /// Machine ID the replica is running on
720    pub machine_id: Option<String>,
721    /// Whether the replica is healthy
722    pub healthy: bool,
723    /// Container IP address (for service discovery)
724    pub container_ip: Option<String>,
725}
726
727/// A container port reachable from the control plane through the manager.
728///
729/// Requests to `/v1/deployments/{deployment}/tunnels/{container}/...` on the
730/// manager are forwarded to this port over the operator's outbound
731/// connection, so the control plane can call the service without any inbound
732/// network path into the deployment.
733#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
734#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
735#[serde(rename_all = "camelCase", deny_unknown_fields)]
736pub struct ContainerTunnel {
737    /// Container port that serves HTTP. Must be one of the container's ports.
738    pub port: u16,
739}
740
741/// Outputs generated by a successfully provisioned Container.
742#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
743#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
744#[serde(rename_all = "camelCase")]
745pub struct ContainerOutputs {
746    /// Container name in the managed container backend
747    pub name: String,
748    /// Current container status
749    pub status: ContainerStatus,
750    /// Number of current replicas
751    pub current_replicas: u32,
752    /// Desired number of replicas
753    pub desired_replicas: u32,
754    /// Internal DNS name (e.g., "api.svc")
755    pub internal_dns: String,
756    /// Public endpoints resolved for this container.
757    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
758    pub public_endpoints: HashMap<String, PublicEndpointOutput>,
759    /// Internal URLs keyed by port for cluster members and linking resources.
760    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
761    pub internal_urls: HashMap<u16, String>,
762    /// Status of each replica
763    pub replicas: Vec<ReplicaStatus>,
764    /// Persistent volumes, one per replica ordinal, with their latest snapshot.
765    #[serde(default, skip_serializing_if = "Vec::is_empty")]
766    pub volumes: Vec<VolumeOutput>,
767    /// Whether the persistent volumes' snapshot schedule is in place.
768    #[serde(default, skip_serializing_if = "Option::is_none")]
769    pub volume_backups: Option<VolumeBackupsStatus>,
770}
771
772/// Whether a container's snapshot schedule is in place.
773#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
774#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
775#[serde(rename_all = "camelCase")]
776pub struct VolumeBackupsStatus {
777    /// Current state of the schedule
778    pub state: VolumeBackupsState,
779    /// What is missing when the state is `setupRequired`
780    #[serde(skip_serializing_if = "Option::is_none")]
781    pub message: Option<String>,
782}
783
784/// State of a container's snapshot schedule.
785#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
786#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
787#[serde(rename_all = "camelCase")]
788pub enum VolumeBackupsState {
789    /// The cloud's scheduler is taking snapshots.
790    Active,
791    /// Backups are turned off in the stack.
792    Disabled,
793    /// The deployment's management permissions predate volume backups. The
794    /// container keeps running without a schedule until the installation's
795    /// setup is updated; the controller then applies the schedule by itself.
796    SetupRequired,
797}
798
799/// A replica's persistent volume and its latest completed snapshot.
800#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
801#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
802#[serde(rename_all = "camelCase")]
803pub struct VolumeOutput {
804    /// Replica ordinal the volume belongs to
805    pub ordinal: u32,
806    /// Cloud ID of the volume (EBS volume ID, Persistent Disk name, or Managed Disk ID)
807    pub volume_id: String,
808    /// Zone the volume lives in
809    pub zone: String,
810    /// Cloud ID of the latest completed snapshot, if any
811    #[serde(skip_serializing_if = "Option::is_none")]
812    pub last_snapshot_id: Option<String>,
813    /// When the latest completed snapshot was started (RFC 3339)
814    #[serde(skip_serializing_if = "Option::is_none")]
815    pub last_snapshot_at: Option<String>,
816    /// The latest volume restore performed on this ordinal, if any
817    #[serde(skip_serializing_if = "Option::is_none")]
818    pub last_restore: Option<VolumeRestoreOutput>,
819}
820
821/// A completed volume restore.
822#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
823#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
824#[serde(rename_all = "camelCase")]
825pub struct VolumeRestoreOutput {
826    /// ID of the restore request
827    pub request_id: String,
828    /// Snapshot the volume was restored from
829    pub snapshot_id: String,
830    /// Snapshot of the replaced volume, taken just before it was deleted
831    pub replaced_volume_snapshot_id: String,
832    /// When the restored volume was put in place (RFC 3339)
833    pub completed_at: String,
834}
835
836impl ResourceOutputsDefinition for ContainerOutputs {
837    fn get_resource_type(&self) -> ResourceType {
838        Container::RESOURCE_TYPE.clone()
839    }
840
841    fn as_any(&self) -> &dyn Any {
842        self
843    }
844
845    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
846        Box::new(self.clone())
847    }
848
849    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
850        other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
851    }
852
853    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
854        serde_json::to_value(self)
855    }
856}
857
858impl ResourceDefinition for Container {
859    fn get_resource_type(&self) -> ResourceType {
860        Self::RESOURCE_TYPE
861    }
862
863    fn id(&self) -> &str {
864        &self.id
865    }
866
867    fn replace_after_failed_create_is_safe(&self) -> bool {
868        // Deleting it destroys the persistent volumes of a stateful container.
869        !(self.stateful && self.persistent_storage.is_some())
870    }
871
872    fn get_dependencies(&self) -> Vec<ResourceRef> {
873        let mut deps = self.links.clone();
874        if let Some(key) = self
875            .persistent_storage
876            .as_ref()
877            .and_then(|storage| storage.encryption_key.as_ref())
878        {
879            deps.push(key.clone());
880        }
881        // Add dependency on the container cluster if explicitly specified.
882        // If None, ComputeClusterMutation will auto-assign at deployment time.
883        if let Some(cluster) = &self.cluster {
884            deps.push(ResourceRef::new(
885                ComputeCluster::RESOURCE_TYPE.clone(),
886                cluster,
887            ));
888        }
889        deps
890    }
891
892    fn get_permissions(&self) -> Option<&str> {
893        Some(&self.permissions)
894    }
895
896    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
897        let new_container = new_config
898            .as_any()
899            .downcast_ref::<Container>()
900            .ok_or_else(|| {
901                AlienError::new(ErrorData::UnexpectedResourceType {
902                    resource_id: self.id.clone(),
903                    expected: Self::RESOURCE_TYPE,
904                    actual: new_config.get_resource_type(),
905                })
906            })?;
907
908        // Validate the new config's public endpoints.
909        new_container.validate_public_endpoints()?;
910        new_container.validate_network_settings()?;
911
912        if self.id != new_container.id {
913            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
914                resource_id: self.id.clone(),
915                reason: "the 'id' field is immutable".to_string(),
916            }));
917        }
918
919        // Cluster is immutable
920        if self.cluster != new_container.cluster {
921            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
922                resource_id: self.id.clone(),
923                reason: "the 'cluster' field is immutable".to_string(),
924            }));
925        }
926
927        // Stateful is immutable
928        if self.stateful != new_container.stateful {
929            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
930                resource_id: self.id.clone(),
931                reason: "the 'stateful' field is immutable".to_string(),
932            }));
933        }
934
935        let old_key = self
936            .persistent_storage
937            .as_ref()
938            .and_then(|storage| storage.encryption_key.as_ref());
939        let new_key = new_container
940            .persistent_storage
941            .as_ref()
942            .and_then(|storage| storage.encryption_key.as_ref());
943        if old_key != new_key {
944            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
945                resource_id: self.id.clone(),
946                reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
947            }));
948        }
949
950        // Ports are immutable (requires load balancer reconfiguration)
951        if self.ports != new_container.ports {
952            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
953                resource_id: self.id.clone(),
954                reason: "the 'ports' field is immutable".to_string(),
955            }));
956        }
957
958        if self.public_endpoints != new_container.public_endpoints {
959            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
960                resource_id: self.id.clone(),
961                reason: "the 'publicEndpoints' field is immutable".to_string(),
962            }));
963        }
964
965        // Pool (capacity group) is immutable
966        if self.pool != new_container.pool {
967            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
968                resource_id: self.id.clone(),
969                reason: "the 'pool' field is immutable".to_string(),
970            }));
971        }
972
973        Ok(())
974    }
975
976    fn as_any(&self) -> &dyn Any {
977        self
978    }
979
980    fn as_any_mut(&mut self) -> &mut dyn Any {
981        self
982    }
983
984    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
985        Box::new(self.clone())
986    }
987
988    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
989        other.as_any().downcast_ref::<Container>() == Some(self)
990    }
991
992    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
993        serde_json::to_value(self)
994    }
995}
996
997#[cfg(test)]
998mod tests {
999    use super::*;
1000    use crate::resources::ExposeProtocol;
1001
1002    fn network_container() -> Container {
1003        Container::new("api".to_string())
1004            .code(ContainerCode::Image {
1005                image: "example:latest".into(),
1006            })
1007            .cpu(ResourceSpec {
1008                min: "1".into(),
1009                desired: "1".into(),
1010            })
1011            .memory(ResourceSpec {
1012                min: "512Mi".into(),
1013                desired: "512Mi".into(),
1014            })
1015            .permissions("execution".into())
1016            .public_endpoint(PublicEndpoint {
1017                name: "web".into(),
1018                port: 8080,
1019                protocol: ExposeProtocol::Http,
1020                host_label: None,
1021                wildcard_subdomains: false,
1022            })
1023            .build()
1024    }
1025
1026    #[test]
1027    fn internet_egress_requires_restricted_security_and_is_opt_in() {
1028        let mut container = network_container();
1029        assert!(serde_json::to_value(&container)
1030            .unwrap()
1031            .get("egress")
1032            .is_none());
1033        container.egress = Some(ContainerEgress::Internet);
1034        assert!(container.validate_update(&container).is_err());
1035        container.security = Some(ContainerSecurity {
1036            profile: ContainerSecurityProfile::Restricted,
1037            run_as_user: 65532,
1038            run_as_group: 65532,
1039            read_only_root_filesystem: true,
1040        });
1041        container.validate_update(&container).unwrap();
1042        assert_eq!(
1043            serde_json::to_value(&container).unwrap()["egress"],
1044            "internet"
1045        );
1046    }
1047
1048    #[test]
1049    fn test_container_creation_with_autoscaling() {
1050        let container = Container::new("api".to_string())
1051            .cluster("compute".to_string())
1052            .code(ContainerCode::Image {
1053                image: "myapp:latest".to_string(),
1054            })
1055            .cpu(ResourceSpec {
1056                min: "0.5".to_string(),
1057                desired: "1".to_string(),
1058            })
1059            .memory(ResourceSpec {
1060                min: "512Mi".to_string(),
1061                desired: "1Gi".to_string(),
1062            })
1063            .port(8080)
1064            .public_endpoint(PublicEndpoint {
1065                name: "api".to_string(),
1066                port: 8080,
1067                protocol: ExposeProtocol::Http,
1068                host_label: None,
1069                wildcard_subdomains: false,
1070            })
1071            .autoscaling(ContainerAutoscaling {
1072                min: 2,
1073                desired: 3,
1074                max: 10,
1075                target_cpu_percent: Some(70.0),
1076                target_memory_percent: None,
1077                target_http_in_flight_per_replica: Some(100),
1078                max_http_p95_latency_ms: None,
1079            })
1080            .permissions("container-execution".to_string())
1081            .build();
1082
1083        assert_eq!(container.id(), "api");
1084        assert_eq!(container.cluster, Some("compute".to_string()));
1085        assert!(!container.stateful);
1086        assert!(container.autoscaling.is_some());
1087        assert_eq!(container.ports.len(), 1);
1088        assert_eq!(container.ports[0].port, 8080);
1089    }
1090
1091    #[test]
1092    fn container_serializes_stop_grace_period_when_set() {
1093        let container = Container::new("api".to_string())
1094            .cluster("compute".to_string())
1095            .code(ContainerCode::Image {
1096                image: "myapp:latest".to_string(),
1097            })
1098            .cpu(ResourceSpec {
1099                min: "0.5".to_string(),
1100                desired: "1".to_string(),
1101            })
1102            .memory(ResourceSpec {
1103                min: "512Mi".to_string(),
1104                desired: "1Gi".to_string(),
1105            })
1106            .port(8080)
1107            .permissions("container-execution".to_string())
1108            .stop_grace_period_seconds(21_600)
1109            .build();
1110
1111        let json = serde_json::to_value(&container).expect("container should serialize");
1112        assert_eq!(json["stopGracePeriodSeconds"], 21_600);
1113    }
1114
1115    #[test]
1116    fn container_omits_stop_grace_period_when_absent() {
1117        let container = Container::new("api".to_string())
1118            .cluster("compute".to_string())
1119            .code(ContainerCode::Image {
1120                image: "myapp:latest".to_string(),
1121            })
1122            .cpu(ResourceSpec {
1123                min: "0.5".to_string(),
1124                desired: "1".to_string(),
1125            })
1126            .memory(ResourceSpec {
1127                min: "512Mi".to_string(),
1128                desired: "1Gi".to_string(),
1129            })
1130            .port(8080)
1131            .permissions("container-execution".to_string())
1132            .build();
1133
1134        let json = serde_json::to_value(&container).expect("container should serialize");
1135        assert!(json.get("stopGracePeriodSeconds").is_none());
1136    }
1137
1138    #[test]
1139    fn test_stateful_container_with_storage() {
1140        let container = Container::new("postgres".to_string())
1141            .cluster("compute".to_string())
1142            .code(ContainerCode::Image {
1143                image: "postgres:16".to_string(),
1144            })
1145            .cpu(ResourceSpec {
1146                min: "1".to_string(),
1147                desired: "2".to_string(),
1148            })
1149            .memory(ResourceSpec {
1150                min: "2Gi".to_string(),
1151                desired: "4Gi".to_string(),
1152            })
1153            .port(5432)
1154            .stateful(true)
1155            .replicas(1)
1156            .persistent_storage(PersistentStorage {
1157                encryption_key: None,
1158                size: "100Gi".to_string(),
1159                mount_path: "/var/lib/postgresql/data".to_string(),
1160                backups: VolumeBackups::default(),
1161            })
1162            .permissions("database".to_string())
1163            .build();
1164
1165        assert_eq!(container.id(), "postgres");
1166        assert!(container.stateful);
1167        assert!(container.replicas.is_some());
1168        assert!(container.persistent_storage.is_some());
1169    }
1170
1171    #[test]
1172    fn test_public_container() {
1173        let container = Container::new("frontend".to_string())
1174            .cluster("compute".to_string())
1175            .code(ContainerCode::Image {
1176                image: "frontend:latest".to_string(),
1177            })
1178            .cpu(ResourceSpec {
1179                min: "0.25".to_string(),
1180                desired: "0.5".to_string(),
1181            })
1182            .memory(ResourceSpec {
1183                min: "256Mi".to_string(),
1184                desired: "512Mi".to_string(),
1185            })
1186            .port(3000)
1187            .public_endpoint(PublicEndpoint {
1188                name: "web".to_string(),
1189                port: 3000,
1190                protocol: ExposeProtocol::Http,
1191                host_label: None,
1192                wildcard_subdomains: false,
1193            })
1194            .autoscaling(ContainerAutoscaling {
1195                min: 2,
1196                desired: 2,
1197                max: 20,
1198                target_cpu_percent: None,
1199                target_memory_percent: None,
1200                target_http_in_flight_per_replica: Some(50),
1201                max_http_p95_latency_ms: Some(100.0),
1202            })
1203            .health_check(HealthCheck {
1204                path: "/health".to_string(),
1205                port: None,
1206                method: "GET".to_string(),
1207                timeout_seconds: 1,
1208                failure_threshold: 3,
1209            })
1210            .permissions("frontend".to_string())
1211            .build();
1212
1213        assert_eq!(container.ports[0].port, 3000);
1214        assert_eq!(container.public_endpoints[0].name, "web");
1215        assert!(container.health_check.is_some());
1216    }
1217
1218    #[test]
1219    fn test_public_container_endpoint_options() {
1220        let container = Container::new("router".to_string())
1221            .cluster("compute".to_string())
1222            .code(ContainerCode::Image {
1223                image: "router:latest".to_string(),
1224            })
1225            .cpu(ResourceSpec {
1226                min: "0.25".to_string(),
1227                desired: "0.5".to_string(),
1228            })
1229            .memory(ResourceSpec {
1230                min: "256Mi".to_string(),
1231                desired: "512Mi".to_string(),
1232            })
1233            .public_endpoint(PublicEndpoint {
1234                name: "gateway".to_string(),
1235                port: 8080,
1236                protocol: ExposeProtocol::Http,
1237                host_label: Some("gateway".to_string()),
1238                wildcard_subdomains: true,
1239            })
1240            .permissions("router".to_string())
1241            .build();
1242
1243        assert!(container.validate_public_endpoints().is_ok());
1244        assert_eq!(container.ports.len(), 1);
1245        assert_eq!(container.public_endpoints.len(), 1);
1246        assert_eq!(
1247            container.public_endpoints[0].host_label.as_deref(),
1248            Some("gateway")
1249        );
1250        assert!(container.public_endpoints[0].wildcard_subdomains);
1251    }
1252
1253    #[test]
1254    fn test_public_container_rejects_invalid_host_label() {
1255        let container = Container::new("router".to_string())
1256            .cluster("compute".to_string())
1257            .code(ContainerCode::Image {
1258                image: "router:latest".to_string(),
1259            })
1260            .cpu(ResourceSpec {
1261                min: "0.25".to_string(),
1262                desired: "0.5".to_string(),
1263            })
1264            .memory(ResourceSpec {
1265                min: "256Mi".to_string(),
1266                desired: "512Mi".to_string(),
1267            })
1268            .public_endpoint(PublicEndpoint {
1269                name: "gateway".to_string(),
1270                port: 8080,
1271                protocol: ExposeProtocol::Http,
1272                host_label: Some("bad.label".to_string()),
1273                wildcard_subdomains: true,
1274            })
1275            .permissions("router".to_string())
1276            .build();
1277
1278        assert!(container.validate_public_endpoints().is_err());
1279    }
1280
1281    #[test]
1282    fn test_container_with_links() {
1283        use crate::Storage;
1284
1285        let storage = Storage::new("data".to_string()).build();
1286
1287        let container = Container::new("worker".to_string())
1288            .cluster("compute".to_string())
1289            .code(ContainerCode::Image {
1290                image: "worker:latest".to_string(),
1291            })
1292            .cpu(ResourceSpec {
1293                min: "0.5".to_string(),
1294                desired: "1".to_string(),
1295            })
1296            .memory(ResourceSpec {
1297                min: "512Mi".to_string(),
1298                desired: "1Gi".to_string(),
1299            })
1300            .port(8080)
1301            .replicas(3)
1302            .link(&storage)
1303            .permissions("worker".to_string())
1304            .build();
1305
1306        // Should have 2 dependencies: cluster + linked storage
1307        let deps = container.get_dependencies();
1308        assert_eq!(deps.len(), 2);
1309    }
1310
1311    #[test]
1312    fn test_container_validate_update_immutable_cluster() {
1313        let container1 = Container::new("api".to_string())
1314            .cluster("cluster-1".to_string())
1315            .code(ContainerCode::Image {
1316                image: "myapp:v1".to_string(),
1317            })
1318            .cpu(ResourceSpec {
1319                min: "0.5".to_string(),
1320                desired: "1".to_string(),
1321            })
1322            .memory(ResourceSpec {
1323                min: "512Mi".to_string(),
1324                desired: "1Gi".to_string(),
1325            })
1326            .port(8080)
1327            .replicas(2)
1328            .permissions("execution".to_string())
1329            .build();
1330
1331        let container2 = Container::new("api".to_string())
1332            .cluster("cluster-2".to_string()) // Changed cluster
1333            .code(ContainerCode::Image {
1334                image: "myapp:v2".to_string(),
1335            })
1336            .cpu(ResourceSpec {
1337                min: "0.5".to_string(),
1338                desired: "1".to_string(),
1339            })
1340            .memory(ResourceSpec {
1341                min: "512Mi".to_string(),
1342                desired: "1Gi".to_string(),
1343            })
1344            .port(8080)
1345            .replicas(2)
1346            .permissions("execution".to_string())
1347            .build();
1348
1349        let result = container1.validate_update(&container2);
1350        assert!(result.is_err());
1351    }
1352
1353    #[test]
1354    fn test_container_validate_update_allowed_changes() {
1355        let container1 = Container::new("api".to_string())
1356            .cluster("compute".to_string())
1357            .code(ContainerCode::Image {
1358                image: "myapp:v1".to_string(),
1359            })
1360            .cpu(ResourceSpec {
1361                min: "0.5".to_string(),
1362                desired: "1".to_string(),
1363            })
1364            .memory(ResourceSpec {
1365                min: "512Mi".to_string(),
1366                desired: "1Gi".to_string(),
1367            })
1368            .port(8080)
1369            .replicas(2)
1370            .permissions("execution".to_string())
1371            .build();
1372
1373        let container2 = Container::new("api".to_string())
1374            .cluster("compute".to_string())
1375            .code(ContainerCode::Image {
1376                image: "myapp:v2".to_string(), // Image can change
1377            })
1378            .cpu(ResourceSpec {
1379                min: "1".to_string(), // Resources can change
1380                desired: "2".to_string(),
1381            })
1382            .memory(ResourceSpec {
1383                min: "1Gi".to_string(),
1384                desired: "2Gi".to_string(),
1385            })
1386            .port(8080)
1387            .replicas(5) // Replicas can change
1388            .permissions("execution".to_string())
1389            .build();
1390
1391        let result = container1.validate_update(&container2);
1392        assert!(result.is_ok());
1393    }
1394
1395    #[test]
1396    fn test_container_serialization() {
1397        let container = Container::new("test".to_string())
1398            .cluster("compute".to_string())
1399            .code(ContainerCode::Image {
1400                image: "test:latest".to_string(),
1401            })
1402            .cpu(ResourceSpec {
1403                min: "0.5".to_string(),
1404                desired: "1".to_string(),
1405            })
1406            .memory(ResourceSpec {
1407                min: "512Mi".to_string(),
1408                desired: "1Gi".to_string(),
1409            })
1410            .port(8080)
1411            .replicas(1)
1412            .permissions("test".to_string())
1413            .build();
1414
1415        let json = serde_json::to_string(&container).unwrap();
1416        let deserialized: Container = serde_json::from_str(&json).unwrap();
1417        assert_eq!(container, deserialized);
1418    }
1419
1420    #[test]
1421    fn test_container_multi_endpoint_validation() {
1422        let container = Container::new("multi-tcp".to_string())
1423            .cluster("compute".to_string())
1424            .code(ContainerCode::Image {
1425                image: "test:latest".to_string(),
1426            })
1427            .cpu(ResourceSpec {
1428                min: "1".to_string(),
1429                desired: "1".to_string(),
1430            })
1431            .memory(ResourceSpec {
1432                min: "1Gi".to_string(),
1433                desired: "1Gi".to_string(),
1434            })
1435            .port(8080)
1436            .public_endpoint(PublicEndpoint {
1437                name: "api".to_string(),
1438                port: 8080,
1439                protocol: ExposeProtocol::Http,
1440                host_label: None,
1441                wildcard_subdomains: false,
1442            })
1443            .public_endpoint(PublicEndpoint {
1444                name: "wildcard".to_string(),
1445                port: 8080,
1446                protocol: ExposeProtocol::Http,
1447                host_label: Some("wildcard".to_string()),
1448                wildcard_subdomains: true,
1449            })
1450            .replicas(1)
1451            .permissions("test".to_string())
1452            .build();
1453
1454        assert!(container.validate_public_endpoints().is_ok());
1455
1456        let invalid_container = Container::new("multi-http".to_string())
1457            .cluster("compute".to_string())
1458            .code(ContainerCode::Image {
1459                image: "test:latest".to_string(),
1460            })
1461            .cpu(ResourceSpec {
1462                min: "1".to_string(),
1463                desired: "1".to_string(),
1464            })
1465            .memory(ResourceSpec {
1466                min: "1Gi".to_string(),
1467                desired: "1Gi".to_string(),
1468            })
1469            .port(8080)
1470            .port(9090)
1471            .public_endpoint(PublicEndpoint {
1472                name: "api".to_string(),
1473                port: 8080,
1474                protocol: ExposeProtocol::Http,
1475                host_label: None,
1476                wildcard_subdomains: false,
1477            })
1478            .public_endpoint(PublicEndpoint {
1479                name: "admin".to_string(),
1480                port: 9090,
1481                protocol: ExposeProtocol::Http,
1482                host_label: None,
1483                wildcard_subdomains: false,
1484            })
1485            .replicas(1)
1486            .permissions("test".to_string())
1487            .build();
1488
1489        assert!(invalid_container.validate_public_endpoints().is_err());
1490    }
1491
1492    #[test]
1493    fn container_rejects_multiple_apex_public_endpoints() {
1494        let container = Container::new("apex-container".to_string())
1495            .cluster("compute".to_string())
1496            .code(ContainerCode::Image {
1497                image: "test:latest".to_string(),
1498            })
1499            .cpu(ResourceSpec {
1500                min: "1".to_string(),
1501                desired: "1".to_string(),
1502            })
1503            .memory(ResourceSpec {
1504                min: "1Gi".to_string(),
1505                desired: "1Gi".to_string(),
1506            })
1507            .port(8080)
1508            .public_endpoint(PublicEndpoint {
1509                name: "web".to_string(),
1510                port: 8080,
1511                protocol: ExposeProtocol::Http,
1512                host_label: Some(APEX_HOST_LABEL.to_string()),
1513                wildcard_subdomains: false,
1514            })
1515            .public_endpoint(PublicEndpoint {
1516                name: "admin".to_string(),
1517                port: 8080,
1518                protocol: ExposeProtocol::Http,
1519                host_label: Some(APEX_HOST_LABEL.to_string()),
1520                wildcard_subdomains: false,
1521            })
1522            .replicas(1)
1523            .permissions("test".to_string())
1524            .build();
1525
1526        assert!(container.validate_public_endpoints().is_err());
1527    }
1528
1529    #[test]
1530    fn test_container_empty_ports_validation() {
1531        let container = Container::new("no-ports".to_string())
1532            .cluster("compute".to_string())
1533            .code(ContainerCode::Image {
1534                image: "test:latest".to_string(),
1535            })
1536            .cpu(ResourceSpec {
1537                min: "1".to_string(),
1538                desired: "1".to_string(),
1539            })
1540            .memory(ResourceSpec {
1541                min: "1Gi".to_string(),
1542                desired: "1Gi".to_string(),
1543            })
1544            .replicas(1)
1545            .permissions("test".to_string())
1546            .build();
1547
1548        assert!(container.validate_public_endpoints().is_ok());
1549    }
1550
1551    #[test]
1552    fn test_container_commands_enabled_defaults_false() {
1553        let container = Container::new("no-commands".to_string())
1554            .cluster("compute".to_string())
1555            .code(ContainerCode::Image {
1556                image: "test:latest".to_string(),
1557            })
1558            .cpu(ResourceSpec {
1559                min: "0.5".to_string(),
1560                desired: "1".to_string(),
1561            })
1562            .memory(ResourceSpec {
1563                min: "512Mi".to_string(),
1564                desired: "1Gi".to_string(),
1565            })
1566            .port(8080)
1567            .permissions("test".to_string())
1568            .build();
1569
1570        assert!(!container.commands_enabled);
1571    }
1572
1573    #[test]
1574    fn test_container_commands_enabled_builder() {
1575        let container = Container::new("cmd-container".to_string())
1576            .cluster("compute".to_string())
1577            .code(ContainerCode::Image {
1578                image: "test:latest".to_string(),
1579            })
1580            .cpu(ResourceSpec {
1581                min: "0.5".to_string(),
1582                desired: "1".to_string(),
1583            })
1584            .memory(ResourceSpec {
1585                min: "512Mi".to_string(),
1586                desired: "1Gi".to_string(),
1587            })
1588            .port(8080)
1589            .permissions("test".to_string())
1590            .commands_enabled(true)
1591            .build();
1592
1593        assert!(container.commands_enabled);
1594    }
1595
1596    #[test]
1597    fn test_container_commands_enabled_serializes_camel_case() {
1598        let container = Container::new("cmd-container".to_string())
1599            .cluster("compute".to_string())
1600            .code(ContainerCode::Image {
1601                image: "test:latest".to_string(),
1602            })
1603            .cpu(ResourceSpec {
1604                min: "0.5".to_string(),
1605                desired: "1".to_string(),
1606            })
1607            .memory(ResourceSpec {
1608                min: "512Mi".to_string(),
1609                desired: "1Gi".to_string(),
1610            })
1611            .port(8080)
1612            .permissions("test".to_string())
1613            .commands_enabled(true)
1614            .build();
1615
1616        let json = serde_json::to_value(&container).expect("container should serialize");
1617        assert_eq!(json["commandsEnabled"], true);
1618
1619        let deserialized: Container =
1620            serde_json::from_value(json).expect("container should deserialize");
1621        assert_eq!(deserialized, container);
1622    }
1623}