Skip to main content

alien_core/
stack_settings.rs

1//!
2//! Defines stack-level settings and management configurations for different cloud platforms.
3//! These settings customize deployment behavior and cross-account/cross-tenant access patterns.
4
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7
8use crate::{KubernetesCloudReference, KubernetesClusterOwnership};
9
10/// AWS management configuration extracted from stack settings
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
13#[serde(rename_all = "camelCase")]
14pub struct AwsManagementConfig {
15    /// The managing AWS IAM role ARN that can assume cross-account roles
16    pub managing_role_arn: String,
17}
18
19/// GCP management configuration extracted from stack settings
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
21#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
22#[serde(rename_all = "camelCase")]
23pub struct GcpManagementConfig {
24    /// Service account email for management roles
25    pub service_account_email: String,
26}
27
28/// Azure management configuration extracted from stack settings
29#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
30#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
31#[serde(rename_all = "camelCase")]
32pub struct AzureManagementConfig {
33    /// The managing Azure Tenant ID for cross-tenant access
34    pub managing_tenant_id: String,
35    /// OIDC issuer URL trusted by the target-side managed identity.
36    pub oidc_issuer: String,
37    /// OIDC subject claim trusted by the target-side managed identity.
38    pub oidc_subject: String,
39}
40
41/// Management configuration for different cloud platforms.
42///
43/// Platform-derived configuration for cross-account/cross-tenant access.
44/// This is NOT user-specified - it's derived from the Manager's ServiceAccount.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
47#[serde(rename_all = "camelCase", tag = "platform")]
48pub enum ManagementConfig {
49    /// AWS management configuration
50    Aws(AwsManagementConfig),
51    /// GCP management configuration  
52    Gcp(GcpManagementConfig),
53    /// Azure management configuration
54    Azure(AzureManagementConfig),
55    /// Kubernetes management configuration (minimal for now)
56    Kubernetes,
57}
58
59/// Network configuration for the stack.
60///
61/// Controls how VPC/VNet networking is provisioned. Users configure this in
62/// `StackSettings`; the Network resource itself is auto-generated by preflights.
63///
64/// ## Egress policy
65///
66/// Container cluster VMs are configured for egress based on the mode:
67///
68/// - `UseDefault` → VMs get ephemeral public IPs (no NAT is provisioned)
69/// - `Create` → VMs use private IPs; Alien provisions a NAT gateway for outbound access
70/// - `ByoVpc*` / `ByoVnet*` → no public IPs assigned; customer manages egress
71///
72/// For production workloads, use `Create`. For fast dev/test iteration, `UseDefault` is
73/// sufficient. For environments with existing VPCs, use the appropriate `ByoVpc*` variant.
74#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
75#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
76#[serde(rename_all = "camelCase", tag = "type")]
77pub enum NetworkSettings {
78    /// Use the cloud provider's default VPC/network.
79    ///
80    /// Designed for fast dev/test provisioning. No isolated VPC is created, so there
81    /// is nothing to wait for or clean up. VMs receive ephemeral public IPs for internet
82    /// access — no NAT gateway is provisioned.
83    ///
84    /// - **AWS**: Discovers the account's default VPC. Subnets are public with auto-assigned IPs.
85    /// - **GCP**: Discovers the project's `default` network and regional subnet. Instance
86    ///   templates include an `AccessConfig` to assign an ephemeral external IP.
87    /// - **Azure**: Azure has no default VNet, so one is created along with a NAT Gateway.
88    ///   VMs stay private and use NAT for egress.
89    ///
90    /// Not recommended for production. Use `Create` instead.
91    #[serde(rename = "use-default")]
92    UseDefault,
93
94    /// Create a new isolated VPC/VNet with a managed NAT gateway.
95    ///
96    /// All networking infrastructure is provisioned by Alien and cleaned up on delete.
97    /// VMs use private IPs only; all outbound traffic routes through the NAT gateway.
98    ///
99    /// Recommended for production deployments.
100    #[serde(rename = "create")]
101    Create {
102        /// VPC/VNet CIDR block. If not specified, auto-generated from stack ID
103        /// to reduce conflicts (e.g., "10.{hash}.0.0/16").
104        #[serde(skip_serializing_if = "Option::is_none")]
105        cidr: Option<String>,
106
107        /// Number of availability zones (default: 2).
108        #[serde(default = "default_availability_zones")]
109        availability_zones: u8,
110    },
111
112    /// Use an existing VPC (AWS).
113    ///
114    /// Alien validates the references but creates no networking infrastructure.
115    /// The customer is responsible for routing and egress (NAT, proxy, VPN, etc.).
116    #[serde(rename = "byo-vpc-aws")]
117    ByoVpcAws {
118        /// The ID of the existing VPC
119        vpc_id: String,
120        /// IDs of public subnets (required for public ingress)
121        public_subnet_ids: Vec<String>,
122        /// IDs of private subnets
123        private_subnet_ids: Vec<String>,
124        /// Optional security group IDs to use
125        #[serde(default)]
126        security_group_ids: Vec<String>,
127    },
128
129    /// Use an existing VPC (GCP).
130    ///
131    /// Alien validates the references but creates no networking infrastructure.
132    /// The customer is responsible for routing and egress (Cloud NAT, proxy, VPN, etc.).
133    #[serde(rename = "byo-vpc-gcp")]
134    ByoVpcGcp {
135        /// The name of the existing VPC network
136        network_name: String,
137        /// The name of the subnet to use
138        subnet_name: String,
139        /// The region of the subnet
140        region: String,
141    },
142
143    /// Use an existing VNet (Azure).
144    ///
145    /// Alien validates the references but creates no networking infrastructure.
146    /// The customer is responsible for routing and egress (NAT Gateway, proxy, VPN, etc.).
147    #[serde(rename = "byo-vnet-azure")]
148    ByoVnetAzure {
149        /// The full resource ID of the existing VNet
150        vnet_resource_id: String,
151        /// Name of the public subnet within the VNet
152        public_subnet_name: String,
153        /// Name of the private subnet within the VNet
154        private_subnet_name: String,
155        /// Name of the dedicated classic Application Gateway subnet within the VNet.
156        #[serde(default, skip_serializing_if = "Option::is_none")]
157        application_gateway_subnet_name: Option<String>,
158        /// Name of the dedicated subnet that hosts Private Endpoints (e.g. for a
159        /// Postgres Flexible Server). A Private Endpoint must not share the private
160        /// subnet, which is already claimed by the Container Apps environment's
161        /// `infrastructure_subnet_id`. Required only when the stack contains a
162        /// Postgres resource; otherwise unused.
163        #[serde(default, skip_serializing_if = "Option::is_none")]
164        private_endpoint_subnet_name: Option<String>,
165    },
166}
167
168fn default_availability_zones() -> u8 {
169    2
170}
171
172/// Deployment-time compute choices for Alien-managed compute pools.
173///
174/// Application source declares portable pool requirements. This settings
175/// object stores the concrete choices made for one deployment, such as the
176/// provider machine type and selected machine counts.
177#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
178#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
179#[serde(rename_all = "camelCase")]
180pub struct ComputeSettings {
181    /// Selected compute choices keyed by pool ID.
182    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
183    pub pools: HashMap<String, ComputePoolSelection>,
184}
185
186/// Failure-domain policy selected for a compute pool.
187#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
188#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
189#[serde(rename_all = "camelCase")]
190pub struct FailureDomainSelection {
191    /// Number of distinct failure domains across which new stateful replicas may be spread.
192    pub spread: u8,
193    /// Concrete provider domains selected during setup.
194    /// Empty delegates deterministic selection to the provider setup implementation.
195    #[serde(default, skip_serializing_if = "Vec::is_empty")]
196    pub selected_failure_domains: Vec<String>,
197}
198
199/// User-selected deployment settings for one compute pool.
200#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
201#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
202#[serde(rename_all = "camelCase", tag = "mode")]
203pub enum ComputePoolSelection {
204    /// Fixed number of machines.
205    Fixed {
206        /// Number of machines to run.
207        machines: u32,
208        /// Provider machine type selected for this deployment.
209        #[serde(default, skip_serializing_if = "Option::is_none")]
210        machine: Option<String>,
211        /// Optional failure-domain policy. Absence preserves the existing aggregate layout.
212        #[serde(default, skip_serializing_if = "Option::is_none")]
213        failure_domains: Option<FailureDomainSelection>,
214    },
215    /// Autoscaling machine pool.
216    Autoscale {
217        /// Minimum machine count.
218        min: u32,
219        /// Maximum machine count.
220        max: u32,
221        /// Provider machine type selected for this deployment.
222        #[serde(default, skip_serializing_if = "Option::is_none")]
223        machine: Option<String>,
224        /// Optional failure-domain policy. Absence preserves the existing aggregate layout.
225        #[serde(default, skip_serializing_if = "Option::is_none")]
226        failure_domains: Option<FailureDomainSelection>,
227    },
228}
229
230impl ComputePoolSelection {
231    /// Selected provider machine type, when this platform needs one.
232    pub fn machine(&self) -> Option<&str> {
233        match self {
234            Self::Fixed { machine, .. } | Self::Autoscale { machine, .. } => machine.as_deref(),
235        }
236    }
237
238    /// Selected failure-domain policy, if this deployment explicitly adopted one.
239    pub fn failure_domains(&self) -> Option<&FailureDomainSelection> {
240        match self {
241            Self::Fixed {
242                failure_domains, ..
243            }
244            | Self::Autoscale {
245                failure_domains, ..
246            } => failure_domains.as_ref(),
247        }
248    }
249
250    /// Selected minimum machine count.
251    pub fn min_size(&self) -> u32 {
252        match self {
253            Self::Fixed { machines, .. } => *machines,
254            Self::Autoscale { min, .. } => *min,
255        }
256    }
257
258    /// Selected maximum machine count.
259    pub fn max_size(&self) -> u32 {
260        match self {
261            Self::Fixed { machines, .. } => *machines,
262            Self::Autoscale { max, .. } => *max,
263        }
264    }
265
266    /// Whether the selection has internally valid scale bounds.
267    pub fn validate(&self) -> std::result::Result<(), String> {
268        if self
269            .failure_domains()
270            .is_some_and(|selection| selection.spread == 0)
271        {
272            return Err("failure-domain spread must be at least one".to_string());
273        }
274        if self.failure_domains().is_some_and(|selection| {
275            !selection.selected_failure_domains.is_empty()
276                && selection.selected_failure_domains.len() != usize::from(selection.spread)
277        }) {
278            return Err("selected failure domains must match the requested spread".to_string());
279        }
280        if self.failure_domains().is_some_and(|selection| {
281            selection.selected_failure_domains.len()
282                != selection
283                    .selected_failure_domains
284                    .iter()
285                    .collect::<std::collections::HashSet<_>>()
286                    .len()
287        }) {
288            return Err("selected failure domains must be unique".to_string());
289        }
290        match self {
291            Self::Fixed { machines, .. } => {
292                if *machines == 0 {
293                    return Err("fixed compute pools must select at least one machine".to_string());
294                }
295                if let Some(failure_domains) = self.failure_domains() {
296                    if *machines < u32::from(failure_domains.spread) {
297                        return Err(format!(
298                            "fixed compute pool machines ({machines}) must be at least failure-domain spread ({})",
299                            failure_domains.spread
300                        ));
301                    }
302                }
303            }
304            Self::Autoscale { min, max, .. } => {
305                if min > max {
306                    return Err(format!(
307                        "autoscaling compute pool minimum ({min}) cannot exceed maximum ({max})"
308                    ));
309                }
310                if let Some(failure_domains) = self.failure_domains() {
311                    let spread = u32::from(failure_domains.spread);
312                    if *max < spread {
313                        return Err(format!(
314                            "autoscaling compute pool maximum ({max}) must be at least failure-domain spread ({spread})"
315                        ));
316                    }
317                    if *min < spread {
318                        return Err(format!(
319                            "autoscaling compute pool minimum ({min}) must be at least failure-domain spread ({spread})"
320                        ));
321                    }
322                }
323            }
324        }
325        Ok(())
326    }
327}
328
329/// Deployment model: how updates are delivered to the remote environment.
330#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
331#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
332#[serde(rename_all = "camelCase")]
333pub enum DeploymentModel {
334    /// Manager pushes updates via cross-account access.
335    /// Available for AWS, GCP, Azure only.
336    #[default]
337    Push,
338    /// Agent in remote environment pulls updates.
339    /// Available for all platforms (AWS, GCP, Azure, Kubernetes, Local).
340    Pull,
341}
342
343/// How updates are delivered to the deployment.
344#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
345#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
346#[serde(rename_all = "kebab-case")]
347pub enum UpdatesMode {
348    /// Updates deploy automatically (default).
349    #[default]
350    Auto,
351    /// Updates require explicit approval before deployment.
352    ApprovalRequired,
353}
354
355/// How telemetry (logs, metrics, traces) is handled.
356#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
357#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
358#[serde(rename_all = "kebab-case")]
359pub enum TelemetryMode {
360    /// No telemetry permissions. Data will not be collected.
361    Off,
362    /// Telemetry flows automatically (default).
363    #[default]
364    Auto,
365    /// Telemetry requires explicit approval before collection begins.
366    ApprovalRequired,
367}
368
369impl TelemetryMode {
370    /// Returns true if telemetry is enabled (Auto or ApprovalRequired).
371    pub fn is_enabled(&self) -> bool {
372        !matches!(self, TelemetryMode::Off)
373    }
374}
375
376/// How heartbeat health checks are handled.
377#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
378#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
379#[serde(rename_all = "kebab-case")]
380pub enum HeartbeatsMode {
381    /// No heartbeat permissions. Health checks disabled.
382    Off,
383    /// Heartbeat enabled (default).
384    #[default]
385    On,
386}
387
388impl HeartbeatsMode {
389    /// Returns true if heartbeat is enabled.
390    pub fn is_enabled(&self) -> bool {
391        matches!(self, HeartbeatsMode::On)
392    }
393}
394
395/// Domain configuration for the stack.
396///
397/// When `custom_domains` is set, the specified resources use customer-provided
398/// domains and certificates. Otherwise, Alien auto-generates domains.
399#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
400#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
401#[serde(rename_all = "camelCase")]
402pub struct DomainSettings {
403    /// Custom domain configuration per resource ID.
404    #[serde(default, skip_serializing_if = "Option::is_none")]
405    pub custom_domains: Option<HashMap<String, CustomDomainConfig>>,
406    /// Public endpoint DNS target selection for machines deployments.
407    ///
408    /// When omitted, machines deployments publish healthy machine public
409    /// addresses directly. Use `LoadBalancer` when an external load balancer
410    /// fronts the machines and Alien should publish a CNAME to that target.
411    #[serde(default, skip_serializing_if = "Option::is_none")]
412    pub public_endpoint_target: Option<PublicEndpointTargetSettings>,
413}
414
415/// DNS target mode for public endpoints.
416#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
417#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
418#[serde(rename_all = "camelCase", tag = "mode")]
419pub enum PublicEndpointTargetSettings {
420    /// Publish DNS records directly to healthy machine public IP addresses.
421    MachineAddresses,
422    /// Publish a CNAME record to an external load balancer.
423    #[serde(rename_all = "camelCase")]
424    LoadBalancer {
425        /// DNS name or URL for the external load balancer.
426        cname_target: String,
427    },
428}
429
430/// Custom domain configuration for a single resource.
431#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
432#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
433#[serde(rename_all = "camelCase")]
434pub struct CustomDomainConfig {
435    /// Fully qualified domain name to use.
436    pub domain: String,
437    /// Customer-provided certificate reference.
438    pub certificate: CustomCertificateConfig,
439}
440
441/// Platform-specific certificate references for custom domains.
442#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
443#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
444#[serde(rename_all = "camelCase")]
445pub struct CustomCertificateConfig {
446    /// AWS ACM certificate ARN
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub aws: Option<AwsCustomCertificateConfig>,
449    /// GCP Certificate Manager certificate name
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub gcp: Option<GcpCustomCertificateConfig>,
452    /// Azure Key Vault certificate ID
453    #[serde(default, skip_serializing_if = "Option::is_none")]
454    pub azure: Option<AzureCustomCertificateConfig>,
455    /// Kubernetes TLS Secret reference for Secret-backed route profiles.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub kubernetes: Option<KubernetesCustomCertificateConfig>,
458}
459
460#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
461#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
462#[serde(rename_all = "camelCase")]
463pub struct AwsCustomCertificateConfig {
464    pub certificate_arn: String,
465}
466
467#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
468#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
469#[serde(rename_all = "camelCase")]
470pub struct GcpCustomCertificateConfig {
471    pub certificate_name: String,
472}
473
474#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
475#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
476#[serde(rename_all = "camelCase")]
477pub struct AzureCustomCertificateConfig {
478    pub key_vault_certificate_id: String,
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub key_vault_resource_id: Option<String>,
481}
482
483#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
484#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
485#[serde(rename_all = "camelCase")]
486pub struct KubernetesCustomCertificateConfig {
487    /// Existing TLS Secret containing `tls.crt` and `tls.key`.
488    pub tls_secret_ref: KubernetesTlsSecretRef,
489}
490
491/// Kubernetes runtime substrate configuration.
492///
493/// This controls how setup chooses the cluster backing `Platform::Kubernetes`
494/// deployments. When omitted, cloud-backed Kubernetes deployments default to a
495/// managed cluster and generic/on-prem Kubernetes defaults to an external
496/// cluster.
497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
498#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
499#[serde(rename_all = "camelCase")]
500pub struct KubernetesSettings {
501    /// Cluster selection or creation settings.
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub cluster: Option<KubernetesClusterSettings>,
504    /// Public HTTPS exposure contract shared by setup, Helm, and runtime.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub exposure: Option<KubernetesExposureSettings>,
507}
508
509/// Kubernetes cluster setup settings.
510#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
511#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
512#[serde(rename_all = "camelCase")]
513pub struct KubernetesClusterSettings {
514    /// Whether Alien should create the cluster, use a setup-owned existing
515    /// cluster, or bind to an external/on-prem cluster.
516    pub ownership: KubernetesClusterOwnership,
517    /// Namespace where the Alien chart and application resources run.
518    #[serde(default, skip_serializing_if = "Option::is_none")]
519    pub namespace: Option<String>,
520    /// Optional provider-specific cloud identity for existing clusters.
521    #[serde(default, skip_serializing_if = "Option::is_none")]
522    pub cloud: Option<KubernetesCloudReference>,
523}
524
525/// Kubernetes public HTTPS exposure mode.
526#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
527#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
528#[serde(rename_all = "camelCase", tag = "mode")]
529pub enum KubernetesExposureSettings {
530    /// Do not create Alien-managed external routing.
531    Disabled,
532    /// Use Alien-generated DNS and Platform-managed certificate material.
533    Generated {
534        /// Runtime route profile to materialize.
535        route: KubernetesRouteProfile,
536        /// How managed certificate material reaches the route profile.
537        certificate: KubernetesCertificateMode,
538    },
539    /// Use a customer hostname and customer-owned certificate reference.
540    Custom {
541        /// Hostname routed by the Kubernetes public endpoint.
542        domain: String,
543        /// Runtime route profile to materialize.
544        route: KubernetesRouteProfile,
545        /// Customer-owned certificate reference consumed by the route profile.
546        certificate: KubernetesCertificateMode,
547    },
548}
549
550/// Kubernetes route API selected for public endpoints.
551#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
552#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
553#[serde(rename_all = "camelCase", tag = "routeApi")]
554pub enum KubernetesRouteProfile {
555    /// `networking.k8s.io/v1` Ingress route profile.
556    Ingress(KubernetesIngressRouteProfile),
557    /// Gateway API `Gateway` + `HTTPRoute` route profile.
558    Gateway(KubernetesGatewayRouteProfile),
559}
560
561/// Shared Ingress route profile values.
562#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
563#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
564#[serde(rename_all = "camelCase")]
565pub struct KubernetesIngressRouteProfile {
566    /// Route controller identifier, for example `eks.amazonaws.com/alb`.
567    #[serde(default, skip_serializing_if = "Option::is_none")]
568    pub controller: Option<String>,
569    /// `spec.ingressClassName` for generated Ingresses.
570    pub ingress_class_name: String,
571    /// Labels applied to route objects.
572    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
573    pub labels: HashMap<String, String>,
574    /// Annotations applied to route objects.
575    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
576    pub annotations: HashMap<String, String>,
577    /// Provider-specific route options that are required by the selected class.
578    #[serde(default, skip_serializing_if = "Option::is_none")]
579    pub provider: Option<KubernetesRouteProviderOptions>,
580}
581
582/// Shared Gateway API route profile values.
583#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
584#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
585#[serde(rename_all = "camelCase")]
586pub struct KubernetesGatewayRouteProfile {
587    /// Route controller identifier, for example a cloud Gateway controller.
588    #[serde(default, skip_serializing_if = "Option::is_none")]
589    pub controller: Option<String>,
590    /// GatewayClass selected for generated Gateways.
591    pub gateway_class_name: String,
592    /// Listener port, usually 443.
593    pub listener_port: u16,
594    /// Labels applied to route objects.
595    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
596    pub labels: HashMap<String, String>,
597    /// Annotations applied to route objects.
598    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
599    pub annotations: HashMap<String, String>,
600    /// Provider-specific route options that are required by the selected class.
601    #[serde(default, skip_serializing_if = "Option::is_none")]
602    pub provider: Option<KubernetesRouteProviderOptions>,
603}
604
605/// Provider-specific route options required by supported managed profiles.
606#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
607#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
608#[serde(rename_all = "camelCase", tag = "provider")]
609pub enum KubernetesRouteProviderOptions {
610    /// AWS ALB route options for EKS.
611    #[serde(rename_all = "camelCase")]
612    AwsAlb {
613        /// Internet-facing or internal ALB scheme.
614        scheme: String,
615        /// ALB target type, usually `ip`.
616        target_type: String,
617        /// Optional ALB IP address type, such as `dualstack`.
618        #[serde(default, skip_serializing_if = "Option::is_none")]
619        ip_address_type: Option<String>,
620        /// Explicit subnet IDs when the profile cannot rely on controller discovery.
621        #[serde(default, skip_serializing_if = "Vec::is_empty")]
622        subnet_ids: Vec<String>,
623    },
624    /// GKE Gateway route options.
625    #[serde(rename_all = "camelCase")]
626    GkeGateway {
627        /// Optional static address name for the Gateway frontend.
628        #[serde(default, skip_serializing_if = "Option::is_none")]
629        static_address_name: Option<String>,
630    },
631    /// Azure Application Gateway for Containers route options.
632    #[serde(rename_all = "camelCase")]
633    AzureApplicationGatewayForContainers {
634        /// Optional ALB namespace when using BYO Application Gateway resources.
635        #[serde(default, skip_serializing_if = "Option::is_none")]
636        alb_namespace: Option<String>,
637        /// Optional ALB name when using BYO Application Gateway resources.
638        #[serde(default, skip_serializing_if = "Option::is_none")]
639        alb_name: Option<String>,
640        /// Public or internal frontend exposure.
641        frontend: String,
642    },
643}
644
645/// Certificate publication or reference mode for Kubernetes public endpoints.
646#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
647#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
648#[serde(rename_all = "camelCase", tag = "mode")]
649pub enum KubernetesCertificateMode {
650    /// Platform-managed cert imported into AWS ACM by the runtime.
651    #[serde(rename_all = "camelCase")]
652    ManagedAcmImport {
653        /// ACM region. Defaults to the deployment region when omitted.
654        #[serde(default, skip_serializing_if = "Option::is_none")]
655        region: Option<String>,
656        /// Tags applied to runtime-imported ACM certificates.
657        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
658        tags: HashMap<String, String>,
659    },
660    /// Customer-provided AWS ACM certificate ARN.
661    #[serde(rename_all = "camelCase")]
662    AwsAcmArn {
663        /// Existing ACM certificate ARN.
664        certificate_arn: String,
665    },
666    /// Platform-managed cert written to a Kubernetes TLS Secret.
667    #[serde(rename_all = "camelCase")]
668    ManagedTlsSecret {
669        /// Secret name template. Runtime may substitute resource/deployment tokens.
670        secret_name_template: String,
671    },
672    /// Customer-provided Kubernetes TLS Secret.
673    TlsSecretRef(KubernetesTlsSecretRef),
674    /// No TLS certificate should be configured by Alien.
675    None,
676}
677
678/// Namespace-scoped Kubernetes TLS Secret reference.
679#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
680#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
681#[serde(rename_all = "camelCase")]
682pub struct KubernetesTlsSecretRef {
683    /// Secret name.
684    pub secret_name: String,
685    /// Secret namespace. Defaults to the release namespace when omitted.
686    #[serde(default, skip_serializing_if = "Option::is_none")]
687    pub namespace: Option<String>,
688}
689
690/// User-customizable deployment settings specified at deploy time.
691///
692/// These settings are provided by the customer via CloudFormation parameters,
693/// Terraform attributes, CLI flags, or Helm values. They customize how the
694/// deployment runs and what capabilities are enabled.
695///
696/// **Key distinction**: StackSettings is user-customizable, while ManagementConfig
697/// is platform-derived (from the Manager's ServiceAccount).
698#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
699#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
700#[serde(rename_all = "camelCase")]
701pub struct StackSettings {
702    /// Network configuration for the stack (VPC/VNet settings).
703    /// If `None`, an isolated VPC with NAT is auto-created when the stack has resources
704    /// that require networking (e.g., containers). Set explicitly to customize:
705    /// `UseDefault` for the provider's default network (fast, dev/test only),
706    /// `Create` for an isolated VPC with managed NAT (production), or `ByoVpc*`
707    /// to reference an existing customer-managed VPC.
708    #[serde(default, skip_serializing_if = "Option::is_none")]
709    pub network: Option<NetworkSettings>,
710
711    /// Domain configuration (future).
712    #[serde(default, skip_serializing_if = "Option::is_none")]
713    pub domains: Option<DomainSettings>,
714
715    /// Kubernetes runtime substrate configuration.
716    #[serde(default, skip_serializing_if = "Option::is_none")]
717    pub kubernetes: Option<KubernetesSettings>,
718
719    /// Deployment-time compute selections for Alien-managed compute pools.
720    ///
721    /// This is where provider machine names such as EC2 instance types, GCE
722    /// machine types, or Azure VM SKUs belong. Application source should
723    /// declare portable requirements instead.
724    #[serde(default, skip_serializing_if = "Option::is_none")]
725    pub compute: Option<ComputeSettings>,
726
727    /// Deployment model: push (Manager) or pull (Agent).
728    /// Default: Push.
729    /// - Push: Manager drives updates. For cloud platforms, requires cross-account
730    ///   credentials established during initial setup. For push-mode local
731    ///   deployments (currently `alien dev`), the manager has direct access —
732    ///   no bootstrap needed.
733    /// - Pull: Agent in the target environment drives updates via polling.
734    ///   Required for Kubernetes and remote local deployments.
735    #[serde(default, skip_serializing_if = "is_default_deployment_model")]
736    pub deployment_model: DeploymentModel,
737
738    /// How updates are delivered.
739    /// - auto: Updates deploy automatically (default)
740    /// - approval-required: Updates wait for explicit approval
741    #[serde(default, skip_serializing_if = "is_default_updates_mode")]
742    pub updates: UpdatesMode,
743
744    /// How telemetry (logs, metrics, traces) is handled.
745    /// - off: No telemetry permissions
746    /// - auto: Telemetry flows automatically (default)
747    /// - approval-required: Telemetry waits for explicit approval
748    #[serde(default, skip_serializing_if = "is_default_telemetry_mode")]
749    pub telemetry: TelemetryMode,
750
751    /// How heartbeat health checks are handled.
752    /// - off: No heartbeat permissions
753    /// - on: Heartbeat enabled (default)
754    #[serde(default, skip_serializing_if = "is_default_heartbeats_mode")]
755    pub heartbeats: HeartbeatsMode,
756
757    /// External bindings for pre-existing infrastructure.
758    /// Allows using existing resources (MinIO, Redis, shared Container Apps
759    /// Environment, etc.) instead of having Alien provision them.
760    /// Required for Kubernetes platform, optional for cloud platforms.
761    #[serde(default, skip_serializing_if = "Option::is_none")]
762    #[cfg_attr(feature = "openapi", schema(value_type = Option<Object>))]
763    pub external_bindings: Option<crate::ExternalBindings>,
764}
765
766fn is_default_deployment_model(model: &DeploymentModel) -> bool {
767    *model == DeploymentModel::default()
768}
769
770fn is_default_updates_mode(mode: &UpdatesMode) -> bool {
771    *mode == UpdatesMode::default()
772}
773
774fn is_default_telemetry_mode(mode: &TelemetryMode) -> bool {
775    *mode == TelemetryMode::default()
776}
777
778fn is_default_heartbeats_mode(mode: &HeartbeatsMode) -> bool {
779    *mode == HeartbeatsMode::default()
780}
781
782#[cfg(test)]
783mod failure_domain_tests {
784    use super::*;
785
786    #[test]
787    fn old_compute_selection_deserializes_without_topology() {
788        let selection: ComputePoolSelection = serde_json::from_value(serde_json::json!({
789            "mode": "fixed",
790            "machines": 2,
791            "machine": "m7i.xlarge"
792        }))
793        .expect("existing selection should deserialize");
794        assert!(selection.failure_domains().is_none());
795    }
796
797    #[test]
798    fn rejects_duplicate_concrete_failure_domains() {
799        let selection = ComputePoolSelection::Fixed {
800            machines: 2,
801            machine: Some("m7i.xlarge".to_string()),
802            failure_domains: Some(FailureDomainSelection {
803                spread: 2,
804                selected_failure_domains: vec!["us-west-2a".to_string(); 2],
805            }),
806        };
807        assert_eq!(
808            selection.validate(),
809            Err("selected failure domains must be unique".to_string())
810        );
811    }
812
813    #[test]
814    fn fixed_pool_must_have_one_machine_per_failure_domain() {
815        let invalid = ComputePoolSelection::Fixed {
816            machines: 1,
817            machine: None,
818            failure_domains: Some(FailureDomainSelection {
819                spread: 2,
820                selected_failure_domains: Vec::new(),
821            }),
822        };
823        assert_eq!(
824            invalid.validate(),
825            Err(
826                "fixed compute pool machines (1) must be at least failure-domain spread (2)"
827                    .to_string()
828            )
829        );
830
831        let valid = ComputePoolSelection::Fixed {
832            machines: 2,
833            machine: None,
834            failure_domains: Some(FailureDomainSelection {
835                spread: 2,
836                selected_failure_domains: Vec::new(),
837            }),
838        };
839        assert_eq!(valid.validate(), Ok(()));
840    }
841
842    #[test]
843    fn autoscaling_pool_bounds_must_cover_every_failure_domain() {
844        let invalid_max = ComputePoolSelection::Autoscale {
845            min: 1,
846            max: 1,
847            machine: None,
848            failure_domains: Some(FailureDomainSelection {
849                spread: 2,
850                selected_failure_domains: Vec::new(),
851            }),
852        };
853        assert_eq!(
854            invalid_max.validate(),
855            Err(
856                "autoscaling compute pool maximum (1) must be at least failure-domain spread (2)"
857                    .to_string()
858            )
859        );
860
861        let invalid_min = ComputePoolSelection::Autoscale {
862            min: 1,
863            max: 3,
864            machine: None,
865            failure_domains: Some(FailureDomainSelection {
866                spread: 2,
867                selected_failure_domains: Vec::new(),
868            }),
869        };
870        assert_eq!(
871            invalid_min.validate(),
872            Err(
873                "autoscaling compute pool minimum (1) must be at least failure-domain spread (2)"
874                    .to_string()
875            )
876        );
877
878        let valid = ComputePoolSelection::Autoscale {
879            min: 2,
880            max: 2,
881            machine: None,
882            failure_domains: Some(FailureDomainSelection {
883                spread: 2,
884                selected_failure_domains: Vec::new(),
885            }),
886        };
887        assert_eq!(valid.validate(), Ok(()));
888    }
889}