Skip to main content

alien_core/deployment/
config.rs

1//! Deployment configuration and OTLP observability settings.
2
3use crate::{ExternalBindings, ManagementConfig, StackSettings};
4use bon::Builder;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7
8use super::{is_false, ComputeBackend, DomainMetadata, EnvironmentVariablesSnapshot};
9
10/// Deployment configuration
11///
12/// Configuration for how to perform the deployment.
13/// Note: Credentials (ClientConfig) are passed separately to step() function.
14#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
15#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
16#[serde(rename_all = "camelCase")]
17pub struct DeploymentConfig {
18    /// Human-readable deployment name for cloud console metadata.
19    ///
20    /// This is separate from the physical resource prefix in StackState. It is
21    /// used only for display text such as IAM role descriptions, service
22    /// account descriptions, and custom role titles.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub deployment_name: Option<String>,
25    /// User-customizable deployment settings (network, deployment model, approvals).
26    /// Provided by customer via CloudFormation, Terraform, CLI, or Helm.
27    #[serde(default)]
28    pub stack_settings: StackSettings,
29    /// Platform service account/role that will manage the infrastructure remotely.
30    /// Derived from Manager's ServiceAccount, not user-specified.
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub management_config: Option<ManagementConfig>,
33    /// Environment variables snapshot
34    pub environment_variables: EnvironmentVariablesSnapshot,
35    /// Deployer-provided stack input values, keyed by input id. A resource
36    /// gated with `.enabled(input)` and a Live lifecycle follows these
37    /// values; a missing key falls back to the input's declared boolean
38    /// default. Suppliers must not place secret-kind input values here:
39    /// this map serializes and debug-prints unredacted.
40    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
41    #[builder(default)]
42    pub input_values: HashMap<String, serde_json::Value>,
43    /// IDs of applicable secret inputs stored for this exact deployment target.
44    /// Trusted presence metadata only: never values, gate answers, or authority.
45    /// Absent on legacy targets; an explicit empty list means no stored secrets.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    #[cfg_attr(feature = "openapi", schema(nullable = false))]
48    pub stored_secret_input_ids: Option<Vec<String>>,
49    /// Allow frozen resource changes during updates
50    /// When true, skips the frozen resources compatibility check.
51    /// This requires running with elevated cloud credentials.
52    #[serde(default, skip_serializing_if = "is_false")]
53    pub allow_frozen_changes: bool,
54    /// Compute backend for Container and Worker resources.
55    /// When None, the platform default is used for cloud platforms.
56    /// Contains cluster IDs and management tokens for container orchestration.
57    /// Worker runtime credentials are provided through cloud identity and vault-backed secrets.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub compute_backend: Option<ComputeBackend>,
60    /// External bindings for pre-existing services.
61    /// Required for Kubernetes platform (all infrastructure resources).
62    /// Optional for cloud platforms (override specific resources).
63    #[serde(default)]
64    pub external_bindings: ExternalBindings,
65    /// Cloud platform that owns imported base infrastructure for a Kubernetes
66    /// runtime deployment.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub base_platform: Option<crate::Platform>,
69    /// DNS-style label domain used for Kubernetes resource ownership labels.
70    ///
71    /// Defaults to `alien.dev` when absent. Whitelabeled Operator builds set this
72    /// so generated workloads and optional log collectors share the same label
73    /// namespace.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub label_domain: Option<String>,
76    /// Kubernetes label selector that narrows which raw resources the observe
77    /// pass reports (e.g. `app.kubernetes.io/part-of=my-app`). `None` observes
78    /// everything in the namespace. Ignored by cloud observers.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub observe_label_selector: Option<String>,
81    /// When true the observe pass reports raw resources across every namespace
82    /// (cluster scope); otherwise it stays within the operator's own namespace.
83    /// The label selector, if any, still filters within whichever scope applies.
84    /// Ignored by cloud observers.
85    #[serde(default)]
86    #[builder(default)]
87    pub observe_all_namespaces: bool,
88    /// Public endpoint URLs for exposed resources (optional override).
89    ///
90    /// Use this only when a caller already knows the public URL. Managed public
91    /// endpoint flows should prefer `domain_metadata` plus controller-reported
92    /// load balancer outputs so DNS, certificate renewal, and route readiness
93    /// stay tied to the resource state.
94    ///
95    /// If not set, platforms determine public endpoint URLs from other sources:
96    /// - Managed DNS/TLS flows: `domain_metadata` FQDN or load balancer DNS
97    /// - Local: `http://localhost:{allocated_port}`
98    /// - Custom or disabled exposure: no public endpoint URL unless a controller reports one
99    ///
100    /// Outer key: resource ID. Inner key: endpoint name. Value: public URL.
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub public_endpoints: Option<HashMap<String, HashMap<String, String>>>,
103    /// Domain metadata for auto-managed public resources.
104    ///
105    /// Contains generated hostnames, DNS record state, certificate material,
106    /// and renewal markers for platforms that use managed public endpoints.
107    /// Kubernetes uses this only when its exposure mode is `generated`; BYO and
108    /// disabled Kubernetes exposure do not receive managed domain metadata.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub domain_metadata: Option<DomainMetadata>,
111    /// OTLP observability configuration for log export (optional).
112    ///
113    /// When set, worker runtimes export captured application logs through this
114    /// endpoint. Container orchestrators may use it for their node-level log
115    /// collectors, but app container configs must not receive the auth header.
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub monitoring: Option<OtlpConfig>,
118    /// Manager base URL (e.g., "https://manager.alien.dev").
119    ///
120    /// The manager IS the container registry — its `/v2/` endpoint serves as
121    /// the OCI Distribution API. Controllers derive the proxy host from this
122    /// to configure pull auth (RegistryCredentials, imagePullSecrets).
123    ///
124    /// When None (e.g., `alien dev`), controllers use image URIs as-is.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub manager_url: Option<String>,
127    /// Deployment token for pull authentication with the manager's registry.
128    ///
129    /// Used by controllers to configure registry credentials so cloud platforms
130    /// and K8s can pull images from the manager's `/v2/` endpoint.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub deployment_token: Option<String>,
133    /// Native image registry host+prefix for platforms that require it.
134    ///
135    /// Lambda (ECR) and Cloud Run (GAR) require native registry URIs. Other
136    /// runtimes, including Azure Container Apps, pull through the manager's
137    /// registry proxy.
138    ///
139    /// Derived by the manager from the artifact registry binding:
140    /// - ECR: `{account_id}.dkr.ecr.{region}.amazonaws.com/{repository_prefix}`
141    /// - GAR: `{region}-docker.pkg.dev/{project_id}/{repository_name}`
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub native_image_host: Option<String>,
144    /// Operator requests to replace a replica's persistent volume with a new
145    /// volume made from a snapshot. A container controller performs each
146    /// request once, identified by its `request_id`, and reports it in
147    /// `ContainerOutputs.volumes`. Only a volume that a controller reports in
148    /// `ContainerOutputs.volumes` can be the target of a request.
149    #[serde(default, skip_serializing_if = "Vec::is_empty")]
150    #[builder(default)]
151    pub volume_restores: Vec<VolumeRestoreRequest>,
152}
153
154/// Replace one replica's persistent volume with a new volume made from a snapshot.
155///
156/// The controller stops the replica, snapshots the volume it is about to
157/// replace (so the restore can be undone), creates the new volume in the same
158/// zone, starts the replica on it, and deletes the replaced volume.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
161#[serde(rename_all = "camelCase")]
162pub struct VolumeRestoreRequest {
163    /// Unique ID of this request. A controller performs each request once.
164    pub request_id: String,
165    /// ID of the container resource that owns the volume
166    pub resource_id: String,
167    /// Replica ordinal whose volume is replaced
168    pub ordinal: u32,
169    /// Cloud ID of the snapshot to restore: an EBS snapshot ID, a Compute
170    /// Engine snapshot name, or an Azure snapshot resource ID
171    pub snapshot_id: String,
172}
173
174/// Resource-attribute key marking OTLP telemetry as Alien system-component
175/// output (infrastructure daemons and internal runtimes) rather than user
176/// workload. Log consumers — the CLI log viewer and the dashboard — hide
177/// telemetry carrying this attribute by default. The value is the string
178/// `"true"`.
179///
180/// System components set this on their own telemetry's resource attributes so
181/// consumers can filter generically, without enumerating component names.
182pub const ALIEN_SYSTEM_RESOURCE_ATTRIBUTE: &str = "alien.system";
183
184/// OTLP log export configuration for a deployment.
185///
186/// When set, injected compute runtimes export captured application logs
187/// through the given endpoint via OTLP/HTTP; which resources are injected
188/// is platform-dependent. Workers read auth headers from a runtime-only
189/// secret. Runtime-less Containers and Daemons receive standard OTEL auth
190/// variables only at the final hosting boundary: Local passes them directly
191/// to the process and Kubernetes projects them from a per-workload Secret.
192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
193#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
194#[serde(rename_all = "camelCase")]
195pub struct OtlpConfig {
196    /// Full OTLP logs endpoint URL.
197    /// Example: "https://<manager-host>/v1/logs"
198    pub logs_endpoint: String,
199    /// Auth header value in "key=value,..." format.
200    /// Example: "authorization=Bearer <write-token>"
201    pub logs_auth_header: String,
202    /// Full OTLP metrics endpoint URL (optional).
203    /// When set, the worker runtime exports its own VM/container orchestration metrics here.
204    /// Example: "https://api.axiom.co/v1/metrics"
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub metrics_endpoint: Option<String>,
207    /// Auth header value for the metrics endpoint in "key=value,..." format (optional).
208    ///
209    /// When absent, `logs_auth_header` is reused for metrics -- suitable when the same
210    /// credential covers both signals. When present (e.g. Axiom with separate datasets),
211    /// this value is used exclusively for metrics.
212    ///
213    /// Example: "authorization=Bearer <token>,x-axiom-dataset=<metrics-dataset>"
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub metrics_auth_header: Option<String>,
216    /// Resource attributes attached to every OTLP signal emitted for this deployment.
217    ///
218    /// Platform managers use this for stable identity such as `alien.workspace_id`,
219    /// `alien.project_id`, `alien.deployment_group_id`, and `alien.deployment_id`.
220    /// Runtime-specific resource attributes such as `service.name` remain owned by
221    /// the runtime/exporter.
222    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
223    pub resource_attributes: HashMap<String, String>,
224}
225
226#[cfg(test)]
227mod input_values_tests {
228    use super::*;
229
230    /// Older actors serialize configs without the field; it must deserialize
231    /// to an empty map, and an empty map must not serialize at all.
232    #[test]
233    fn input_values_default_to_empty_and_stay_off_the_wire() {
234        let json = serde_json::json!({
235            "stackSettings": serde_json::to_value(crate::StackSettings::default()).unwrap(),
236            "environmentVariables": {
237                "variables": [],
238                "hash": "hash",
239                "createdAt": "2026-01-01T00:00:00Z",
240            },
241            "externalBindings": {},
242        });
243        let config: DeploymentConfig =
244            serde_json::from_value(json).expect("old shape deserializes");
245        assert!(config.input_values.is_empty());
246        assert!(config.stored_secret_input_ids.is_none());
247
248        let round = serde_json::to_value(&config).expect("serializes");
249        assert!(round.get("storedSecretInputIds").is_none());
250        assert!(
251            round.get("inputValues").is_none(),
252            "empty map must not serialize"
253        );
254    }
255    #[test]
256    fn stored_secret_presence_roundtrips_without_values_or_gate_answers() {
257        let mut config = DeploymentConfig::builder()
258            .stack_settings(StackSettings::default())
259            .environment_variables(EnvironmentVariablesSnapshot {
260                variables: vec![],
261                hash: String::new(),
262                created_at: String::new(),
263            })
264            .allow_frozen_changes(false)
265            .external_bindings(ExternalBindings::default())
266            .build();
267        assert!(config.stored_secret_input_ids.is_none());
268        config.stored_secret_input_ids = Some(Vec::new());
269        let empty = serde_json::to_value(&config).unwrap();
270        assert_eq!(empty["storedSecretInputIds"], serde_json::json!([]));
271        assert_eq!(
272            serde_json::from_value::<DeploymentConfig>(empty)
273                .unwrap()
274                .stored_secret_input_ids,
275            Some(Vec::new())
276        );
277        config.stored_secret_input_ids =
278            Some(vec!["apiKey".to_string(), "enableFeature".to_string()]);
279        let wire = serde_json::to_value(&config).unwrap();
280        assert_eq!(
281            wire["storedSecretInputIds"],
282            serde_json::json!(["apiKey", "enableFeature"])
283        );
284        assert!(wire.get("inputValues").is_none());
285        let decoded: DeploymentConfig = serde_json::from_value(wire.clone()).unwrap();
286        assert_eq!(
287            decoded.stored_secret_input_ids,
288            config.stored_secret_input_ids
289        );
290        assert_eq!(serde_json::to_value(decoded.clone()).unwrap(), wire);
291        assert!(decoded.input_values.is_empty());
292        for default in [false, true] {
293            let input: crate::StackInputDefinition = serde_json::from_value(serde_json::json!({
294                "id": "enableFeature", "kind": "boolean", "providedBy": ["deployer"],
295                "required": false, "label": "Enable feature", "description": "", "default": crate::StackInputDefaultValue::Boolean(default)
296            }))
297            .unwrap();
298            assert_eq!(
299                crate::gate_resolves_true(
300                    &[input],
301                    "enableFeature",
302                    &decoded.input_values,
303                    "worker"
304                )
305                .unwrap(),
306                default
307            );
308        }
309        assert!(
310            crate::gate_resolves_true(&[], "enableFeature", &decoded.input_values, "worker")
311                .is_err()
312        );
313    }
314}