use crate::error::{ErrorData, Result};
use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
use crate::resources::{
ComputeCluster, PublicEndpoint, PublicEndpointOutput, ToolchainConfig, APEX_HOST_LABEL,
};
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
use std::fmt::Debug;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum ContainerCode {
#[serde(rename_all = "camelCase")]
Image {
image: String,
},
#[serde(rename_all = "camelCase")]
Source {
src: String,
toolchain: ToolchainConfig,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ResourceSpec {
pub min: String,
pub desired: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ResourceChoiceRange {
pub min: String,
pub max: String,
pub default: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ContainerResourceChoices {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu: Option<ResourceChoiceRange>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memory: Option<ResourceChoiceRange>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContainerGpuSpec {
#[serde(rename = "type")]
pub gpu_type: String,
pub count: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct PersistentStorage {
pub size: String,
pub mount_path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub encryption_key: Option<ResourceRef>,
#[serde(default)]
pub backups: VolumeBackups,
}
pub const VOLUME_BACKUP_INTERVAL_HOURS: [u32; 7] = [1, 2, 4, 6, 8, 12, 24];
pub const VOLUME_BACKUP_MAX_SNAPSHOTS: u32 = 450;
pub const VOLUME_BACKUP_MAX_RETENTION_DAYS: u32 = 365;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct VolumeBackups {
#[serde(default = "default_volume_backups_enabled")]
pub enabled: bool,
#[serde(default = "default_volume_backup_interval_hours")]
pub interval_hours: u32,
#[serde(default = "default_volume_backup_retention_days")]
pub retention_days: u32,
}
fn default_volume_backups_enabled() -> bool {
true
}
fn default_volume_backup_interval_hours() -> u32 {
24
}
fn default_volume_backup_retention_days() -> u32 {
7
}
impl Default for VolumeBackups {
fn default() -> Self {
Self {
enabled: default_volume_backups_enabled(),
interval_hours: default_volume_backup_interval_hours(),
retention_days: default_volume_backup_retention_days(),
}
}
}
impl VolumeBackups {
pub fn disabled() -> Self {
Self {
enabled: false,
..Self::default()
}
}
pub fn validation_error(&self) -> Option<String> {
if !self.enabled {
return None;
}
if !VOLUME_BACKUP_INTERVAL_HOURS.contains(&self.interval_hours) {
return Some(format!(
"backup intervalHours must be one of {VOLUME_BACKUP_INTERVAL_HOURS:?}, got {}",
self.interval_hours
));
}
if self.retention_days == 0 {
return Some("backup retentionDays must be at least 1".to_string());
}
if self.retention_days > VOLUME_BACKUP_MAX_RETENTION_DAYS {
return Some(format!(
"backup retentionDays must be at most {VOLUME_BACKUP_MAX_RETENTION_DAYS}, got {}",
self.retention_days
));
}
let snapshots = self.retention_days * 24 / self.interval_hours;
if snapshots > VOLUME_BACKUP_MAX_SNAPSHOTS {
return Some(format!(
"backups every {} hours for {} days keep {snapshots} snapshots per volume; \
the most is {VOLUME_BACKUP_MAX_SNAPSHOTS}",
self.interval_hours, self.retention_days
));
}
None
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct KubernetesSecretMount {
pub secret_name: String,
pub mount_path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct KubernetesHttpProbe {
pub path: String,
pub port: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum WorkloadPriority {
Critical,
High,
Normal,
Low,
}
impl WorkloadPriority {
pub fn as_str(&self) -> &'static str {
match self {
Self::Critical => "critical",
Self::High => "high",
Self::Normal => "normal",
Self::Low => "low",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum ContainerSecurityProfile {
Restricted,
Unrestricted,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(
rename_all = "camelCase",
from = "ContainerSecurityWire",
into = "ContainerSecurityWire"
)]
pub struct ContainerSecurity {
pub profile: ContainerSecurityProfile,
pub run_as_user: Option<i64>,
pub run_as_group: Option<i64>,
pub read_only_root_filesystem: Option<bool>,
#[serde(default)]
pub writable_paths: Vec<String>,
}
const PREVIOUS_RELEASE_ID: i64 = 65532;
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ContainerSecurityWire {
profile: ContainerSecurityProfile,
#[serde(default)]
run_as_user: Option<i64>,
#[serde(default)]
run_as_group: Option<i64>,
#[serde(default)]
read_only_root_filesystem: Option<bool>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
unrestricted: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
run_as_user_unset: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
run_as_group_unset: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
read_only_root_filesystem_unset: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
writable_paths: Vec<String>,
}
impl From<ContainerSecurity> for ContainerSecurityWire {
fn from(security: ContainerSecurity) -> Self {
let unrestricted = security.profile == ContainerSecurityProfile::Unrestricted;
Self {
profile: ContainerSecurityProfile::Restricted,
unrestricted,
run_as_user_unset: security.run_as_user.is_none(),
run_as_user: Some(security.run_as_user.unwrap_or(PREVIOUS_RELEASE_ID)),
run_as_group_unset: security.run_as_group.is_none(),
run_as_group: Some(security.run_as_group.unwrap_or(PREVIOUS_RELEASE_ID)),
read_only_root_filesystem_unset: security.read_only_root_filesystem.is_none(),
read_only_root_filesystem: Some(
security.read_only_root_filesystem.unwrap_or(!unrestricted),
),
writable_paths: security.writable_paths,
}
}
}
impl From<ContainerSecurityWire> for ContainerSecurity {
fn from(wire: ContainerSecurityWire) -> Self {
let profile = if wire.unrestricted {
ContainerSecurityProfile::Unrestricted
} else {
wire.profile
};
Self {
profile,
run_as_user: wire.run_as_user.filter(|_| !wire.run_as_user_unset),
run_as_group: wire.run_as_group.filter(|_| !wire.run_as_group_unset),
read_only_root_filesystem: wire
.read_only_root_filesystem
.filter(|_| !wire.read_only_root_filesystem_unset),
writable_paths: wire.writable_paths,
}
}
}
impl ContainerSecurity {
pub fn is_restricted(security: Option<&ContainerSecurity>) -> bool {
security.is_some_and(|security| security.profile == ContainerSecurityProfile::Restricted)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContainerAutoscaling {
pub min: u32,
pub desired: u32,
pub max: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub target_cpu_percent: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target_memory_percent: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target_http_in_flight_per_replica: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_http_p95_latency_ms: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct HealthCheck {
#[serde(default = "default_health_path")]
pub path: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub port: Option<u16>,
#[serde(default = "default_health_method")]
pub method: String,
#[serde(default = "default_timeout_seconds")]
pub timeout_seconds: u32,
#[serde(default = "default_failure_threshold")]
pub failure_threshold: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub startup_timeout_seconds: Option<u32>,
}
impl Default for HealthCheck {
fn default() -> Self {
HealthCheck {
path: default_health_path(),
port: None,
method: default_health_method(),
timeout_seconds: default_timeout_seconds(),
failure_threshold: default_failure_threshold(),
startup_timeout_seconds: None,
}
}
}
fn default_health_path() -> String {
"/health".to_string()
}
fn default_health_method() -> String {
"GET".to_string()
}
fn default_timeout_seconds() -> u32 {
1
}
fn default_failure_threshold() -> u32 {
3
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContainerPort {
pub port: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum ContainerEgress {
Internet,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct Container {
#[builder(start_fn)]
pub id: String,
#[builder(field)]
pub links: Vec<ResourceRef>,
#[builder(field)]
pub ports: Vec<ContainerPort>,
#[builder(field)]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub kubernetes_secret_mounts: Vec<KubernetesSecretMount>,
#[builder(field)]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub public_endpoints: Vec<PublicEndpoint>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub egress: Option<ContainerEgress>,
#[serde(default, rename = "tunnel", skip_serializing)]
#[cfg_attr(feature = "openapi", schema(ignore))]
#[builder(skip)]
retired_tunnel: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kubernetes_liveness_probe: Option<KubernetesHttpProbe>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kubernetes_readiness_probe: Option<KubernetesHttpProbe>,
#[serde(skip_serializing_if = "Option::is_none")]
pub security: Option<ContainerSecurity>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cluster: Option<String>,
pub code: ContainerCode,
pub cpu: ResourceSpec,
pub memory: ResourceSpec,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource_choices: Option<ContainerResourceChoices>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gpu: Option<ContainerGpuSpec>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ephemeral_storage: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub persistent_storage: Option<PersistentStorage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub replicas: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub autoscaling: Option<ContainerAutoscaling>,
#[builder(default = false)]
#[serde(default)]
pub stateful: bool,
#[builder(default)]
#[serde(default)]
pub environment: HashMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pool: Option<String>,
pub permissions: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub health_check: Option<HealthCheck>,
#[serde(skip_serializing_if = "Option::is_none")]
pub command: Option<Vec<String>>,
#[builder(default = default_commands_enabled())]
#[serde(default = "default_commands_enabled")]
#[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
pub commands_enabled: bool,
#[builder(default)]
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub commands_capability_file: bool,
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
pub stop_grace_period_seconds: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<WorkloadPriority>,
}
impl Container {
pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("container");
pub fn id(&self) -> &str {
&self.id
}
pub fn get_permissions(&self) -> &str {
&self.permissions
}
pub fn is_stateless(&self) -> bool {
!self.stateful
}
pub fn validate_network_settings(&self) -> Result<()> {
let invalid = |reason: String| {
AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason,
})
};
if self.egress.is_some() && !ContainerSecurity::is_restricted(self.security.as_ref()) {
return Err(invalid(
"container egress internet requires security.profile restricted".into(),
));
}
Ok(())
}
fn validate_public_endpoints(&self) -> Result<()> {
let mut endpoint_names = std::collections::HashSet::new();
let mut backend_ports = std::collections::HashSet::new();
let mut apex_endpoint_name: Option<&str> = None;
for endpoint in &self.public_endpoints {
endpoint.validate_for_resource(&self.id)?;
if !endpoint_names.insert(endpoint.name.as_str()) {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: format!("duplicate public endpoint name '{}'", endpoint.name),
}));
}
if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
if let Some(existing_name) = apex_endpoint_name {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: format!(
"only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
existing_name
),
}));
}
apex_endpoint_name = Some(endpoint.name.as_str());
}
backend_ports.insert(endpoint.port);
if !self.ports.iter().any(|port| port.port == endpoint.port) {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: format!(
"public endpoint '{}' references undeclared port {}",
endpoint.name, endpoint.port
),
}));
}
}
if backend_ports.len() > 1 {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason:
"public endpoints on one container must currently route to the same backend port"
.to_string(),
}));
}
Ok(())
}
}
fn default_commands_enabled() -> bool {
false
}
impl<S: container_builder::State> ContainerBuilder<S> {
pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
where
for<'a> &'a R: Into<ResourceRef>,
{
let resource_ref: ResourceRef = resource.into();
self.links.push(resource_ref);
self
}
pub fn port(mut self, port: u16) -> Self {
self.ports.push(ContainerPort { port });
self
}
pub fn kubernetes_secret_mount(mut self, mount: KubernetesSecretMount) -> Self {
self.kubernetes_secret_mounts.push(mount);
self
}
pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
if !self.ports.iter().any(|p| p.port == endpoint.port) {
self.ports.push(ContainerPort {
port: endpoint.port,
});
}
self.public_endpoints.push(endpoint);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum ContainerStatus {
Pending,
Running,
Stopped,
Failing,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ReplicaStatus {
pub replica_id: String,
pub ordinal: Option<u32>,
pub machine_id: Option<String>,
pub healthy: bool,
pub container_ip: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ContainerOutputs {
pub name: String,
pub status: ContainerStatus,
pub current_replicas: u32,
pub desired_replicas: u32,
pub internal_dns: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub public_endpoints: HashMap<String, PublicEndpointOutput>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub internal_urls: HashMap<u16, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
pub link_address: Option<std::net::Ipv4Addr>,
pub replicas: Vec<ReplicaStatus>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub volumes: Vec<VolumeOutput>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub volume_backups: Option<VolumeBackupsStatus>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct VolumeBackupsStatus {
pub state: VolumeBackupsState,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum VolumeBackupsState {
Active,
Disabled,
SetupRequired,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct VolumeOutput {
pub ordinal: u32,
pub volume_id: String,
pub zone: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_snapshot_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_snapshot_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_restore: Option<VolumeRestoreOutput>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct VolumeRestoreOutput {
pub request_id: String,
pub snapshot_id: String,
pub replaced_volume_snapshot_id: String,
pub completed_at: String,
}
impl ResourceOutputsDefinition for ContainerOutputs {
fn get_resource_type(&self) -> ResourceType {
Container::RESOURCE_TYPE.clone()
}
fn as_any(&self) -> &dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
Box::new(self.clone())
}
fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
other.as_any().downcast_ref::<ContainerOutputs>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
impl ResourceDefinition for Container {
fn get_resource_type(&self) -> ResourceType {
Self::RESOURCE_TYPE
}
fn id(&self) -> &str {
&self.id
}
fn replace_after_failed_create_is_safe(&self) -> bool {
!(self.stateful && self.persistent_storage.is_some())
}
fn get_dependencies(&self) -> Vec<ResourceRef> {
let mut deps = self.links.clone();
if let Some(key) = self
.persistent_storage
.as_ref()
.and_then(|storage| storage.encryption_key.as_ref())
{
deps.push(key.clone());
}
if let Some(cluster) = &self.cluster {
deps.push(ResourceRef::new(
ComputeCluster::RESOURCE_TYPE.clone(),
cluster,
));
}
deps
}
fn get_permissions(&self) -> Option<&str> {
Some(&self.permissions)
}
fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
let new_container = new_config
.as_any()
.downcast_ref::<Container>()
.ok_or_else(|| {
AlienError::new(ErrorData::UnexpectedResourceType {
resource_id: self.id.clone(),
expected: Self::RESOURCE_TYPE,
actual: new_config.get_resource_type(),
})
})?;
new_container.validate_public_endpoints()?;
new_container.validate_network_settings()?;
if self.id != new_container.id {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'id' field is immutable".to_string(),
}));
}
if self.cluster != new_container.cluster {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'cluster' field is immutable".to_string(),
}));
}
if self.stateful != new_container.stateful {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'stateful' field is immutable".to_string(),
}));
}
let old_key = self
.persistent_storage
.as_ref()
.and_then(|storage| storage.encryption_key.as_ref());
let new_key = new_container
.persistent_storage
.as_ref()
.and_then(|storage| storage.encryption_key.as_ref());
if old_key != new_key {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'persistentStorage.encryptionKey' field is immutable once the resource exists".to_string(),
}));
}
if self.ports != new_container.ports {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'ports' field is immutable".to_string(),
}));
}
if self.public_endpoints != new_container.public_endpoints {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'publicEndpoints' field is immutable".to_string(),
}));
}
if self.pool != new_container.pool {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'pool' field is immutable".to_string(),
}));
}
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceDefinition> {
Box::new(self.clone())
}
fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
other.as_any().downcast_ref::<Container>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
#[cfg(test)]
mod tests {
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
enum PreviousProfile {
Restricted,
}
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct PreviousContainerSecurity {
profile: PreviousProfile,
run_as_user: i64,
run_as_group: i64,
read_only_root_filesystem: bool,
}
#[test]
fn written_security_parses_with_the_previous_release_struct() {
let defaults = ContainerSecurity {
profile: ContainerSecurityProfile::Restricted,
run_as_user: None,
run_as_group: None,
read_only_root_filesystem: None,
writable_paths: Vec::new(),
};
let explicit = ContainerSecurity {
profile: ContainerSecurityProfile::Unrestricted,
run_as_user: Some(70),
run_as_group: Some(71),
read_only_root_filesystem: Some(false),
writable_paths: vec!["/data".to_string()],
};
let unrestricted_defaults = ContainerSecurity {
profile: ContainerSecurityProfile::Unrestricted,
..defaults.clone()
};
let explicit_zero = ContainerSecurity {
profile: ContainerSecurityProfile::Restricted,
run_as_user: Some(0),
run_as_group: None,
read_only_root_filesystem: Some(false),
writable_paths: Vec::new(),
};
for security in [defaults, explicit, unrestricted_defaults, explicit_zero] {
let json = serde_json::to_value(&security).unwrap();
serde_json::from_value::<PreviousContainerSecurity>(json.clone())
.unwrap_or_else(|error| panic!("previous release cannot read {json}: {error}"));
let back: ContainerSecurity = serde_json::from_value(json).unwrap();
assert_eq!(back, security);
}
}
#[test]
fn unrestricted_opt_out_reads_as_restricted_with_the_previous_release_struct() {
let security = ContainerSecurity {
profile: ContainerSecurityProfile::Unrestricted,
run_as_user: Some(0),
run_as_group: Some(0),
read_only_root_filesystem: Some(false),
writable_paths: Vec::new(),
};
let json = serde_json::to_value(&security).unwrap();
assert_eq!(json["profile"], "restricted");
assert_eq!(json["unrestricted"], true);
let previous: PreviousContainerSecurity = serde_json::from_value(json.clone()).unwrap();
assert!(matches!(previous.profile, PreviousProfile::Restricted));
let back: ContainerSecurity = serde_json::from_value(json).unwrap();
assert_eq!(back, security);
}
#[test]
fn security_without_a_profile_fails_to_parse() {
assert!(
serde_json::from_str::<ContainerSecurity>(r#"{"writablePaths":["/cache"]}"#).is_err()
);
assert!(serde_json::from_str::<ContainerSecurity>("{}").is_err());
}
#[test]
fn security_reads_accept_the_plain_unrestricted_profile() {
let security: ContainerSecurity =
serde_json::from_str(r#"{"profile":"unrestricted"}"#).unwrap();
assert_eq!(security.profile, ContainerSecurityProfile::Unrestricted);
}
#[test]
fn security_reads_tolerate_omitted_fields() {
let security: ContainerSecurity =
serde_json::from_str(r#"{"profile":"restricted"}"#).unwrap();
assert_eq!(security.run_as_user, None);
assert_eq!(security.read_only_root_filesystem, None);
}
use super::*;
use crate::resources::ExposeProtocol;
fn network_container() -> Container {
Container::new("api".to_string())
.code(ContainerCode::Image {
image: "example:latest".into(),
})
.cpu(ResourceSpec {
min: "1".into(),
desired: "1".into(),
})
.memory(ResourceSpec {
min: "512Mi".into(),
desired: "512Mi".into(),
})
.permissions("execution".into())
.public_endpoint(PublicEndpoint {
name: "web".into(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: None,
wildcard_subdomains: false,
})
.build()
}
#[test]
fn a_saved_container_with_the_retired_tunnel_field_still_loads() {
let saved = serde_json::json!({
"id": "api",
"code": {"type": "image", "image": "example/api:1"},
"cpu": {"min": "0.5", "desired": "0.5"},
"memory": {"min": "256Mi", "desired": "256Mi"},
"permissions": "execution",
"links": [], "ports": [],
"tunnel": {"port": 8080}
});
let container: Container = serde_json::from_value(saved).expect("saved container loads");
assert!(serde_json::to_value(&container)
.unwrap()
.get("tunnel")
.is_none());
}
#[test]
fn internet_egress_is_opt_in_and_refuses_the_unrestricted_profile() {
let mut container = network_container();
assert!(serde_json::to_value(&container)
.unwrap()
.get("egress")
.is_none());
container.egress = Some(ContainerEgress::Internet);
assert!(container.validate_update(&container).is_err());
container.security = Some(ContainerSecurity {
profile: ContainerSecurityProfile::Unrestricted,
run_as_user: None,
run_as_group: None,
read_only_root_filesystem: None,
writable_paths: Vec::new(),
});
assert!(container.validate_update(&container).is_err());
container.security = Some(ContainerSecurity {
profile: ContainerSecurityProfile::Restricted,
run_as_user: Some(65532),
run_as_group: Some(65532),
read_only_root_filesystem: Some(true),
writable_paths: Vec::new(),
});
container.validate_update(&container).unwrap();
assert_eq!(
serde_json::to_value(&container).unwrap()["egress"],
"internet"
);
}
#[test]
fn test_container_creation_with_autoscaling() {
let container = Container::new("api".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "myapp:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.public_endpoint(PublicEndpoint {
name: "api".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: None,
wildcard_subdomains: false,
})
.autoscaling(ContainerAutoscaling {
min: 2,
desired: 3,
max: 10,
target_cpu_percent: Some(70.0),
target_memory_percent: None,
target_http_in_flight_per_replica: Some(100),
max_http_p95_latency_ms: None,
})
.permissions("container-execution".to_string())
.build();
assert_eq!(container.id(), "api");
assert_eq!(container.cluster, Some("compute".to_string()));
assert!(!container.stateful);
assert!(container.autoscaling.is_some());
assert_eq!(container.ports.len(), 1);
assert_eq!(container.ports[0].port, 8080);
}
#[test]
fn container_serializes_stop_grace_period_when_set() {
let container = Container::new("api".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "myapp:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.permissions("container-execution".to_string())
.stop_grace_period_seconds(21_600)
.build();
let json = serde_json::to_value(&container).expect("container should serialize");
assert_eq!(json["stopGracePeriodSeconds"], 21_600);
}
#[test]
fn container_omits_stop_grace_period_when_absent() {
let container = Container::new("api".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "myapp:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.permissions("container-execution".to_string())
.build();
let json = serde_json::to_value(&container).expect("container should serialize");
assert!(json.get("stopGracePeriodSeconds").is_none());
}
#[test]
fn test_stateful_container_with_storage() {
let container = Container::new("postgres".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "postgres:16".to_string(),
})
.cpu(ResourceSpec {
min: "1".to_string(),
desired: "2".to_string(),
})
.memory(ResourceSpec {
min: "2Gi".to_string(),
desired: "4Gi".to_string(),
})
.port(5432)
.stateful(true)
.replicas(1)
.persistent_storage(PersistentStorage {
encryption_key: None,
size: "100Gi".to_string(),
mount_path: "/var/lib/postgresql/data".to_string(),
backups: VolumeBackups::default(),
})
.permissions("database".to_string())
.build();
assert_eq!(container.id(), "postgres");
assert!(container.stateful);
assert!(container.replicas.is_some());
assert!(container.persistent_storage.is_some());
}
#[test]
fn test_public_container() {
let container = Container::new("frontend".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "frontend:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.25".to_string(),
desired: "0.5".to_string(),
})
.memory(ResourceSpec {
min: "256Mi".to_string(),
desired: "512Mi".to_string(),
})
.port(3000)
.public_endpoint(PublicEndpoint {
name: "web".to_string(),
port: 3000,
protocol: ExposeProtocol::Http,
host_label: None,
wildcard_subdomains: false,
})
.autoscaling(ContainerAutoscaling {
min: 2,
desired: 2,
max: 20,
target_cpu_percent: None,
target_memory_percent: None,
target_http_in_flight_per_replica: Some(50),
max_http_p95_latency_ms: Some(100.0),
})
.health_check(HealthCheck {
path: "/health".to_string(),
port: None,
method: "GET".to_string(),
timeout_seconds: 1,
failure_threshold: 3,
startup_timeout_seconds: None,
})
.permissions("frontend".to_string())
.build();
assert_eq!(container.ports[0].port, 3000);
assert_eq!(container.public_endpoints[0].name, "web");
assert!(container.health_check.is_some());
}
#[test]
fn test_public_container_endpoint_options() {
let container = Container::new("router".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "router:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.25".to_string(),
desired: "0.5".to_string(),
})
.memory(ResourceSpec {
min: "256Mi".to_string(),
desired: "512Mi".to_string(),
})
.public_endpoint(PublicEndpoint {
name: "gateway".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: Some("gateway".to_string()),
wildcard_subdomains: true,
})
.permissions("router".to_string())
.build();
assert!(container.validate_public_endpoints().is_ok());
assert_eq!(container.ports.len(), 1);
assert_eq!(container.public_endpoints.len(), 1);
assert_eq!(
container.public_endpoints[0].host_label.as_deref(),
Some("gateway")
);
assert!(container.public_endpoints[0].wildcard_subdomains);
}
#[test]
fn test_public_container_rejects_invalid_host_label() {
let container = Container::new("router".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "router:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.25".to_string(),
desired: "0.5".to_string(),
})
.memory(ResourceSpec {
min: "256Mi".to_string(),
desired: "512Mi".to_string(),
})
.public_endpoint(PublicEndpoint {
name: "gateway".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: Some("bad.label".to_string()),
wildcard_subdomains: true,
})
.permissions("router".to_string())
.build();
assert!(container.validate_public_endpoints().is_err());
}
#[test]
fn test_container_with_links() {
use crate::Storage;
let storage = Storage::new("data".to_string()).build();
let container = Container::new("worker".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "worker:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.replicas(3)
.link(&storage)
.permissions("worker".to_string())
.build();
let deps = container.get_dependencies();
assert_eq!(deps.len(), 2);
}
#[test]
fn test_container_validate_update_immutable_cluster() {
let container1 = Container::new("api".to_string())
.cluster("cluster-1".to_string())
.code(ContainerCode::Image {
image: "myapp:v1".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.replicas(2)
.permissions("execution".to_string())
.build();
let container2 = Container::new("api".to_string())
.cluster("cluster-2".to_string()) .code(ContainerCode::Image {
image: "myapp:v2".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.replicas(2)
.permissions("execution".to_string())
.build();
let result = container1.validate_update(&container2);
assert!(result.is_err());
}
#[test]
fn test_container_validate_update_allowed_changes() {
let container1 = Container::new("api".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "myapp:v1".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.replicas(2)
.permissions("execution".to_string())
.build();
let container2 = Container::new("api".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "myapp:v2".to_string(), })
.cpu(ResourceSpec {
min: "1".to_string(), desired: "2".to_string(),
})
.memory(ResourceSpec {
min: "1Gi".to_string(),
desired: "2Gi".to_string(),
})
.port(8080)
.replicas(5) .permissions("execution".to_string())
.build();
let result = container1.validate_update(&container2);
assert!(result.is_ok());
}
#[test]
fn test_container_serialization() {
let container = Container::new("test".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.replicas(1)
.permissions("test".to_string())
.build();
let json = serde_json::to_string(&container).unwrap();
let deserialized: Container = serde_json::from_str(&json).unwrap();
assert_eq!(container, deserialized);
}
#[test]
fn test_container_multi_endpoint_validation() {
let container = Container::new("multi-tcp".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "1".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "1Gi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.public_endpoint(PublicEndpoint {
name: "api".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: None,
wildcard_subdomains: false,
})
.public_endpoint(PublicEndpoint {
name: "wildcard".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: Some("wildcard".to_string()),
wildcard_subdomains: true,
})
.replicas(1)
.permissions("test".to_string())
.build();
assert!(container.validate_public_endpoints().is_ok());
let invalid_container = Container::new("multi-http".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "1".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "1Gi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.port(9090)
.public_endpoint(PublicEndpoint {
name: "api".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: None,
wildcard_subdomains: false,
})
.public_endpoint(PublicEndpoint {
name: "admin".to_string(),
port: 9090,
protocol: ExposeProtocol::Http,
host_label: None,
wildcard_subdomains: false,
})
.replicas(1)
.permissions("test".to_string())
.build();
assert!(invalid_container.validate_public_endpoints().is_err());
}
#[test]
fn container_rejects_multiple_apex_public_endpoints() {
let container = Container::new("apex-container".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "1".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "1Gi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.public_endpoint(PublicEndpoint {
name: "web".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: Some(APEX_HOST_LABEL.to_string()),
wildcard_subdomains: false,
})
.public_endpoint(PublicEndpoint {
name: "admin".to_string(),
port: 8080,
protocol: ExposeProtocol::Http,
host_label: Some(APEX_HOST_LABEL.to_string()),
wildcard_subdomains: false,
})
.replicas(1)
.permissions("test".to_string())
.build();
assert!(container.validate_public_endpoints().is_err());
}
#[test]
fn test_container_empty_ports_validation() {
let container = Container::new("no-ports".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "1".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "1Gi".to_string(),
desired: "1Gi".to_string(),
})
.replicas(1)
.permissions("test".to_string())
.build();
assert!(container.validate_public_endpoints().is_ok());
}
#[test]
fn test_container_commands_enabled_defaults_false() {
let container = Container::new("no-commands".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.permissions("test".to_string())
.build();
assert!(!container.commands_enabled);
}
#[test]
fn test_container_commands_enabled_builder() {
let container = Container::new("cmd-container".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.permissions("test".to_string())
.commands_enabled(true)
.build();
assert!(container.commands_enabled);
}
#[test]
fn test_container_commands_enabled_serializes_camel_case() {
let container = Container::new("cmd-container".to_string())
.cluster("compute".to_string())
.code(ContainerCode::Image {
image: "test:latest".to_string(),
})
.cpu(ResourceSpec {
min: "0.5".to_string(),
desired: "1".to_string(),
})
.memory(ResourceSpec {
min: "512Mi".to_string(),
desired: "1Gi".to_string(),
})
.port(8080)
.permissions("test".to_string())
.commands_enabled(true)
.build();
let json = serde_json::to_value(&container).expect("container should serialize");
assert_eq!(json["commandsEnabled"], true);
let deserialized: Container =
serde_json::from_value(json).expect("container should deserialize");
assert_eq!(deserialized, container);
}
}