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    /// Set by `alien build` when the container's command receiver reads its
546    /// credential from `ALIEN_COMMANDS_CAPABILITY_FILE`. Absent means the
547    /// receiver may be older, so a deployer that rotates credentials keeps
548    /// the long-lived `ALIEN_COMMANDS_TOKEN` for it. Build output replaces any
549    /// value written in the stack definition.
550    #[builder(default)]
551    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
552    pub commands_capability_file: bool,
553
554    /// Grace period in seconds for stopping replicas during updates, drains, and deletes.
555    ///
556    /// When omitted, the runtime backend applies its default. Valid values are
557    /// 1 second through 24 hours.
558    #[serde(skip_serializing_if = "Option::is_none")]
559    #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
560    pub stop_grace_period_seconds: Option<u32>,
561
562    /// Relative scheduling importance. On Kubernetes the cluster administrator maps each
563    /// level to a PriorityClass at install time; unset leaves the pod without one. Other
564    /// platforms ignore it.
565    #[serde(default, skip_serializing_if = "Option::is_none")]
566    pub priority: Option<WorkloadPriority>,
567}
568
569impl Container {
570    /// The resource type identifier for Container
571    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
572
573    /// Returns the container's unique identifier.
574    pub fn id(&self) -> &str {
575        &self.id
576    }
577
578    /// Returns the permission profile name for this container.
579    pub fn get_permissions(&self) -> &str {
580        &self.permissions
581    }
582
583    /// Returns true if this container is stateless (not stateful).
584    pub fn is_stateless(&self) -> bool {
585        !self.stateful
586    }
587
588    /// Validate resource-local network options; preflight also checks source existence and backend support.
589    pub fn validate_network_settings(&self) -> Result<()> {
590        let invalid = |reason: String| {
591            AlienError::new(ErrorData::InvalidResourceUpdate {
592                resource_id: self.id.clone(),
593                reason,
594            })
595        };
596        if self.egress.is_some()
597            && !self
598                .security
599                .as_ref()
600                .is_some_and(|security| security.profile == ContainerSecurityProfile::Restricted)
601        {
602            return Err(invalid(
603                "container egress internet requires security.profile restricted".into(),
604            ));
605        }
606        Ok(())
607    }
608
609    /// Validates the public endpoint configuration.
610    fn validate_public_endpoints(&self) -> Result<()> {
611        let mut endpoint_names = std::collections::HashSet::new();
612        let mut backend_ports = std::collections::HashSet::new();
613        let mut apex_endpoint_name: Option<&str> = None;
614
615        for endpoint in &self.public_endpoints {
616            endpoint.validate_for_resource(&self.id)?;
617
618            if !endpoint_names.insert(endpoint.name.as_str()) {
619                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
620                    resource_id: self.id.clone(),
621                    reason: format!("duplicate public endpoint name '{}'", endpoint.name),
622                }));
623            }
624
625            if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
626                if let Some(existing_name) = apex_endpoint_name {
627                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
628                        resource_id: self.id.clone(),
629                        reason: format!(
630                            "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
631                            existing_name
632                        ),
633                    }));
634                }
635                apex_endpoint_name = Some(endpoint.name.as_str());
636            }
637
638            backend_ports.insert(endpoint.port);
639
640            if !self.ports.iter().any(|port| port.port == endpoint.port) {
641                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
642                    resource_id: self.id.clone(),
643                    reason: format!(
644                        "public endpoint '{}' references undeclared port {}",
645                        endpoint.name, endpoint.port
646                    ),
647                }));
648            }
649        }
650
651        if backend_ports.len() > 1 {
652            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
653                resource_id: self.id.clone(),
654                reason:
655                    "public endpoints on one container must currently route to the same backend port"
656                        .to_string(),
657            }));
658        }
659
660        Ok(())
661    }
662}
663
664fn default_commands_enabled() -> bool {
665    false
666}
667
668impl<S: container_builder::State> ContainerBuilder<S> {
669    /// Links the container to another resource with specified permissions.
670    pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
671    where
672        for<'a> &'a R: Into<ResourceRef>,
673    {
674        let resource_ref: ResourceRef = resource.into();
675        self.links.push(resource_ref);
676        self
677    }
678
679    /// Adds an internal-only port to the container.
680    pub fn port(mut self, port: u16) -> Self {
681        self.ports.push(ContainerPort { port });
682        self
683    }
684
685    /// Mounts an existing Kubernetes Secret without copying its value into the stack.
686    pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
687        self.kubernetes_secret_mounts.push(mount);
688        self
689    }
690
691    /// Exposes a named public endpoint.
692    pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
693        if !self.ports.iter().any(|p| p.port == endpoint.port) {
694            self.ports.push(ContainerPort {
695                port: endpoint.port,
696            });
697        }
698        self.public_endpoints.push(endpoint);
699        self
700    }
701}
702
703/// Container status in the managed container backend.
704#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
705#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
706#[serde(rename_all = "camelCase")]
707pub enum ContainerStatus {
708    /// Waiting for replicas to start
709    Pending,
710    /// Min replicas healthy and serving
711    Running,
712    /// Manually stopped
713    Stopped,
714    /// Something is wrong — see statusReason/statusMessage; scheduler keeps retrying.
715    /// Covers all failure modes: crash-looping, unschedulable, replica failures, etc.
716    Failing,
717}
718
719/// Status of a single container replica.
720#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
721#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
722#[serde(rename_all = "camelCase")]
723pub struct ReplicaStatus {
724    /// Replica ID (e.g., "api-0", "api-1")
725    pub replica_id: String,
726    /// Ordinal (for stateful containers)
727    pub ordinal: Option<u32>,
728    /// Machine ID the replica is running on
729    pub machine_id: Option<String>,
730    /// Whether the replica is healthy
731    pub healthy: bool,
732    /// Container IP address (for service discovery)
733    pub container_ip: Option<String>,
734}
735
736/// A container port reachable from the control plane through the manager.
737///
738/// Requests to `/v1/deployments/{deployment}/tunnels/{container}/...` on the
739/// manager are forwarded to this port over the operator's outbound
740/// connection, so the control plane can call the service without any inbound
741/// network path into the deployment.
742#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
743#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
744#[serde(rename_all = "camelCase", deny_unknown_fields)]
745pub struct ContainerTunnel {
746    /// Container port that serves HTTP. Must be one of the container's ports.
747    pub port: u16,
748}
749
750/// Outputs generated by a successfully provisioned Container.
751#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
752#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
753#[serde(rename_all = "camelCase")]
754pub struct ContainerOutputs {
755    /// Container name in the managed container backend
756    pub name: String,
757    /// Current container status
758    pub status: ContainerStatus,
759    /// Number of current replicas
760    pub current_replicas: u32,
761    /// Desired number of replicas
762    pub desired_replicas: u32,
763    /// Internal DNS name (e.g., "api.svc")
764    pub internal_dns: String,
765    /// Public endpoints resolved for this container.
766    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
767    pub public_endpoints: HashMap<String, PublicEndpointOutput>,
768    /// Internal URLs keyed by port for cluster members and linking resources.
769    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
770    pub internal_urls: HashMap<u16, String>,
771    /// Status of each replica
772    pub replicas: Vec<ReplicaStatus>,
773    /// Persistent volumes, one per replica ordinal, with their latest snapshot.
774    #[serde(default, skip_serializing_if = "Vec::is_empty")]
775    pub volumes: Vec<VolumeOutput>,
776    /// Whether the persistent volumes' snapshot schedule is in place.
777    #[serde(default, skip_serializing_if = "Option::is_none")]
778    pub volume_backups: Option<VolumeBackupsStatus>,
779}
780
781/// Whether a container's snapshot schedule is in place.
782#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
783#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
784#[serde(rename_all = "camelCase")]
785pub struct VolumeBackupsStatus {
786    /// Current state of the schedule
787    pub state: VolumeBackupsState,
788    /// What is missing when the state is `setupRequired`
789    #[serde(skip_serializing_if = "Option::is_none")]
790    pub message: Option<String>,
791}
792
793/// State of a container's snapshot schedule.
794#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
795#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
796#[serde(rename_all = "camelCase")]
797pub enum VolumeBackupsState {
798    /// The cloud's scheduler is taking snapshots.
799    Active,
800    /// Backups are turned off in the stack.
801    Disabled,
802    /// The deployment's management permissions predate volume backups. The
803    /// container keeps running without a schedule until the installation's
804    /// setup is updated; the controller then applies the schedule by itself.
805    SetupRequired,
806}
807
808/// A replica's persistent volume and its latest completed snapshot.
809#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
810#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
811#[serde(rename_all = "camelCase")]
812pub struct VolumeOutput {
813    /// Replica ordinal the volume belongs to
814    pub ordinal: u32,
815    /// Cloud ID of the volume (EBS volume ID, Persistent Disk name, or Managed Disk ID)
816    pub volume_id: String,
817    /// Zone the volume lives in
818    pub zone: String,
819    /// Cloud ID of the latest completed snapshot, if any
820    #[serde(skip_serializing_if = "Option::is_none")]
821    pub last_snapshot_id: Option<String>,
822    /// When the latest completed snapshot was started (RFC 3339)
823    #[serde(skip_serializing_if = "Option::is_none")]
824    pub last_snapshot_at: Option<String>,
825    /// The latest volume restore performed on this ordinal, if any
826    #[serde(skip_serializing_if = "Option::is_none")]
827    pub last_restore: Option<VolumeRestoreOutput>,
828}
829
830/// A completed volume restore.
831#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
832#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
833#[serde(rename_all = "camelCase")]
834pub struct VolumeRestoreOutput {
835    /// ID of the restore request
836    pub request_id: String,
837    /// Snapshot the volume was restored from
838    pub snapshot_id: String,
839    /// Snapshot of the replaced volume, taken just before it was deleted
840    pub replaced_volume_snapshot_id: String,
841    /// When the restored volume was put in place (RFC 3339)
842    pub completed_at: String,
843}
844
845impl ResourceOutputsDefinition for ContainerOutputs {
846    fn get_resource_type(&self) -> ResourceType {
847        Container::RESOURCE_TYPE.clone()
848    }
849
850    fn as_any(&self) -> &dyn Any {
851        self
852    }
853
854    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
855        Box::new(self.clone())
856    }
857
858    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
859        other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
860    }
861
862    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
863        serde_json::to_value(self)
864    }
865}
866
867impl ResourceDefinition for Container {
868    fn get_resource_type(&self) -> ResourceType {
869        Self::RESOURCE_TYPE
870    }
871
872    fn id(&self) -> &str {
873        &self.id
874    }
875
876    fn replace_after_failed_create_is_safe(&self) -> bool {
877        // Deleting it destroys the persistent volumes of a stateful container.
878        !(self.stateful && self.persistent_storage.is_some())
879    }
880
881    fn get_dependencies(&self) -> Vec<ResourceRef> {
882        let mut deps = self.links.clone();
883        if let Some(key) = self
884            .persistent_storage
885            .as_ref()
886            .and_then(|storage| storage.encryption_key.as_ref())
887        {
888            deps.push(key.clone());
889        }
890        // Add dependency on the container cluster if explicitly specified.
891        // If None, ComputeClusterMutation will auto-assign at deployment time.
892        if let Some(cluster) = &self.cluster {
893            deps.push(ResourceRef::new(
894                ComputeCluster::RESOURCE_TYPE.clone(),
895                cluster,
896            ));
897        }
898        deps
899    }
900
901    fn get_permissions(&self) -> Option<&str> {
902        Some(&self.permissions)
903    }
904
905    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
906        let new_container = new_config
907            .as_any()
908            .downcast_ref::<Container>()
909            .ok_or_else(|| {
910                AlienError::new(ErrorData::UnexpectedResourceType {
911                    resource_id: self.id.clone(),
912                    expected: Self::RESOURCE_TYPE,
913                    actual: new_config.get_resource_type(),
914                })
915            })?;
916
917        // Validate the new config's public endpoints.
918        new_container.validate_public_endpoints()?;
919        new_container.validate_network_settings()?;
920
921        if self.id != new_container.id {
922            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
923                resource_id: self.id.clone(),
924                reason: "the 'id' field is immutable".to_string(),
925            }));
926        }
927
928        // Cluster is immutable
929        if self.cluster != new_container.cluster {
930            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
931                resource_id: self.id.clone(),
932                reason: "the 'cluster' field is immutable".to_string(),
933            }));
934        }
935
936        // Stateful is immutable
937        if self.stateful != new_container.stateful {
938            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
939                resource_id: self.id.clone(),
940                reason: "the 'stateful' field is immutable".to_string(),
941            }));
942        }
943
944        let old_key = self
945            .persistent_storage
946            .as_ref()
947            .and_then(|storage| storage.encryption_key.as_ref());
948        let new_key = new_container
949            .persistent_storage
950            .as_ref()
951            .and_then(|storage| storage.encryption_key.as_ref());
952        if old_key != new_key {
953            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
954                resource_id: self.id.clone(),
955                reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
956            }));
957        }
958
959        // Ports are immutable (requires load balancer reconfiguration)
960        if self.ports != new_container.ports {
961            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
962                resource_id: self.id.clone(),
963                reason: "the 'ports' field is immutable".to_string(),
964            }));
965        }
966
967        if self.public_endpoints != new_container.public_endpoints {
968            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
969                resource_id: self.id.clone(),
970                reason: "the 'publicEndpoints' field is immutable".to_string(),
971            }));
972        }
973
974        // Pool (capacity group) is immutable
975        if self.pool != new_container.pool {
976            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
977                resource_id: self.id.clone(),
978                reason: "the 'pool' field is immutable".to_string(),
979            }));
980        }
981
982        Ok(())
983    }
984
985    fn as_any(&self) -> &dyn Any {
986        self
987    }
988
989    fn as_any_mut(&mut self) -> &mut dyn Any {
990        self
991    }
992
993    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
994        Box::new(self.clone())
995    }
996
997    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
998        other.as_any().downcast_ref::<Container>() == Some(self)
999    }
1000
1001    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1002        serde_json::to_value(self)
1003    }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008    use super::*;
1009    use crate::resources::ExposeProtocol;
1010
1011    fn network_container() -> Container {
1012        Container::new("api".to_string())
1013            .code(ContainerCode::Image {
1014                image: "example:latest".into(),
1015            })
1016            .cpu(ResourceSpec {
1017                min: "1".into(),
1018                desired: "1".into(),
1019            })
1020            .memory(ResourceSpec {
1021                min: "512Mi".into(),
1022                desired: "512Mi".into(),
1023            })
1024            .permissions("execution".into())
1025            .public_endpoint(PublicEndpoint {
1026                name: "web".into(),
1027                port: 8080,
1028                protocol: ExposeProtocol::Http,
1029                host_label: None,
1030                wildcard_subdomains: false,
1031            })
1032            .build()
1033    }
1034
1035    #[test]
1036    fn internet_egress_requires_restricted_security_and_is_opt_in() {
1037        let mut container = network_container();
1038        assert!(serde_json::to_value(&container)
1039            .unwrap()
1040            .get("egress")
1041            .is_none());
1042        container.egress = Some(ContainerEgress::Internet);
1043        assert!(container.validate_update(&container).is_err());
1044        container.security = Some(ContainerSecurity {
1045            profile: ContainerSecurityProfile::Restricted,
1046            run_as_user: 65532,
1047            run_as_group: 65532,
1048            read_only_root_filesystem: true,
1049        });
1050        container.validate_update(&container).unwrap();
1051        assert_eq!(
1052            serde_json::to_value(&container).unwrap()["egress"],
1053            "internet"
1054        );
1055    }
1056
1057    #[test]
1058    fn test_container_creation_with_autoscaling() {
1059        let container = Container::new("api".to_string())
1060            .cluster("compute".to_string())
1061            .code(ContainerCode::Image {
1062                image: "myapp:latest".to_string(),
1063            })
1064            .cpu(ResourceSpec {
1065                min: "0.5".to_string(),
1066                desired: "1".to_string(),
1067            })
1068            .memory(ResourceSpec {
1069                min: "512Mi".to_string(),
1070                desired: "1Gi".to_string(),
1071            })
1072            .port(8080)
1073            .public_endpoint(PublicEndpoint {
1074                name: "api".to_string(),
1075                port: 8080,
1076                protocol: ExposeProtocol::Http,
1077                host_label: None,
1078                wildcard_subdomains: false,
1079            })
1080            .autoscaling(ContainerAutoscaling {
1081                min: 2,
1082                desired: 3,
1083                max: 10,
1084                target_cpu_percent: Some(70.0),
1085                target_memory_percent: None,
1086                target_http_in_flight_per_replica: Some(100),
1087                max_http_p95_latency_ms: None,
1088            })
1089            .permissions("container-execution".to_string())
1090            .build();
1091
1092        assert_eq!(container.id(), "api");
1093        assert_eq!(container.cluster, Some("compute".to_string()));
1094        assert!(!container.stateful);
1095        assert!(container.autoscaling.is_some());
1096        assert_eq!(container.ports.len(), 1);
1097        assert_eq!(container.ports[0].port, 8080);
1098    }
1099
1100    #[test]
1101    fn container_serializes_stop_grace_period_when_set() {
1102        let container = Container::new("api".to_string())
1103            .cluster("compute".to_string())
1104            .code(ContainerCode::Image {
1105                image: "myapp:latest".to_string(),
1106            })
1107            .cpu(ResourceSpec {
1108                min: "0.5".to_string(),
1109                desired: "1".to_string(),
1110            })
1111            .memory(ResourceSpec {
1112                min: "512Mi".to_string(),
1113                desired: "1Gi".to_string(),
1114            })
1115            .port(8080)
1116            .permissions("container-execution".to_string())
1117            .stop_grace_period_seconds(21_600)
1118            .build();
1119
1120        let json = serde_json::to_value(&container).expect("container should serialize");
1121        assert_eq!(json["stopGracePeriodSeconds"], 21_600);
1122    }
1123
1124    #[test]
1125    fn container_omits_stop_grace_period_when_absent() {
1126        let container = Container::new("api".to_string())
1127            .cluster("compute".to_string())
1128            .code(ContainerCode::Image {
1129                image: "myapp:latest".to_string(),
1130            })
1131            .cpu(ResourceSpec {
1132                min: "0.5".to_string(),
1133                desired: "1".to_string(),
1134            })
1135            .memory(ResourceSpec {
1136                min: "512Mi".to_string(),
1137                desired: "1Gi".to_string(),
1138            })
1139            .port(8080)
1140            .permissions("container-execution".to_string())
1141            .build();
1142
1143        let json = serde_json::to_value(&container).expect("container should serialize");
1144        assert!(json.get("stopGracePeriodSeconds").is_none());
1145    }
1146
1147    #[test]
1148    fn test_stateful_container_with_storage() {
1149        let container = Container::new("postgres".to_string())
1150            .cluster("compute".to_string())
1151            .code(ContainerCode::Image {
1152                image: "postgres:16".to_string(),
1153            })
1154            .cpu(ResourceSpec {
1155                min: "1".to_string(),
1156                desired: "2".to_string(),
1157            })
1158            .memory(ResourceSpec {
1159                min: "2Gi".to_string(),
1160                desired: "4Gi".to_string(),
1161            })
1162            .port(5432)
1163            .stateful(true)
1164            .replicas(1)
1165            .persistent_storage(PersistentStorage {
1166                encryption_key: None,
1167                size: "100Gi".to_string(),
1168                mount_path: "/var/lib/postgresql/data".to_string(),
1169                backups: VolumeBackups::default(),
1170            })
1171            .permissions("database".to_string())
1172            .build();
1173
1174        assert_eq!(container.id(), "postgres");
1175        assert!(container.stateful);
1176        assert!(container.replicas.is_some());
1177        assert!(container.persistent_storage.is_some());
1178    }
1179
1180    #[test]
1181    fn test_public_container() {
1182        let container = Container::new("frontend".to_string())
1183            .cluster("compute".to_string())
1184            .code(ContainerCode::Image {
1185                image: "frontend:latest".to_string(),
1186            })
1187            .cpu(ResourceSpec {
1188                min: "0.25".to_string(),
1189                desired: "0.5".to_string(),
1190            })
1191            .memory(ResourceSpec {
1192                min: "256Mi".to_string(),
1193                desired: "512Mi".to_string(),
1194            })
1195            .port(3000)
1196            .public_endpoint(PublicEndpoint {
1197                name: "web".to_string(),
1198                port: 3000,
1199                protocol: ExposeProtocol::Http,
1200                host_label: None,
1201                wildcard_subdomains: false,
1202            })
1203            .autoscaling(ContainerAutoscaling {
1204                min: 2,
1205                desired: 2,
1206                max: 20,
1207                target_cpu_percent: None,
1208                target_memory_percent: None,
1209                target_http_in_flight_per_replica: Some(50),
1210                max_http_p95_latency_ms: Some(100.0),
1211            })
1212            .health_check(HealthCheck {
1213                path: "/health".to_string(),
1214                port: None,
1215                method: "GET".to_string(),
1216                timeout_seconds: 1,
1217                failure_threshold: 3,
1218            })
1219            .permissions("frontend".to_string())
1220            .build();
1221
1222        assert_eq!(container.ports[0].port, 3000);
1223        assert_eq!(container.public_endpoints[0].name, "web");
1224        assert!(container.health_check.is_some());
1225    }
1226
1227    #[test]
1228    fn test_public_container_endpoint_options() {
1229        let container = Container::new("router".to_string())
1230            .cluster("compute".to_string())
1231            .code(ContainerCode::Image {
1232                image: "router:latest".to_string(),
1233            })
1234            .cpu(ResourceSpec {
1235                min: "0.25".to_string(),
1236                desired: "0.5".to_string(),
1237            })
1238            .memory(ResourceSpec {
1239                min: "256Mi".to_string(),
1240                desired: "512Mi".to_string(),
1241            })
1242            .public_endpoint(PublicEndpoint {
1243                name: "gateway".to_string(),
1244                port: 8080,
1245                protocol: ExposeProtocol::Http,
1246                host_label: Some("gateway".to_string()),
1247                wildcard_subdomains: true,
1248            })
1249            .permissions("router".to_string())
1250            .build();
1251
1252        assert!(container.validate_public_endpoints().is_ok());
1253        assert_eq!(container.ports.len(), 1);
1254        assert_eq!(container.public_endpoints.len(), 1);
1255        assert_eq!(
1256            container.public_endpoints[0].host_label.as_deref(),
1257            Some("gateway")
1258        );
1259        assert!(container.public_endpoints[0].wildcard_subdomains);
1260    }
1261
1262    #[test]
1263    fn test_public_container_rejects_invalid_host_label() {
1264        let container = Container::new("router".to_string())
1265            .cluster("compute".to_string())
1266            .code(ContainerCode::Image {
1267                image: "router:latest".to_string(),
1268            })
1269            .cpu(ResourceSpec {
1270                min: "0.25".to_string(),
1271                desired: "0.5".to_string(),
1272            })
1273            .memory(ResourceSpec {
1274                min: "256Mi".to_string(),
1275                desired: "512Mi".to_string(),
1276            })
1277            .public_endpoint(PublicEndpoint {
1278                name: "gateway".to_string(),
1279                port: 8080,
1280                protocol: ExposeProtocol::Http,
1281                host_label: Some("bad.label".to_string()),
1282                wildcard_subdomains: true,
1283            })
1284            .permissions("router".to_string())
1285            .build();
1286
1287        assert!(container.validate_public_endpoints().is_err());
1288    }
1289
1290    #[test]
1291    fn test_container_with_links() {
1292        use crate::Storage;
1293
1294        let storage = Storage::new("data".to_string()).build();
1295
1296        let container = Container::new("worker".to_string())
1297            .cluster("compute".to_string())
1298            .code(ContainerCode::Image {
1299                image: "worker:latest".to_string(),
1300            })
1301            .cpu(ResourceSpec {
1302                min: "0.5".to_string(),
1303                desired: "1".to_string(),
1304            })
1305            .memory(ResourceSpec {
1306                min: "512Mi".to_string(),
1307                desired: "1Gi".to_string(),
1308            })
1309            .port(8080)
1310            .replicas(3)
1311            .link(&storage)
1312            .permissions("worker".to_string())
1313            .build();
1314
1315        // Should have 2 dependencies: cluster + linked storage
1316        let deps = container.get_dependencies();
1317        assert_eq!(deps.len(), 2);
1318    }
1319
1320    #[test]
1321    fn test_container_validate_update_immutable_cluster() {
1322        let container1 = Container::new("api".to_string())
1323            .cluster("cluster-1".to_string())
1324            .code(ContainerCode::Image {
1325                image: "myapp:v1".to_string(),
1326            })
1327            .cpu(ResourceSpec {
1328                min: "0.5".to_string(),
1329                desired: "1".to_string(),
1330            })
1331            .memory(ResourceSpec {
1332                min: "512Mi".to_string(),
1333                desired: "1Gi".to_string(),
1334            })
1335            .port(8080)
1336            .replicas(2)
1337            .permissions("execution".to_string())
1338            .build();
1339
1340        let container2 = Container::new("api".to_string())
1341            .cluster("cluster-2".to_string()) // Changed cluster
1342            .code(ContainerCode::Image {
1343                image: "myapp:v2".to_string(),
1344            })
1345            .cpu(ResourceSpec {
1346                min: "0.5".to_string(),
1347                desired: "1".to_string(),
1348            })
1349            .memory(ResourceSpec {
1350                min: "512Mi".to_string(),
1351                desired: "1Gi".to_string(),
1352            })
1353            .port(8080)
1354            .replicas(2)
1355            .permissions("execution".to_string())
1356            .build();
1357
1358        let result = container1.validate_update(&container2);
1359        assert!(result.is_err());
1360    }
1361
1362    #[test]
1363    fn test_container_validate_update_allowed_changes() {
1364        let container1 = Container::new("api".to_string())
1365            .cluster("compute".to_string())
1366            .code(ContainerCode::Image {
1367                image: "myapp:v1".to_string(),
1368            })
1369            .cpu(ResourceSpec {
1370                min: "0.5".to_string(),
1371                desired: "1".to_string(),
1372            })
1373            .memory(ResourceSpec {
1374                min: "512Mi".to_string(),
1375                desired: "1Gi".to_string(),
1376            })
1377            .port(8080)
1378            .replicas(2)
1379            .permissions("execution".to_string())
1380            .build();
1381
1382        let container2 = Container::new("api".to_string())
1383            .cluster("compute".to_string())
1384            .code(ContainerCode::Image {
1385                image: "myapp:v2".to_string(), // Image can change
1386            })
1387            .cpu(ResourceSpec {
1388                min: "1".to_string(), // Resources can change
1389                desired: "2".to_string(),
1390            })
1391            .memory(ResourceSpec {
1392                min: "1Gi".to_string(),
1393                desired: "2Gi".to_string(),
1394            })
1395            .port(8080)
1396            .replicas(5) // Replicas can change
1397            .permissions("execution".to_string())
1398            .build();
1399
1400        let result = container1.validate_update(&container2);
1401        assert!(result.is_ok());
1402    }
1403
1404    #[test]
1405    fn test_container_serialization() {
1406        let container = Container::new("test".to_string())
1407            .cluster("compute".to_string())
1408            .code(ContainerCode::Image {
1409                image: "test:latest".to_string(),
1410            })
1411            .cpu(ResourceSpec {
1412                min: "0.5".to_string(),
1413                desired: "1".to_string(),
1414            })
1415            .memory(ResourceSpec {
1416                min: "512Mi".to_string(),
1417                desired: "1Gi".to_string(),
1418            })
1419            .port(8080)
1420            .replicas(1)
1421            .permissions("test".to_string())
1422            .build();
1423
1424        let json = serde_json::to_string(&container).unwrap();
1425        let deserialized: Container = serde_json::from_str(&json).unwrap();
1426        assert_eq!(container, deserialized);
1427    }
1428
1429    #[test]
1430    fn test_container_multi_endpoint_validation() {
1431        let container = Container::new("multi-tcp".to_string())
1432            .cluster("compute".to_string())
1433            .code(ContainerCode::Image {
1434                image: "test:latest".to_string(),
1435            })
1436            .cpu(ResourceSpec {
1437                min: "1".to_string(),
1438                desired: "1".to_string(),
1439            })
1440            .memory(ResourceSpec {
1441                min: "1Gi".to_string(),
1442                desired: "1Gi".to_string(),
1443            })
1444            .port(8080)
1445            .public_endpoint(PublicEndpoint {
1446                name: "api".to_string(),
1447                port: 8080,
1448                protocol: ExposeProtocol::Http,
1449                host_label: None,
1450                wildcard_subdomains: false,
1451            })
1452            .public_endpoint(PublicEndpoint {
1453                name: "wildcard".to_string(),
1454                port: 8080,
1455                protocol: ExposeProtocol::Http,
1456                host_label: Some("wildcard".to_string()),
1457                wildcard_subdomains: true,
1458            })
1459            .replicas(1)
1460            .permissions("test".to_string())
1461            .build();
1462
1463        assert!(container.validate_public_endpoints().is_ok());
1464
1465        let invalid_container = Container::new("multi-http".to_string())
1466            .cluster("compute".to_string())
1467            .code(ContainerCode::Image {
1468                image: "test:latest".to_string(),
1469            })
1470            .cpu(ResourceSpec {
1471                min: "1".to_string(),
1472                desired: "1".to_string(),
1473            })
1474            .memory(ResourceSpec {
1475                min: "1Gi".to_string(),
1476                desired: "1Gi".to_string(),
1477            })
1478            .port(8080)
1479            .port(9090)
1480            .public_endpoint(PublicEndpoint {
1481                name: "api".to_string(),
1482                port: 8080,
1483                protocol: ExposeProtocol::Http,
1484                host_label: None,
1485                wildcard_subdomains: false,
1486            })
1487            .public_endpoint(PublicEndpoint {
1488                name: "admin".to_string(),
1489                port: 9090,
1490                protocol: ExposeProtocol::Http,
1491                host_label: None,
1492                wildcard_subdomains: false,
1493            })
1494            .replicas(1)
1495            .permissions("test".to_string())
1496            .build();
1497
1498        assert!(invalid_container.validate_public_endpoints().is_err());
1499    }
1500
1501    #[test]
1502    fn container_rejects_multiple_apex_public_endpoints() {
1503        let container = Container::new("apex-container".to_string())
1504            .cluster("compute".to_string())
1505            .code(ContainerCode::Image {
1506                image: "test:latest".to_string(),
1507            })
1508            .cpu(ResourceSpec {
1509                min: "1".to_string(),
1510                desired: "1".to_string(),
1511            })
1512            .memory(ResourceSpec {
1513                min: "1Gi".to_string(),
1514                desired: "1Gi".to_string(),
1515            })
1516            .port(8080)
1517            .public_endpoint(PublicEndpoint {
1518                name: "web".to_string(),
1519                port: 8080,
1520                protocol: ExposeProtocol::Http,
1521                host_label: Some(APEX_HOST_LABEL.to_string()),
1522                wildcard_subdomains: false,
1523            })
1524            .public_endpoint(PublicEndpoint {
1525                name: "admin".to_string(),
1526                port: 8080,
1527                protocol: ExposeProtocol::Http,
1528                host_label: Some(APEX_HOST_LABEL.to_string()),
1529                wildcard_subdomains: false,
1530            })
1531            .replicas(1)
1532            .permissions("test".to_string())
1533            .build();
1534
1535        assert!(container.validate_public_endpoints().is_err());
1536    }
1537
1538    #[test]
1539    fn test_container_empty_ports_validation() {
1540        let container = Container::new("no-ports".to_string())
1541            .cluster("compute".to_string())
1542            .code(ContainerCode::Image {
1543                image: "test:latest".to_string(),
1544            })
1545            .cpu(ResourceSpec {
1546                min: "1".to_string(),
1547                desired: "1".to_string(),
1548            })
1549            .memory(ResourceSpec {
1550                min: "1Gi".to_string(),
1551                desired: "1Gi".to_string(),
1552            })
1553            .replicas(1)
1554            .permissions("test".to_string())
1555            .build();
1556
1557        assert!(container.validate_public_endpoints().is_ok());
1558    }
1559
1560    #[test]
1561    fn test_container_commands_enabled_defaults_false() {
1562        let container = Container::new("no-commands".to_string())
1563            .cluster("compute".to_string())
1564            .code(ContainerCode::Image {
1565                image: "test:latest".to_string(),
1566            })
1567            .cpu(ResourceSpec {
1568                min: "0.5".to_string(),
1569                desired: "1".to_string(),
1570            })
1571            .memory(ResourceSpec {
1572                min: "512Mi".to_string(),
1573                desired: "1Gi".to_string(),
1574            })
1575            .port(8080)
1576            .permissions("test".to_string())
1577            .build();
1578
1579        assert!(!container.commands_enabled);
1580    }
1581
1582    #[test]
1583    fn test_container_commands_enabled_builder() {
1584        let container = Container::new("cmd-container".to_string())
1585            .cluster("compute".to_string())
1586            .code(ContainerCode::Image {
1587                image: "test:latest".to_string(),
1588            })
1589            .cpu(ResourceSpec {
1590                min: "0.5".to_string(),
1591                desired: "1".to_string(),
1592            })
1593            .memory(ResourceSpec {
1594                min: "512Mi".to_string(),
1595                desired: "1Gi".to_string(),
1596            })
1597            .port(8080)
1598            .permissions("test".to_string())
1599            .commands_enabled(true)
1600            .build();
1601
1602        assert!(container.commands_enabled);
1603    }
1604
1605    #[test]
1606    fn test_container_commands_enabled_serializes_camel_case() {
1607        let container = Container::new("cmd-container".to_string())
1608            .cluster("compute".to_string())
1609            .code(ContainerCode::Image {
1610                image: "test:latest".to_string(),
1611            })
1612            .cpu(ResourceSpec {
1613                min: "0.5".to_string(),
1614                desired: "1".to_string(),
1615            })
1616            .memory(ResourceSpec {
1617                min: "512Mi".to_string(),
1618                desired: "1Gi".to_string(),
1619            })
1620            .port(8080)
1621            .permissions("test".to_string())
1622            .commands_enabled(true)
1623            .build();
1624
1625        let json = serde_json::to_value(&container).expect("container should serialize");
1626        assert_eq!(json["commandsEnabled"], true);
1627
1628        let deserialized: Container =
1629            serde_json::from_value(json).expect("container should deserialize");
1630        assert_eq!(deserialized, container);
1631    }
1632}