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