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///
265/// A workload without a `security` setting runs as its image was built. Setting
266/// `security.profile` to `restricted` applies the Kubernetes Pod Security
267/// `restricted` profile; `unrestricted` states that no profile is applied. A
268/// `security` object without a `profile` is a parse error: there is no default
269/// profile.
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
271#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
272#[serde(rename_all = "camelCase")]
273pub enum ContainerSecurityProfile {
274    /// Non-root, seccomp RuntimeDefault, all capabilities dropped, no
275    /// privilege escalation, read-only root filesystem.
276    Restricted,
277    /// Opt-out: no security context is applied and the image runs as built.
278    Unrestricted,
279}
280
281/// Container process identity and filesystem security.
282///
283/// Absent means no pod security settings are applied: the workload runs as
284/// its image was built. Setting `profile: restricted` applies the restricted
285/// profile (with the image's own non-root user unless `runAsUser` is set).
286///
287/// On the wire every field a previous Operator requires is always written with
288/// a concrete value (`runAsUser`/`runAsGroup` as 65532 and `readOnlyRootFilesystem`
289/// as the profile's default when unset) and `profile` is written as `restricted`
290/// (the only value a previous release knows), so state and bundles written by
291/// this version stay readable after an Operator rollback. The `*Unset` and
292/// `unrestricted` markers, which previous releases ignore, record what was
293/// really set, so reading restores the exact value and never treats a real `0`
294/// or `false` as unset. A previous Operator applies `restricted` to an opted-out
295/// workload, so an image that needs root must not be rolled back to it.
296#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
297#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
298#[serde(
299    rename_all = "camelCase",
300    from = "ContainerSecurityWire",
301    into = "ContainerSecurityWire"
302)]
303pub struct ContainerSecurity {
304    /// Runtime security profile. `unrestricted` is the explicit opt-out.
305    pub profile: ContainerSecurityProfile,
306    /// Numeric UID for the container process. Defaults to the image's user,
307    /// which must not be root.
308    pub run_as_user: Option<i64>,
309    /// Numeric GID for the container process. Defaults to the image's group.
310    pub run_as_group: Option<i64>,
311    /// Mount the root filesystem read-only. Defaults to true under `restricted`.
312    pub read_only_root_filesystem: Option<bool>,
313    /// Absolute paths backed by a writable emptyDir. `/tmp` is always writable.
314    #[serde(default)]
315    pub writable_paths: Vec<String>,
316}
317
318/// Stands in for an unset user or group on the wire: a previous release needs a
319/// positive ID, and 65532 is the user source-built images run as.
320const PREVIOUS_RELEASE_ID: i64 = 65532;
321
322/// Wire form of [`ContainerSecurity`]; see its documentation.
323#[derive(Serialize, Deserialize)]
324#[serde(rename_all = "camelCase")]
325struct ContainerSecurityWire {
326    profile: ContainerSecurityProfile,
327    #[serde(default)]
328    run_as_user: Option<i64>,
329    #[serde(default)]
330    run_as_group: Option<i64>,
331    #[serde(default)]
332    read_only_root_filesystem: Option<bool>,
333    /// The opt-out, which `profile` cannot carry for a previous release.
334    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
335    unrestricted: bool,
336    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
337    run_as_user_unset: bool,
338    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
339    run_as_group_unset: bool,
340    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
341    read_only_root_filesystem_unset: bool,
342    #[serde(default, skip_serializing_if = "Vec::is_empty")]
343    writable_paths: Vec<String>,
344}
345
346impl From<ContainerSecurity> for ContainerSecurityWire {
347    fn from(security: ContainerSecurity) -> Self {
348        let unrestricted = security.profile == ContainerSecurityProfile::Unrestricted;
349        Self {
350            profile: ContainerSecurityProfile::Restricted,
351            unrestricted,
352            run_as_user_unset: security.run_as_user.is_none(),
353            run_as_user: Some(security.run_as_user.unwrap_or(PREVIOUS_RELEASE_ID)),
354            run_as_group_unset: security.run_as_group.is_none(),
355            run_as_group: Some(security.run_as_group.unwrap_or(PREVIOUS_RELEASE_ID)),
356            read_only_root_filesystem_unset: security.read_only_root_filesystem.is_none(),
357            read_only_root_filesystem: Some(
358                security.read_only_root_filesystem.unwrap_or(!unrestricted),
359            ),
360            writable_paths: security.writable_paths,
361        }
362    }
363}
364
365impl From<ContainerSecurityWire> for ContainerSecurity {
366    fn from(wire: ContainerSecurityWire) -> Self {
367        let profile = if wire.unrestricted {
368            ContainerSecurityProfile::Unrestricted
369        } else {
370            wire.profile
371        };
372        Self {
373            profile,
374            run_as_user: wire.run_as_user.filter(|_| !wire.run_as_user_unset),
375            run_as_group: wire.run_as_group.filter(|_| !wire.run_as_group_unset),
376            read_only_root_filesystem: wire
377                .read_only_root_filesystem
378                .filter(|_| !wire.read_only_root_filesystem_unset),
379            writable_paths: wire.writable_paths,
380        }
381    }
382}
383
384impl ContainerSecurity {
385    /// Whether a workload with this (possibly absent) setting runs restricted.
386    /// Absent is not restricted: only an explicit `restricted` profile is.
387    pub fn is_restricted(security: Option<&ContainerSecurity>) -> bool {
388        security.is_some_and(|security| security.profile == ContainerSecurityProfile::Restricted)
389    }
390}
391
392/// Autoscaling configuration for stateless containers.
393#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
394#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
395#[serde(rename_all = "camelCase")]
396pub struct ContainerAutoscaling {
397    /// Minimum replicas (always running)
398    pub min: u32,
399    /// Initial desired replicas at container creation
400    pub desired: u32,
401    /// Maximum replicas under load
402    pub max: u32,
403    /// Target CPU utilization percentage for scaling (default: 70%)
404    #[serde(skip_serializing_if = "Option::is_none")]
405    pub target_cpu_percent: Option<f64>,
406    /// Target memory utilization percentage for scaling (default: 80%)
407    #[serde(skip_serializing_if = "Option::is_none")]
408    pub target_memory_percent: Option<f64>,
409    /// Target in-flight HTTP requests per replica
410    #[serde(skip_serializing_if = "Option::is_none")]
411    pub target_http_in_flight_per_replica: Option<u32>,
412    /// Maximum acceptable p95 HTTP latency in milliseconds
413    #[serde(skip_serializing_if = "Option::is_none")]
414    pub max_http_p95_latency_ms: Option<f64>,
415}
416
417/// HTTP health check configuration.
418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
419#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
420#[serde(rename_all = "camelCase")]
421pub struct HealthCheck {
422    /// HTTP endpoint path to check (e.g., "/health", "/ready")
423    #[serde(default = "default_health_path")]
424    pub path: String,
425    /// Port to check (defaults to container port if not specified)
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub port: Option<u16>,
428    /// HTTP method to use for health check
429    #[serde(default = "default_health_method")]
430    pub method: String,
431    /// Request timeout in seconds (1-5)
432    #[serde(default = "default_timeout_seconds")]
433    pub timeout_seconds: u32,
434    /// Number of consecutive failures before marking replica unhealthy
435    #[serde(default = "default_failure_threshold")]
436    pub failure_threshold: u32,
437    /// Daemons only: how long a replica may run without passing its health check before the
438    /// update fails, in seconds, counted from when the replica first reports running.
439    /// Defaults to 600 (10 minutes); at most 86400 (24 hours).
440    #[serde(default, skip_serializing_if = "Option::is_none")]
441    pub startup_timeout_seconds: Option<u32>,
442}
443
444impl Default for HealthCheck {
445    /// The values a health check takes for every field it leaves out; no port.
446    fn default() -> Self {
447        HealthCheck {
448            path: default_health_path(),
449            port: None,
450            method: default_health_method(),
451            timeout_seconds: default_timeout_seconds(),
452            failure_threshold: default_failure_threshold(),
453            startup_timeout_seconds: None,
454        }
455    }
456}
457
458fn default_health_path() -> String {
459    "/health".to_string()
460}
461
462fn default_health_method() -> String {
463    "GET".to_string()
464}
465
466fn default_timeout_seconds() -> u32 {
467    1
468}
469
470fn default_failure_threshold() -> u32 {
471    3
472}
473
474/// Container port configuration.
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
477#[serde(rename_all = "camelCase")]
478pub struct ContainerPort {
479    /// Port number
480    pub port: u16,
481}
482
483/// Outbound network restriction enforced outside the container.
484/// Internet access also permits this container's own replicas on declared TCP ports,
485/// own-service discovery, and the credential proxy for its own identity.
486/// Absence preserves the runtime's existing full-network behavior.
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
488#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
489#[serde(rename_all = "camelCase")]
490pub enum ContainerEgress {
491    /// Public addresses and DNS, plus own replicas on declared TCP ports and
492    /// the platform credential proxy for this identity.
493    /// Requires the restricted security profile and backend enforcement.
494    Internet,
495}
496
497/// Container resource for running long-running container workloads.
498///
499/// A Container defines a deployable unit that runs on a ComputeCluster.
500/// The managed container backend handles scheduling replicas across machines,
501/// autoscaling based on various metrics, and service discovery.
502///
503/// ## Example
504///
505/// ```rust
506/// use alien_core::{Container, ContainerCode, ResourceSpec, ContainerAutoscaling, PublicEndpoint, ExposeProtocol};
507///
508/// let container = Container::new("api".to_string())
509///     .cluster("compute".to_string())
510///     .code(ContainerCode::Image {
511///         image: "myapp:latest".to_string(),
512///     })
513///     .cpu(ResourceSpec { min: "0.5".to_string(), desired: "1".to_string() })
514///     .memory(ResourceSpec { min: "512Mi".to_string(), desired: "1Gi".to_string() })
515///     .port(8080)
516///     .public_endpoint(PublicEndpoint {
517///         name: "api".to_string(),
518///         port: 8080,
519///         protocol: ExposeProtocol::Http,
520///         host_label: None,
521///         wildcard_subdomains: false,
522///     })
523///     .autoscaling(ContainerAutoscaling {
524///         min: 2,
525///         desired: 3,
526///         max: 10,
527///         target_cpu_percent: Some(70.0),
528///         target_memory_percent: None,
529///         target_http_in_flight_per_replica: Some(100),
530///         max_http_p95_latency_ms: None,
531///     })
532///     .permissions("container-execution".to_string())
533///     .build();
534/// ```
535#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
536#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
537#[serde(rename_all = "camelCase", deny_unknown_fields)]
538#[builder(start_fn = new)]
539pub struct Container {
540    /// Unique identifier for the container.
541    /// Must be DNS-compatible: lowercase alphanumeric with hyphens.
542    #[builder(start_fn)]
543    pub id: String,
544
545    /// Resource links (dependencies)
546    #[builder(field)]
547    pub links: Vec<ResourceRef>,
548
549    /// Ports reachable by compute-cluster members and resources that link to this container.
550    #[builder(field)]
551    pub ports: Vec<ContainerPort>,
552
553    /// Existing Kubernetes Secrets mounted as read-only directories.
554    #[builder(field)]
555    #[serde(default, skip_serializing_if = "Vec::is_empty")]
556    pub kubernetes_secret_mounts: Vec<KubernetesSecretMount>,
557
558    /// Public endpoints exposed by the container.
559    #[builder(field)]
560    #[serde(default, skip_serializing_if = "Vec::is_empty")]
561    pub public_endpoints: Vec<PublicEndpoint>,
562
563    /// Optional public-internet-only egress. Requires restricted security and backend support.
564    #[serde(default, skip_serializing_if = "Option::is_none")]
565    pub egress: Option<ContainerEgress>,
566
567    /// Container tunnels were removed. Releases and checkpoints saved before
568    /// that still carry the field; it is read and discarded, never written.
569    #[serde(default, rename = "tunnel", skip_serializing)]
570    #[cfg_attr(feature = "openapi", schema(ignore))]
571    #[builder(skip)]
572    retired_tunnel: Option<serde_json::Value>,
573
574    /// Kubernetes liveness probe. Restarts an unhealthy container.
575    #[serde(skip_serializing_if = "Option::is_none")]
576    pub kubernetes_liveness_probe: Option<KubernetesHttpProbe>,
577
578    /// Kubernetes readiness probe. Removes an unready pod from Service endpoints.
579    #[serde(skip_serializing_if = "Option::is_none")]
580    pub kubernetes_readiness_probe: Option<KubernetesHttpProbe>,
581
582    /// Security settings shared by supported container runtimes. Absent means
583    /// the workload runs as its image was built; set `profile: restricted` for
584    /// the Kubernetes Pod Security `restricted` profile.
585    #[serde(skip_serializing_if = "Option::is_none")]
586    pub security: Option<ContainerSecurity>,
587
588    /// ComputeCluster resource ID that this container runs on.
589    /// If None, will be auto-assigned by ComputeClusterMutation at deployment time.
590    #[serde(skip_serializing_if = "Option::is_none")]
591    pub cluster: Option<String>,
592
593    /// Container code (image or source)
594    pub code: ContainerCode,
595
596    /// CPU resource requirements
597    pub cpu: ResourceSpec,
598
599    /// Memory resource requirements (must use Ki/Mi/Gi/Ti suffix)
600    pub memory: ResourceSpec,
601
602    /// Optional deployment-time CPU and memory choices. Fixed declarations stay fixed.
603    #[serde(default, skip_serializing_if = "Option::is_none")]
604    pub resource_choices: Option<ContainerResourceChoices>,
605
606    /// GPU requirements (optional)
607    #[serde(skip_serializing_if = "Option::is_none")]
608    pub gpu: Option<ContainerGpuSpec>,
609
610    /// Ephemeral storage requirement (e.g., "10Gi")
611    #[serde(skip_serializing_if = "Option::is_none")]
612    pub ephemeral_storage: Option<String>,
613
614    /// Persistent storage configuration (only for stateful containers)
615    #[serde(skip_serializing_if = "Option::is_none")]
616    pub persistent_storage: Option<PersistentStorage>,
617
618    /// Fixed replica count (for stateful containers or stateless without autoscaling)
619    #[serde(skip_serializing_if = "Option::is_none")]
620    pub replicas: Option<u32>,
621
622    /// Autoscaling configuration (only for stateless containers)
623    #[serde(skip_serializing_if = "Option::is_none")]
624    pub autoscaling: Option<ContainerAutoscaling>,
625
626    /// Whether container is stateful (gets stable ordinals, optional persistent volumes)
627    #[builder(default = false)]
628    #[serde(default)]
629    pub stateful: bool,
630
631    /// Environment variables
632    #[builder(default)]
633    #[serde(default)]
634    pub environment: HashMap<String, String>,
635
636    /// Capacity group to run on (must exist in the cluster)
637    /// If not specified, containers are scheduled to any available group.
638    #[serde(skip_serializing_if = "Option::is_none")]
639    pub pool: Option<String>,
640
641    /// Permission profile name
642    pub permissions: String,
643
644    /// Health check configuration
645    #[serde(skip_serializing_if = "Option::is_none")]
646    pub health_check: Option<HealthCheck>,
647
648    /// Command to override image default
649    #[serde(skip_serializing_if = "Option::is_none")]
650    pub command: Option<Vec<String>>,
651
652    /// Whether the container can receive remote commands via the Commands protocol.
653    /// When enabled, an app-owned command receiver can lease pending commands
654    /// for this Container and execute registered handlers.
655    #[builder(default = default_commands_enabled())]
656    #[serde(default = "default_commands_enabled")]
657    #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
658    pub commands_enabled: bool,
659
660    /// Set by `alien build` when the container's command receiver reads its
661    /// credential from `ALIEN_COMMANDS_CAPABILITY_FILE`. Absent means the
662    /// receiver may be older, so a deployer that rotates credentials keeps
663    /// the long-lived `ALIEN_COMMANDS_TOKEN` for it. Build output replaces any
664    /// value written in the stack definition.
665    #[builder(default)]
666    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
667    pub commands_capability_file: bool,
668
669    /// Grace period in seconds for stopping replicas during updates, drains, and deletes.
670    ///
671    /// When omitted, the runtime backend applies its default. Valid values are
672    /// 1 second through 24 hours.
673    #[serde(skip_serializing_if = "Option::is_none")]
674    #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
675    pub stop_grace_period_seconds: Option<u32>,
676
677    /// Relative scheduling importance. On Kubernetes the cluster administrator maps each
678    /// level to a PriorityClass at install time; unset leaves the pod without one. Other
679    /// platforms ignore it.
680    #[serde(default, skip_serializing_if = "Option::is_none")]
681    pub priority: Option<WorkloadPriority>,
682}
683
684impl Container {
685    /// The resource type identifier for Container
686    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
687
688    /// Returns the container's unique identifier.
689    pub fn id(&self) -> &str {
690        &self.id
691    }
692
693    /// Returns the permission profile name for this container.
694    pub fn get_permissions(&self) -> &str {
695        &self.permissions
696    }
697
698    /// Returns true if this container is stateless (not stateful).
699    pub fn is_stateless(&self) -> bool {
700        !self.stateful
701    }
702
703    /// Validate resource-local network options; preflight also checks source existence and backend support.
704    pub fn validate_network_settings(&self) -> Result<()> {
705        let invalid = |reason: String| {
706            AlienError::new(ErrorData::InvalidResourceUpdate {
707                resource_id: self.id.clone(),
708                reason,
709            })
710        };
711        if self.egress.is_some() && !ContainerSecurity::is_restricted(self.security.as_ref()) {
712            return Err(invalid(
713                "container egress internet requires security.profile restricted".into(),
714            ));
715        }
716        Ok(())
717    }
718
719    /// Validates the public endpoint configuration.
720    fn validate_public_endpoints(&self) -> Result<()> {
721        let mut endpoint_names = std::collections::HashSet::new();
722        let mut backend_ports = std::collections::HashSet::new();
723        let mut apex_endpoint_name: Option<&str> = None;
724
725        for endpoint in &self.public_endpoints {
726            endpoint.validate_for_resource(&self.id)?;
727
728            if !endpoint_names.insert(endpoint.name.as_str()) {
729                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
730                    resource_id: self.id.clone(),
731                    reason: format!("duplicate public endpoint name '{}'", endpoint.name),
732                }));
733            }
734
735            if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
736                if let Some(existing_name) = apex_endpoint_name {
737                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
738                        resource_id: self.id.clone(),
739                        reason: format!(
740                            "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
741                            existing_name
742                        ),
743                    }));
744                }
745                apex_endpoint_name = Some(endpoint.name.as_str());
746            }
747
748            backend_ports.insert(endpoint.port);
749
750            if !self.ports.iter().any(|port| port.port == endpoint.port) {
751                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
752                    resource_id: self.id.clone(),
753                    reason: format!(
754                        "public endpoint '{}' references undeclared port {}",
755                        endpoint.name, endpoint.port
756                    ),
757                }));
758            }
759        }
760
761        if backend_ports.len() > 1 {
762            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
763                resource_id: self.id.clone(),
764                reason:
765                    "public endpoints on one container must currently route to the same backend port"
766                        .to_string(),
767            }));
768        }
769
770        Ok(())
771    }
772}
773
774fn default_commands_enabled() -> bool {
775    false
776}
777
778impl<S: container_builder::State> ContainerBuilder<S> {
779    /// Links the container to another resource with specified permissions.
780    pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
781    where
782        for<'a> &'a R: Into<ResourceRef>,
783    {
784        let resource_ref: ResourceRef = resource.into();
785        self.links.push(resource_ref);
786        self
787    }
788
789    /// Adds an internal-only port to the container.
790    pub fn port(mut self, port: u16) -> Self {
791        self.ports.push(ContainerPort { port });
792        self
793    }
794
795    /// Mounts an existing Kubernetes Secret without copying its value into the stack.
796    pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
797        self.kubernetes_secret_mounts.push(mount);
798        self
799    }
800
801    /// Exposes a named public endpoint.
802    pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
803        if !self.ports.iter().any(|p| p.port == endpoint.port) {
804            self.ports.push(ContainerPort {
805                port: endpoint.port,
806            });
807        }
808        self.public_endpoints.push(endpoint);
809        self
810    }
811}
812
813/// Container status in the managed container backend.
814#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
815#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
816#[serde(rename_all = "camelCase")]
817pub enum ContainerStatus {
818    /// Waiting for replicas to start
819    Pending,
820    /// Min replicas healthy and serving
821    Running,
822    /// Manually stopped
823    Stopped,
824    /// Something is wrong — see statusReason/statusMessage; scheduler keeps retrying.
825    /// Covers all failure modes: crash-looping, unschedulable, replica failures, etc.
826    Failing,
827}
828
829/// Status of a single container replica.
830#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
831#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
832#[serde(rename_all = "camelCase")]
833pub struct ReplicaStatus {
834    /// Replica ID (e.g., "api-0", "api-1")
835    pub replica_id: String,
836    /// Ordinal (for stateful containers)
837    pub ordinal: Option<u32>,
838    /// Machine ID the replica is running on
839    pub machine_id: Option<String>,
840    /// Whether the replica is healthy
841    pub healthy: bool,
842    /// Container IP address (for service discovery)
843    pub container_ip: Option<String>,
844}
845
846/// Outputs generated by a successfully provisioned Container.
847#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
848#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
849#[serde(rename_all = "camelCase")]
850pub struct ContainerOutputs {
851    /// Container name in the managed container backend
852    pub name: String,
853    /// Current container status
854    pub status: ContainerStatus,
855    /// Number of current replicas
856    pub current_replicas: u32,
857    /// Desired number of replicas
858    pub desired_replicas: u32,
859    /// Internal DNS name of the container's Service. On Kubernetes this is
860    /// `<name>.<namespace>.svc.<cluster domain>`; other platforms have no such
861    /// name. To reach another container, use the link binding
862    /// (`ALIEN_<ID>_BINDING`, `internalUrls`), not a name built from the id.
863    pub internal_dns: String,
864    /// Public endpoints resolved for this container.
865    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
866    pub public_endpoints: HashMap<String, PublicEndpointOutput>,
867    /// Internal URLs keyed by port for cluster members and linking resources.
868    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
869    pub internal_urls: HashMap<u16, String>,
870    /// Status of each replica
871    pub replicas: Vec<ReplicaStatus>,
872    /// Persistent volumes, one per replica ordinal, with their latest snapshot.
873    #[serde(default, skip_serializing_if = "Vec::is_empty")]
874    pub volumes: Vec<VolumeOutput>,
875    /// Whether the persistent volumes' snapshot schedule is in place.
876    #[serde(default, skip_serializing_if = "Option::is_none")]
877    pub volume_backups: Option<VolumeBackupsStatus>,
878}
879
880/// Whether a container's snapshot schedule is in place.
881#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
882#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
883#[serde(rename_all = "camelCase")]
884pub struct VolumeBackupsStatus {
885    /// Current state of the schedule
886    pub state: VolumeBackupsState,
887    /// What is missing when the state is `setupRequired`
888    #[serde(skip_serializing_if = "Option::is_none")]
889    pub message: Option<String>,
890}
891
892/// State of a container's snapshot schedule.
893#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
894#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
895#[serde(rename_all = "camelCase")]
896pub enum VolumeBackupsState {
897    /// The cloud's scheduler is taking snapshots.
898    Active,
899    /// Backups are turned off in the stack.
900    Disabled,
901    /// The deployment's management permissions predate volume backups. The
902    /// container keeps running without a schedule until the installation's
903    /// setup is updated; the controller then applies the schedule by itself.
904    SetupRequired,
905}
906
907/// A replica's persistent volume and its latest completed snapshot.
908#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
909#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
910#[serde(rename_all = "camelCase")]
911pub struct VolumeOutput {
912    /// Replica ordinal the volume belongs to
913    pub ordinal: u32,
914    /// Cloud ID of the volume (EBS volume ID, Persistent Disk name, or Managed Disk ID)
915    pub volume_id: String,
916    /// Zone the volume lives in
917    pub zone: String,
918    /// Cloud ID of the latest completed snapshot, if any
919    #[serde(skip_serializing_if = "Option::is_none")]
920    pub last_snapshot_id: Option<String>,
921    /// When the latest completed snapshot was started (RFC 3339)
922    #[serde(skip_serializing_if = "Option::is_none")]
923    pub last_snapshot_at: Option<String>,
924    /// The latest volume restore performed on this ordinal, if any
925    #[serde(skip_serializing_if = "Option::is_none")]
926    pub last_restore: Option<VolumeRestoreOutput>,
927}
928
929/// A completed volume restore.
930#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
931#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
932#[serde(rename_all = "camelCase")]
933pub struct VolumeRestoreOutput {
934    /// ID of the restore request
935    pub request_id: String,
936    /// Snapshot the volume was restored from
937    pub snapshot_id: String,
938    /// Snapshot of the replaced volume, taken just before it was deleted
939    pub replaced_volume_snapshot_id: String,
940    /// When the restored volume was put in place (RFC 3339)
941    pub completed_at: String,
942}
943
944impl ResourceOutputsDefinition for ContainerOutputs {
945    fn get_resource_type(&self) -> ResourceType {
946        Container::RESOURCE_TYPE.clone()
947    }
948
949    fn as_any(&self) -> &dyn Any {
950        self
951    }
952
953    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
954        Box::new(self.clone())
955    }
956
957    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
958        other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
959    }
960
961    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
962        serde_json::to_value(self)
963    }
964}
965
966impl ResourceDefinition for Container {
967    fn get_resource_type(&self) -> ResourceType {
968        Self::RESOURCE_TYPE
969    }
970
971    fn id(&self) -> &str {
972        &self.id
973    }
974
975    fn replace_after_failed_create_is_safe(&self) -> bool {
976        // Deleting it destroys the persistent volumes of a stateful container.
977        !(self.stateful && self.persistent_storage.is_some())
978    }
979
980    fn get_dependencies(&self) -> Vec<ResourceRef> {
981        let mut deps = self.links.clone();
982        if let Some(key) = self
983            .persistent_storage
984            .as_ref()
985            .and_then(|storage| storage.encryption_key.as_ref())
986        {
987            deps.push(key.clone());
988        }
989        // Add dependency on the container cluster if explicitly specified.
990        // If None, ComputeClusterMutation will auto-assign at deployment time.
991        if let Some(cluster) = &self.cluster {
992            deps.push(ResourceRef::new(
993                ComputeCluster::RESOURCE_TYPE.clone(),
994                cluster,
995            ));
996        }
997        deps
998    }
999
1000    fn get_permissions(&self) -> Option<&str> {
1001        Some(&self.permissions)
1002    }
1003
1004    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1005        let new_container = new_config
1006            .as_any()
1007            .downcast_ref::<Container>()
1008            .ok_or_else(|| {
1009                AlienError::new(ErrorData::UnexpectedResourceType {
1010                    resource_id: self.id.clone(),
1011                    expected: Self::RESOURCE_TYPE,
1012                    actual: new_config.get_resource_type(),
1013                })
1014            })?;
1015
1016        // Validate the new config's public endpoints.
1017        new_container.validate_public_endpoints()?;
1018        new_container.validate_network_settings()?;
1019
1020        if self.id != new_container.id {
1021            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1022                resource_id: self.id.clone(),
1023                reason: "the 'id' field is immutable".to_string(),
1024            }));
1025        }
1026
1027        // Cluster is immutable
1028        if self.cluster != new_container.cluster {
1029            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1030                resource_id: self.id.clone(),
1031                reason: "the 'cluster' field is immutable".to_string(),
1032            }));
1033        }
1034
1035        // Stateful is immutable
1036        if self.stateful != new_container.stateful {
1037            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1038                resource_id: self.id.clone(),
1039                reason: "the 'stateful' field is immutable".to_string(),
1040            }));
1041        }
1042
1043        let old_key = self
1044            .persistent_storage
1045            .as_ref()
1046            .and_then(|storage| storage.encryption_key.as_ref());
1047        let new_key = new_container
1048            .persistent_storage
1049            .as_ref()
1050            .and_then(|storage| storage.encryption_key.as_ref());
1051        if old_key != new_key {
1052            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1053                resource_id: self.id.clone(),
1054                reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
1055            }));
1056        }
1057
1058        // Ports are immutable (requires load balancer reconfiguration)
1059        if self.ports != new_container.ports {
1060            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1061                resource_id: self.id.clone(),
1062                reason: "the 'ports' field is immutable".to_string(),
1063            }));
1064        }
1065
1066        if self.public_endpoints != new_container.public_endpoints {
1067            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1068                resource_id: self.id.clone(),
1069                reason: "the 'publicEndpoints' field is immutable".to_string(),
1070            }));
1071        }
1072
1073        // Pool (capacity group) is immutable
1074        if self.pool != new_container.pool {
1075            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1076                resource_id: self.id.clone(),
1077                reason: "the 'pool' field is immutable".to_string(),
1078            }));
1079        }
1080
1081        Ok(())
1082    }
1083
1084    fn as_any(&self) -> &dyn Any {
1085        self
1086    }
1087
1088    fn as_any_mut(&mut self) -> &mut dyn Any {
1089        self
1090    }
1091
1092    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1093        Box::new(self.clone())
1094    }
1095
1096    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1097        other.as_any().downcast_ref::<Container>() == Some(self)
1098    }
1099
1100    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1101        serde_json::to_value(self)
1102    }
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107    #[derive(Debug, serde::Deserialize)]
1108    #[serde(rename_all = "camelCase")]
1109    enum PreviousProfile {
1110        Restricted,
1111    }
1112
1113    /// `ContainerSecurity` exactly as the previous release declares it. State and
1114    /// air-gap bundles written by this version must parse with it, so an Operator
1115    /// rollback keeps working.
1116    #[derive(Debug, serde::Deserialize)]
1117    #[serde(rename_all = "camelCase")]
1118    #[allow(dead_code)]
1119    struct PreviousContainerSecurity {
1120        profile: PreviousProfile,
1121        run_as_user: i64,
1122        run_as_group: i64,
1123        read_only_root_filesystem: bool,
1124    }
1125
1126    #[test]
1127    fn written_security_parses_with_the_previous_release_struct() {
1128        let defaults = ContainerSecurity {
1129            profile: ContainerSecurityProfile::Restricted,
1130            run_as_user: None,
1131            run_as_group: None,
1132            read_only_root_filesystem: None,
1133            writable_paths: Vec::new(),
1134        };
1135        let explicit = ContainerSecurity {
1136            profile: ContainerSecurityProfile::Unrestricted,
1137            run_as_user: Some(70),
1138            run_as_group: Some(71),
1139            read_only_root_filesystem: Some(false),
1140            writable_paths: vec!["/data".to_string()],
1141        };
1142        let unrestricted_defaults = ContainerSecurity {
1143            profile: ContainerSecurityProfile::Unrestricted,
1144            ..defaults.clone()
1145        };
1146        let explicit_zero = ContainerSecurity {
1147            profile: ContainerSecurityProfile::Restricted,
1148            run_as_user: Some(0),
1149            run_as_group: None,
1150            read_only_root_filesystem: Some(false),
1151            writable_paths: Vec::new(),
1152        };
1153        for security in [defaults, explicit, unrestricted_defaults, explicit_zero] {
1154            let json = serde_json::to_value(&security).unwrap();
1155            serde_json::from_value::<PreviousContainerSecurity>(json.clone())
1156                .unwrap_or_else(|error| panic!("previous release cannot read {json}: {error}"));
1157            // Reading our own output restores the value, so stacks do not diff.
1158            let back: ContainerSecurity = serde_json::from_value(json).unwrap();
1159            assert_eq!(back, security);
1160        }
1161    }
1162
1163    /// An opted-out workload is written as `restricted` plus a marker. A previous
1164    /// Operator ignores the marker and applies the restricted settings, so a
1165    /// rollback fails safe: a root image stops starting instead of gaining
1166    /// privileges. Upgrading the Operator again restores the opt-out.
1167    #[test]
1168    fn unrestricted_opt_out_reads_as_restricted_with_the_previous_release_struct() {
1169        let security = ContainerSecurity {
1170            profile: ContainerSecurityProfile::Unrestricted,
1171            run_as_user: Some(0),
1172            run_as_group: Some(0),
1173            read_only_root_filesystem: Some(false),
1174            writable_paths: Vec::new(),
1175        };
1176        let json = serde_json::to_value(&security).unwrap();
1177        assert_eq!(json["profile"], "restricted");
1178        assert_eq!(json["unrestricted"], true);
1179        let previous: PreviousContainerSecurity = serde_json::from_value(json.clone()).unwrap();
1180        assert!(matches!(previous.profile, PreviousProfile::Restricted));
1181        let back: ContainerSecurity = serde_json::from_value(json).unwrap();
1182        assert_eq!(back, security);
1183    }
1184
1185    /// There is no default profile: a `security` object that omits it must
1186    /// not parse as restricted (or as anything else).
1187    #[test]
1188    fn security_without_a_profile_fails_to_parse() {
1189        assert!(
1190            serde_json::from_str::<ContainerSecurity>(r#"{"writablePaths":["/cache"]}"#).is_err()
1191        );
1192        assert!(serde_json::from_str::<ContainerSecurity>("{}").is_err());
1193    }
1194
1195    #[test]
1196    fn security_reads_accept_the_plain_unrestricted_profile() {
1197        let security: ContainerSecurity =
1198            serde_json::from_str(r#"{"profile":"unrestricted"}"#).unwrap();
1199        assert_eq!(security.profile, ContainerSecurityProfile::Unrestricted);
1200    }
1201
1202    #[test]
1203    fn security_reads_tolerate_omitted_fields() {
1204        let security: ContainerSecurity =
1205            serde_json::from_str(r#"{"profile":"restricted"}"#).unwrap();
1206        assert_eq!(security.run_as_user, None);
1207        assert_eq!(security.read_only_root_filesystem, None);
1208    }
1209
1210    use super::*;
1211    use crate::resources::ExposeProtocol;
1212
1213    fn network_container() -> Container {
1214        Container::new("api".to_string())
1215            .code(ContainerCode::Image {
1216                image: "example:latest".into(),
1217            })
1218            .cpu(ResourceSpec {
1219                min: "1".into(),
1220                desired: "1".into(),
1221            })
1222            .memory(ResourceSpec {
1223                min: "512Mi".into(),
1224                desired: "512Mi".into(),
1225            })
1226            .permissions("execution".into())
1227            .public_endpoint(PublicEndpoint {
1228                name: "web".into(),
1229                port: 8080,
1230                protocol: ExposeProtocol::Http,
1231                host_label: None,
1232                wildcard_subdomains: false,
1233            })
1234            .build()
1235    }
1236
1237    #[test]
1238    fn a_saved_container_with_the_retired_tunnel_field_still_loads() {
1239        let saved = serde_json::json!({
1240            "id": "api",
1241            "code": {"type": "image", "image": "example/api:1"},
1242            "cpu": {"min": "0.5", "desired": "0.5"},
1243            "memory": {"min": "256Mi", "desired": "256Mi"},
1244            "permissions": "execution",
1245            "links": [], "ports": [],
1246            "tunnel": {"port": 8080}
1247        });
1248        let container: Container = serde_json::from_value(saved).expect("saved container loads");
1249        assert!(serde_json::to_value(&container)
1250            .unwrap()
1251            .get("tunnel")
1252            .is_none());
1253    }
1254
1255    #[test]
1256    fn internet_egress_is_opt_in_and_refuses_the_unrestricted_profile() {
1257        let mut container = network_container();
1258        assert!(serde_json::to_value(&container)
1259            .unwrap()
1260            .get("egress")
1261            .is_none());
1262        // Egress needs the restricted profile written explicitly: an absent
1263        // setting means the workload runs as built.
1264        container.egress = Some(ContainerEgress::Internet);
1265        assert!(container.validate_update(&container).is_err());
1266        container.security = Some(ContainerSecurity {
1267            profile: ContainerSecurityProfile::Unrestricted,
1268            run_as_user: None,
1269            run_as_group: None,
1270            read_only_root_filesystem: None,
1271            writable_paths: Vec::new(),
1272        });
1273        assert!(container.validate_update(&container).is_err());
1274        container.security = Some(ContainerSecurity {
1275            profile: ContainerSecurityProfile::Restricted,
1276            run_as_user: Some(65532),
1277            run_as_group: Some(65532),
1278            read_only_root_filesystem: Some(true),
1279            writable_paths: Vec::new(),
1280        });
1281        container.validate_update(&container).unwrap();
1282        assert_eq!(
1283            serde_json::to_value(&container).unwrap()["egress"],
1284            "internet"
1285        );
1286    }
1287
1288    #[test]
1289    fn test_container_creation_with_autoscaling() {
1290        let container = Container::new("api".to_string())
1291            .cluster("compute".to_string())
1292            .code(ContainerCode::Image {
1293                image: "myapp:latest".to_string(),
1294            })
1295            .cpu(ResourceSpec {
1296                min: "0.5".to_string(),
1297                desired: "1".to_string(),
1298            })
1299            .memory(ResourceSpec {
1300                min: "512Mi".to_string(),
1301                desired: "1Gi".to_string(),
1302            })
1303            .port(8080)
1304            .public_endpoint(PublicEndpoint {
1305                name: "api".to_string(),
1306                port: 8080,
1307                protocol: ExposeProtocol::Http,
1308                host_label: None,
1309                wildcard_subdomains: false,
1310            })
1311            .autoscaling(ContainerAutoscaling {
1312                min: 2,
1313                desired: 3,
1314                max: 10,
1315                target_cpu_percent: Some(70.0),
1316                target_memory_percent: None,
1317                target_http_in_flight_per_replica: Some(100),
1318                max_http_p95_latency_ms: None,
1319            })
1320            .permissions("container-execution".to_string())
1321            .build();
1322
1323        assert_eq!(container.id(), "api");
1324        assert_eq!(container.cluster, Some("compute".to_string()));
1325        assert!(!container.stateful);
1326        assert!(container.autoscaling.is_some());
1327        assert_eq!(container.ports.len(), 1);
1328        assert_eq!(container.ports[0].port, 8080);
1329    }
1330
1331    #[test]
1332    fn container_serializes_stop_grace_period_when_set() {
1333        let container = Container::new("api".to_string())
1334            .cluster("compute".to_string())
1335            .code(ContainerCode::Image {
1336                image: "myapp:latest".to_string(),
1337            })
1338            .cpu(ResourceSpec {
1339                min: "0.5".to_string(),
1340                desired: "1".to_string(),
1341            })
1342            .memory(ResourceSpec {
1343                min: "512Mi".to_string(),
1344                desired: "1Gi".to_string(),
1345            })
1346            .port(8080)
1347            .permissions("container-execution".to_string())
1348            .stop_grace_period_seconds(21_600)
1349            .build();
1350
1351        let json = serde_json::to_value(&container).expect("container should serialize");
1352        assert_eq!(json["stopGracePeriodSeconds"], 21_600);
1353    }
1354
1355    #[test]
1356    fn container_omits_stop_grace_period_when_absent() {
1357        let container = Container::new("api".to_string())
1358            .cluster("compute".to_string())
1359            .code(ContainerCode::Image {
1360                image: "myapp:latest".to_string(),
1361            })
1362            .cpu(ResourceSpec {
1363                min: "0.5".to_string(),
1364                desired: "1".to_string(),
1365            })
1366            .memory(ResourceSpec {
1367                min: "512Mi".to_string(),
1368                desired: "1Gi".to_string(),
1369            })
1370            .port(8080)
1371            .permissions("container-execution".to_string())
1372            .build();
1373
1374        let json = serde_json::to_value(&container).expect("container should serialize");
1375        assert!(json.get("stopGracePeriodSeconds").is_none());
1376    }
1377
1378    #[test]
1379    fn test_stateful_container_with_storage() {
1380        let container = Container::new("postgres".to_string())
1381            .cluster("compute".to_string())
1382            .code(ContainerCode::Image {
1383                image: "postgres:16".to_string(),
1384            })
1385            .cpu(ResourceSpec {
1386                min: "1".to_string(),
1387                desired: "2".to_string(),
1388            })
1389            .memory(ResourceSpec {
1390                min: "2Gi".to_string(),
1391                desired: "4Gi".to_string(),
1392            })
1393            .port(5432)
1394            .stateful(true)
1395            .replicas(1)
1396            .persistent_storage(PersistentStorage {
1397                encryption_key: None,
1398                size: "100Gi".to_string(),
1399                mount_path: "/var/lib/postgresql/data".to_string(),
1400                backups: VolumeBackups::default(),
1401            })
1402            .permissions("database".to_string())
1403            .build();
1404
1405        assert_eq!(container.id(), "postgres");
1406        assert!(container.stateful);
1407        assert!(container.replicas.is_some());
1408        assert!(container.persistent_storage.is_some());
1409    }
1410
1411    #[test]
1412    fn test_public_container() {
1413        let container = Container::new("frontend".to_string())
1414            .cluster("compute".to_string())
1415            .code(ContainerCode::Image {
1416                image: "frontend:latest".to_string(),
1417            })
1418            .cpu(ResourceSpec {
1419                min: "0.25".to_string(),
1420                desired: "0.5".to_string(),
1421            })
1422            .memory(ResourceSpec {
1423                min: "256Mi".to_string(),
1424                desired: "512Mi".to_string(),
1425            })
1426            .port(3000)
1427            .public_endpoint(PublicEndpoint {
1428                name: "web".to_string(),
1429                port: 3000,
1430                protocol: ExposeProtocol::Http,
1431                host_label: None,
1432                wildcard_subdomains: false,
1433            })
1434            .autoscaling(ContainerAutoscaling {
1435                min: 2,
1436                desired: 2,
1437                max: 20,
1438                target_cpu_percent: None,
1439                target_memory_percent: None,
1440                target_http_in_flight_per_replica: Some(50),
1441                max_http_p95_latency_ms: Some(100.0),
1442            })
1443            .health_check(HealthCheck {
1444                path: "/health".to_string(),
1445                port: None,
1446                method: "GET".to_string(),
1447                timeout_seconds: 1,
1448                failure_threshold: 3,
1449                startup_timeout_seconds: None,
1450            })
1451            .permissions("frontend".to_string())
1452            .build();
1453
1454        assert_eq!(container.ports[0].port, 3000);
1455        assert_eq!(container.public_endpoints[0].name, "web");
1456        assert!(container.health_check.is_some());
1457    }
1458
1459    #[test]
1460    fn test_public_container_endpoint_options() {
1461        let container = Container::new("router".to_string())
1462            .cluster("compute".to_string())
1463            .code(ContainerCode::Image {
1464                image: "router:latest".to_string(),
1465            })
1466            .cpu(ResourceSpec {
1467                min: "0.25".to_string(),
1468                desired: "0.5".to_string(),
1469            })
1470            .memory(ResourceSpec {
1471                min: "256Mi".to_string(),
1472                desired: "512Mi".to_string(),
1473            })
1474            .public_endpoint(PublicEndpoint {
1475                name: "gateway".to_string(),
1476                port: 8080,
1477                protocol: ExposeProtocol::Http,
1478                host_label: Some("gateway".to_string()),
1479                wildcard_subdomains: true,
1480            })
1481            .permissions("router".to_string())
1482            .build();
1483
1484        assert!(container.validate_public_endpoints().is_ok());
1485        assert_eq!(container.ports.len(), 1);
1486        assert_eq!(container.public_endpoints.len(), 1);
1487        assert_eq!(
1488            container.public_endpoints[0].host_label.as_deref(),
1489            Some("gateway")
1490        );
1491        assert!(container.public_endpoints[0].wildcard_subdomains);
1492    }
1493
1494    #[test]
1495    fn test_public_container_rejects_invalid_host_label() {
1496        let container = Container::new("router".to_string())
1497            .cluster("compute".to_string())
1498            .code(ContainerCode::Image {
1499                image: "router:latest".to_string(),
1500            })
1501            .cpu(ResourceSpec {
1502                min: "0.25".to_string(),
1503                desired: "0.5".to_string(),
1504            })
1505            .memory(ResourceSpec {
1506                min: "256Mi".to_string(),
1507                desired: "512Mi".to_string(),
1508            })
1509            .public_endpoint(PublicEndpoint {
1510                name: "gateway".to_string(),
1511                port: 8080,
1512                protocol: ExposeProtocol::Http,
1513                host_label: Some("bad.label".to_string()),
1514                wildcard_subdomains: true,
1515            })
1516            .permissions("router".to_string())
1517            .build();
1518
1519        assert!(container.validate_public_endpoints().is_err());
1520    }
1521
1522    #[test]
1523    fn test_container_with_links() {
1524        use crate::Storage;
1525
1526        let storage = Storage::new("data".to_string()).build();
1527
1528        let container = Container::new("worker".to_string())
1529            .cluster("compute".to_string())
1530            .code(ContainerCode::Image {
1531                image: "worker:latest".to_string(),
1532            })
1533            .cpu(ResourceSpec {
1534                min: "0.5".to_string(),
1535                desired: "1".to_string(),
1536            })
1537            .memory(ResourceSpec {
1538                min: "512Mi".to_string(),
1539                desired: "1Gi".to_string(),
1540            })
1541            .port(8080)
1542            .replicas(3)
1543            .link(&storage)
1544            .permissions("worker".to_string())
1545            .build();
1546
1547        // Should have 2 dependencies: cluster + linked storage
1548        let deps = container.get_dependencies();
1549        assert_eq!(deps.len(), 2);
1550    }
1551
1552    #[test]
1553    fn test_container_validate_update_immutable_cluster() {
1554        let container1 = Container::new("api".to_string())
1555            .cluster("cluster-1".to_string())
1556            .code(ContainerCode::Image {
1557                image: "myapp:v1".to_string(),
1558            })
1559            .cpu(ResourceSpec {
1560                min: "0.5".to_string(),
1561                desired: "1".to_string(),
1562            })
1563            .memory(ResourceSpec {
1564                min: "512Mi".to_string(),
1565                desired: "1Gi".to_string(),
1566            })
1567            .port(8080)
1568            .replicas(2)
1569            .permissions("execution".to_string())
1570            .build();
1571
1572        let container2 = Container::new("api".to_string())
1573            .cluster("cluster-2".to_string()) // Changed cluster
1574            .code(ContainerCode::Image {
1575                image: "myapp:v2".to_string(),
1576            })
1577            .cpu(ResourceSpec {
1578                min: "0.5".to_string(),
1579                desired: "1".to_string(),
1580            })
1581            .memory(ResourceSpec {
1582                min: "512Mi".to_string(),
1583                desired: "1Gi".to_string(),
1584            })
1585            .port(8080)
1586            .replicas(2)
1587            .permissions("execution".to_string())
1588            .build();
1589
1590        let result = container1.validate_update(&container2);
1591        assert!(result.is_err());
1592    }
1593
1594    #[test]
1595    fn test_container_validate_update_allowed_changes() {
1596        let container1 = Container::new("api".to_string())
1597            .cluster("compute".to_string())
1598            .code(ContainerCode::Image {
1599                image: "myapp:v1".to_string(),
1600            })
1601            .cpu(ResourceSpec {
1602                min: "0.5".to_string(),
1603                desired: "1".to_string(),
1604            })
1605            .memory(ResourceSpec {
1606                min: "512Mi".to_string(),
1607                desired: "1Gi".to_string(),
1608            })
1609            .port(8080)
1610            .replicas(2)
1611            .permissions("execution".to_string())
1612            .build();
1613
1614        let container2 = Container::new("api".to_string())
1615            .cluster("compute".to_string())
1616            .code(ContainerCode::Image {
1617                image: "myapp:v2".to_string(), // Image can change
1618            })
1619            .cpu(ResourceSpec {
1620                min: "1".to_string(), // Resources can change
1621                desired: "2".to_string(),
1622            })
1623            .memory(ResourceSpec {
1624                min: "1Gi".to_string(),
1625                desired: "2Gi".to_string(),
1626            })
1627            .port(8080)
1628            .replicas(5) // Replicas can change
1629            .permissions("execution".to_string())
1630            .build();
1631
1632        let result = container1.validate_update(&container2);
1633        assert!(result.is_ok());
1634    }
1635
1636    #[test]
1637    fn test_container_serialization() {
1638        let container = Container::new("test".to_string())
1639            .cluster("compute".to_string())
1640            .code(ContainerCode::Image {
1641                image: "test:latest".to_string(),
1642            })
1643            .cpu(ResourceSpec {
1644                min: "0.5".to_string(),
1645                desired: "1".to_string(),
1646            })
1647            .memory(ResourceSpec {
1648                min: "512Mi".to_string(),
1649                desired: "1Gi".to_string(),
1650            })
1651            .port(8080)
1652            .replicas(1)
1653            .permissions("test".to_string())
1654            .build();
1655
1656        let json = serde_json::to_string(&container).unwrap();
1657        let deserialized: Container = serde_json::from_str(&json).unwrap();
1658        assert_eq!(container, deserialized);
1659    }
1660
1661    #[test]
1662    fn test_container_multi_endpoint_validation() {
1663        let container = Container::new("multi-tcp".to_string())
1664            .cluster("compute".to_string())
1665            .code(ContainerCode::Image {
1666                image: "test:latest".to_string(),
1667            })
1668            .cpu(ResourceSpec {
1669                min: "1".to_string(),
1670                desired: "1".to_string(),
1671            })
1672            .memory(ResourceSpec {
1673                min: "1Gi".to_string(),
1674                desired: "1Gi".to_string(),
1675            })
1676            .port(8080)
1677            .public_endpoint(PublicEndpoint {
1678                name: "api".to_string(),
1679                port: 8080,
1680                protocol: ExposeProtocol::Http,
1681                host_label: None,
1682                wildcard_subdomains: false,
1683            })
1684            .public_endpoint(PublicEndpoint {
1685                name: "wildcard".to_string(),
1686                port: 8080,
1687                protocol: ExposeProtocol::Http,
1688                host_label: Some("wildcard".to_string()),
1689                wildcard_subdomains: true,
1690            })
1691            .replicas(1)
1692            .permissions("test".to_string())
1693            .build();
1694
1695        assert!(container.validate_public_endpoints().is_ok());
1696
1697        let invalid_container = Container::new("multi-http".to_string())
1698            .cluster("compute".to_string())
1699            .code(ContainerCode::Image {
1700                image: "test:latest".to_string(),
1701            })
1702            .cpu(ResourceSpec {
1703                min: "1".to_string(),
1704                desired: "1".to_string(),
1705            })
1706            .memory(ResourceSpec {
1707                min: "1Gi".to_string(),
1708                desired: "1Gi".to_string(),
1709            })
1710            .port(8080)
1711            .port(9090)
1712            .public_endpoint(PublicEndpoint {
1713                name: "api".to_string(),
1714                port: 8080,
1715                protocol: ExposeProtocol::Http,
1716                host_label: None,
1717                wildcard_subdomains: false,
1718            })
1719            .public_endpoint(PublicEndpoint {
1720                name: "admin".to_string(),
1721                port: 9090,
1722                protocol: ExposeProtocol::Http,
1723                host_label: None,
1724                wildcard_subdomains: false,
1725            })
1726            .replicas(1)
1727            .permissions("test".to_string())
1728            .build();
1729
1730        assert!(invalid_container.validate_public_endpoints().is_err());
1731    }
1732
1733    #[test]
1734    fn container_rejects_multiple_apex_public_endpoints() {
1735        let container = Container::new("apex-container".to_string())
1736            .cluster("compute".to_string())
1737            .code(ContainerCode::Image {
1738                image: "test:latest".to_string(),
1739            })
1740            .cpu(ResourceSpec {
1741                min: "1".to_string(),
1742                desired: "1".to_string(),
1743            })
1744            .memory(ResourceSpec {
1745                min: "1Gi".to_string(),
1746                desired: "1Gi".to_string(),
1747            })
1748            .port(8080)
1749            .public_endpoint(PublicEndpoint {
1750                name: "web".to_string(),
1751                port: 8080,
1752                protocol: ExposeProtocol::Http,
1753                host_label: Some(APEX_HOST_LABEL.to_string()),
1754                wildcard_subdomains: false,
1755            })
1756            .public_endpoint(PublicEndpoint {
1757                name: "admin".to_string(),
1758                port: 8080,
1759                protocol: ExposeProtocol::Http,
1760                host_label: Some(APEX_HOST_LABEL.to_string()),
1761                wildcard_subdomains: false,
1762            })
1763            .replicas(1)
1764            .permissions("test".to_string())
1765            .build();
1766
1767        assert!(container.validate_public_endpoints().is_err());
1768    }
1769
1770    #[test]
1771    fn test_container_empty_ports_validation() {
1772        let container = Container::new("no-ports".to_string())
1773            .cluster("compute".to_string())
1774            .code(ContainerCode::Image {
1775                image: "test:latest".to_string(),
1776            })
1777            .cpu(ResourceSpec {
1778                min: "1".to_string(),
1779                desired: "1".to_string(),
1780            })
1781            .memory(ResourceSpec {
1782                min: "1Gi".to_string(),
1783                desired: "1Gi".to_string(),
1784            })
1785            .replicas(1)
1786            .permissions("test".to_string())
1787            .build();
1788
1789        assert!(container.validate_public_endpoints().is_ok());
1790    }
1791
1792    #[test]
1793    fn test_container_commands_enabled_defaults_false() {
1794        let container = Container::new("no-commands".to_string())
1795            .cluster("compute".to_string())
1796            .code(ContainerCode::Image {
1797                image: "test:latest".to_string(),
1798            })
1799            .cpu(ResourceSpec {
1800                min: "0.5".to_string(),
1801                desired: "1".to_string(),
1802            })
1803            .memory(ResourceSpec {
1804                min: "512Mi".to_string(),
1805                desired: "1Gi".to_string(),
1806            })
1807            .port(8080)
1808            .permissions("test".to_string())
1809            .build();
1810
1811        assert!(!container.commands_enabled);
1812    }
1813
1814    #[test]
1815    fn test_container_commands_enabled_builder() {
1816        let container = Container::new("cmd-container".to_string())
1817            .cluster("compute".to_string())
1818            .code(ContainerCode::Image {
1819                image: "test:latest".to_string(),
1820            })
1821            .cpu(ResourceSpec {
1822                min: "0.5".to_string(),
1823                desired: "1".to_string(),
1824            })
1825            .memory(ResourceSpec {
1826                min: "512Mi".to_string(),
1827                desired: "1Gi".to_string(),
1828            })
1829            .port(8080)
1830            .permissions("test".to_string())
1831            .commands_enabled(true)
1832            .build();
1833
1834        assert!(container.commands_enabled);
1835    }
1836
1837    #[test]
1838    fn test_container_commands_enabled_serializes_camel_case() {
1839        let container = Container::new("cmd-container".to_string())
1840            .cluster("compute".to_string())
1841            .code(ContainerCode::Image {
1842                image: "test:latest".to_string(),
1843            })
1844            .cpu(ResourceSpec {
1845                min: "0.5".to_string(),
1846                desired: "1".to_string(),
1847            })
1848            .memory(ResourceSpec {
1849                min: "512Mi".to_string(),
1850                desired: "1Gi".to_string(),
1851            })
1852            .port(8080)
1853            .permissions("test".to_string())
1854            .commands_enabled(true)
1855            .build();
1856
1857        let json = serde_json::to_value(&container).expect("container should serialize");
1858        assert_eq!(json["commandsEnabled"], true);
1859
1860        let deserialized: Container =
1861            serde_json::from_value(json).expect("container should deserialize");
1862        assert_eq!(deserialized, container);
1863    }
1864}