Skip to main content

alien_core/deployment/
compute.rs

1//! Compute backend configuration for container orchestration.
2
3use std::collections::HashMap;
4
5use serde::{Deserialize, Serialize};
6
7/// Configuration for a single container worker cluster.
8///
9/// Contains the cluster ID and management token needed to interact with
10/// the managed container control plane API for container operations.
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
13#[serde(rename_all = "camelCase")]
14pub struct HorizonClusterConfig {
15    /// Cluster ID (deterministic: workspace/project/deployment/resourceid)
16    pub cluster_id: String,
17
18    /// Management token for API access (hm_...)
19    /// Used by alien-deployment controllers to create/update containers
20    pub management_token: String,
21
22    /// Nonsecret configuration for bounded machine identity. Existing clusters
23    /// remain on their prior authentication until explicitly migrated.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub runtime_identity: Option<MachineRuntimeIdentity>,
26
27    /// Machine image this cluster's machines run. When set, it replaces
28    /// [`HorizonConfig::horizon_machine_image`] for this cluster only, so one
29    /// cluster can stay on the image it runs while others move to a newer one.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub horizon_machine_image: Option<HorizonMachineImage>,
32
33    /// Control-plane URL this cluster's machines use, when it differs from
34    /// [`HorizonConfig::url`], for example a relay in front of the control
35    /// plane. Chosen when the cluster is created and never changed by later
36    /// updates, so machines that have already joined keep the URL they use.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub machine_url: Option<String>,
39}
40
41/// Trusted manager endpoint and audience used by a machine to obtain leaf capabilities.
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
43#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
44#[serde(rename_all = "camelCase", deny_unknown_fields)]
45pub struct MachineRuntimeIdentity {
46    pub exchange_url: String,
47    pub deployment_id: String,
48    pub audience: String,
49}
50
51/// Machine image architecture.
52#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
53#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
54#[serde(rename_all = "camelCase")]
55pub enum HorizonMachineArchitecture {
56    /// Linux arm64 / aarch64 machine image.
57    #[serde(rename = "arm64")]
58    Arm64,
59    /// Linux amd64 / x86_64 machine image.
60    #[serde(rename = "amd64")]
61    Amd64,
62}
63
64/// AWS machine image catalog.
65#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
66#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
67#[serde(rename_all = "camelCase")]
68pub struct HorizonAwsMachineImages {
69    /// AMI IDs by architecture, then AWS region.
70    pub amis: HashMap<HorizonMachineArchitecture, HashMap<String, String>>,
71}
72
73/// GCP machine image entry.
74#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
75#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
76#[serde(rename_all = "camelCase")]
77pub struct HorizonGcpMachineImage {
78    /// Source image self link or image-family URL.
79    pub source_image: String,
80}
81
82/// GCP machine image catalog.
83#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
84#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
85#[serde(rename_all = "camelCase")]
86pub struct HorizonGcpMachineImages {
87    /// Images by architecture.
88    pub images: HashMap<HorizonMachineArchitecture, HorizonGcpMachineImage>,
89}
90
91/// Azure machine image entry.
92#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
93#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
94#[serde(rename_all = "camelCase")]
95pub struct HorizonAzureMachineImage {
96    /// Azure Compute Gallery image version ID.
97    pub image_version_id: String,
98}
99
100/// Base image metadata for the machine image.
101#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
102#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
103#[serde(rename_all = "camelCase")]
104pub struct HorizonMachineBaseImage {
105    /// Base OS image name.
106    pub name: String,
107    /// Base OS image version or channel.
108    pub version: String,
109}
110
111/// Azure machine image catalog.
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
113#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
114#[serde(rename_all = "camelCase")]
115pub struct HorizonAzureMachineImages {
116    /// Images by architecture.
117    pub images: HashMap<HorizonMachineArchitecture, HorizonAzureMachineImage>,
118}
119
120/// Machine agent download for one release platform.
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
122#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
123#[serde(rename_all = "camelCase")]
124pub struct HorizondArtifact {
125    /// Runtime isolation capability generation of the immutable artifact, not live readiness.
126    #[serde(default)]
127    pub runtime_isolation_generation: u32,
128    /// HTTPS URL for the artifact.
129    pub url: String,
130    /// SHA-256 digest for the artifact payload.
131    pub sha256: String,
132}
133
134/// Machine image catalog.
135///
136/// Platform resolves concrete provider images from this catalog during rollout.
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
138#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
139#[serde(rename_all = "camelCase")]
140pub struct HorizonMachineImage {
141    /// Runtime isolation capability generation of the immutable artifact, not live readiness.
142    #[serde(default)]
143    pub runtime_isolation_generation: u32,
144    /// Logical image channel, such as prod, staging, or canary.
145    pub channel: String,
146    /// Published immutable machine image version.
147    pub machine_image_version: String,
148    /// Machine agent version baked into the image.
149    pub horizond_version: String,
150    /// Git commit SHA used to build the image.
151    pub git_sha: String,
152    /// Image manifest creation timestamp.
153    pub created_at: String,
154    /// Base OS image metadata.
155    pub base_image: HorizonMachineBaseImage,
156    /// Per-architecture machine agent downloads by release-platform key.
157    pub horizond_artifacts: HashMap<String, HorizondArtifact>,
158    /// AWS image catalog.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub aws: Option<HorizonAwsMachineImages>,
161    /// GCP image catalog.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub gcp: Option<HorizonGcpMachineImages>,
164    /// Azure image catalog.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub azure: Option<HorizonAzureMachineImages>,
167}
168
169/// Machine control-plane configuration for container orchestration.
170///
171/// Contains all the information needed for Alien to interact with managed
172/// container clusters during deployment. Each ComputeCluster resource gets its own
173/// entry in the clusters map.
174#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
175#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
176#[serde(rename_all = "camelCase")]
177pub struct HorizonConfig {
178    /// Machine control-plane API base URL.
179    pub url: String,
180
181    /// Machine image catalog.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub horizon_machine_image: Option<HorizonMachineImage>,
184
185    /// Cluster configurations (one per ComputeCluster resource)
186    /// Key: ComputeCluster resource ID from stack
187    /// Value: Cluster ID and management token for that cluster
188    pub clusters: HashMap<String, HorizonClusterConfig>,
189}
190
191impl HorizonConfig {
192    /// The machine image for the cluster of the ComputeCluster resource
193    /// `resource_id`: its own image when it has one, otherwise the catalog's.
194    pub fn machine_image_for(&self, resource_id: &str) -> Option<&HorizonMachineImage> {
195        self.clusters
196            .get(resource_id)
197            .and_then(|cluster| cluster.horizon_machine_image.as_ref())
198            .or(self.horizon_machine_image.as_ref())
199    }
200}
201
202/// Compute backend for Container and Worker resources.
203///
204/// Determines how compute workloads are orchestrated on cloud platforms.
205/// When None, the platform default is used for cloud platforms.
206#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
207#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
208#[serde(tag = "type", rename_all = "camelCase")]
209pub enum ComputeBackend {
210    /// VM-backed container orchestration (default for cloud platforms)
211    Horizon(HorizonConfig),
212    // Future backends:
213    // /// Deploy to existing Kubernetes cluster (EKS/GKE/AKS)
214    // Kubernetes(KubernetesCredentials),
215    // /// AWS ECS Fargate (serverless containers)
216    // EcsFargate,
217}
218
219#[cfg(test)]
220mod tests {
221    use serde_json::{json, Value};
222
223    use std::collections::HashMap;
224
225    use serde::Deserialize;
226
227    use super::{HorizonClusterConfig, HorizonConfig, HorizonMachineImage, HorizondArtifact};
228
229    fn legacy_catalog() -> Value {
230        json!({
231            "channel": "stable",
232            "machineImageVersion": "1",
233            "horizondVersion": "1",
234            "gitSha": "abc123",
235            "createdAt": "2026-01-01T00:00:00Z",
236            "baseImage": { "name": "linux", "version": "1" },
237            "horizondArtifacts": {
238                "linux-arm64": { "url": "https://example.com/arm64", "sha256": "a".repeat(64) },
239                "linux-amd64": { "url": "https://example.com/amd64", "sha256": "b".repeat(64) }
240            },
241            "aws": { "amis": { "arm64": { "us-east-1": "ami-example" } } },
242            "gcp": { "images": { "arm64": { "sourceImage": "example-image" } } },
243            "azure": { "images": { "arm64": { "imageVersionId": "example-version" } } }
244        })
245    }
246
247    #[test]
248    fn runtime_isolation_generation_legacy_catalog_defaults_to_zero() {
249        let mut expected = legacy_catalog();
250        let catalog: HorizonMachineImage = serde_json::from_value(expected.clone()).unwrap();
251        assert_eq!(catalog.runtime_isolation_generation, 0);
252        expected["runtimeIsolationGeneration"] = json!(0);
253        for (arch, artifact) in &catalog.horizond_artifacts {
254            assert_eq!(artifact.runtime_isolation_generation, 0);
255            let decoded: HorizondArtifact =
256                serde_json::from_value(expected["horizondArtifacts"][arch].clone()).unwrap();
257            assert_eq!(&decoded, artifact);
258            expected["horizondArtifacts"][arch]["runtimeIsolationGeneration"] = json!(0);
259            assert_eq!(
260                serde_json::to_value(decoded).unwrap(),
261                expected["horizondArtifacts"][arch]
262            );
263        }
264        assert_eq!(serde_json::to_value(catalog).unwrap(), expected);
265    }
266
267    #[test]
268    fn runtime_isolation_generation_roundtrips_catalog_and_each_artifact() {
269        let mut expected = legacy_catalog();
270        expected["runtimeIsolationGeneration"] = json!(1);
271        for artifact in expected["horizondArtifacts"]
272            .as_object_mut()
273            .unwrap()
274            .values_mut()
275        {
276            artifact["runtimeIsolationGeneration"] = json!(1);
277        }
278        let catalog: HorizonMachineImage = serde_json::from_value(expected.clone()).unwrap();
279        assert_eq!(catalog.runtime_isolation_generation, 1);
280        for (arch, artifact) in &catalog.horizond_artifacts {
281            assert_eq!(artifact.runtime_isolation_generation, 1);
282            let encoded = serde_json::to_value(artifact).unwrap();
283            assert_eq!(encoded, expected["horizondArtifacts"][arch]);
284            assert_eq!(
285                serde_json::from_value::<HorizondArtifact>(encoded).unwrap(),
286                *artifact
287            );
288        }
289        assert_eq!(serde_json::to_value(catalog).unwrap(), expected);
290    }
291
292    #[test]
293    fn runtime_isolation_generation_rejects_invalid_numbers_and_types() {
294        for invalid in [
295            json!(-1),
296            json!(1.5),
297            json!("1"),
298            json!(null),
299            json!(4294967296_u64),
300        ] {
301            let mut catalog = legacy_catalog();
302            catalog["runtimeIsolationGeneration"] = invalid.clone();
303            assert!(serde_json::from_value::<HorizonMachineImage>(catalog).is_err());
304            for arch in ["linux-arm64", "linux-amd64"] {
305                let mut catalog = legacy_catalog();
306                catalog["horizondArtifacts"][arch]["runtimeIsolationGeneration"] = invalid.clone();
307                assert!(serde_json::from_value::<HorizondArtifact>(
308                    catalog["horizondArtifacts"][arch].clone()
309                )
310                .is_err());
311                assert!(serde_json::from_value::<HorizonMachineImage>(catalog).is_err());
312            }
313        }
314    }
315
316    fn catalog_version(version: &str) -> Value {
317        let mut catalog = legacy_catalog();
318        catalog["machineImageVersion"] = json!(version);
319        catalog
320    }
321
322    #[test]
323    fn cluster_without_its_own_machine_image_reads_as_before() {
324        let config: HorizonConfig = serde_json::from_value(json!({
325            "url": "https://horizon.example.com",
326            "horizonMachineImage": catalog_version("2"),
327            "clusters": {
328                "compute": { "clusterId": "cluster-1", "managementToken": "hm_test" }
329            }
330        }))
331        .expect("a config written before the field existed must deserialize");
332
333        assert_eq!(config.clusters["compute"].horizon_machine_image, None);
334        assert_eq!(
335            config
336                .machine_image_for("compute")
337                .map(|image| image.machine_image_version.as_str()),
338            Some("2")
339        );
340        // Writing it back adds nothing, so readers that predate the field see the same document.
341        let written = serde_json::to_value(&config.clusters["compute"]).unwrap();
342        assert_eq!(
343            written,
344            json!({ "clusterId": "cluster-1", "managementToken": "hm_test" })
345        );
346    }
347
348    #[test]
349    fn each_cluster_uses_its_own_machine_image_when_it_has_one() {
350        let config: HorizonConfig = serde_json::from_value(json!({
351            "url": "https://horizon.example.com",
352            "horizonMachineImage": catalog_version("2"),
353            "clusters": {
354                "held": {
355                    "clusterId": "cluster-1",
356                    "managementToken": "hm_test",
357                    "horizonMachineImage": catalog_version("1")
358                },
359                "moving": { "clusterId": "cluster-2", "managementToken": "hm_test" }
360            }
361        }))
362        .unwrap();
363
364        let version = |resource_id| {
365            config
366                .machine_image_for(resource_id)
367                .map(|image| image.machine_image_version.clone())
368        };
369        assert_eq!(version("held").as_deref(), Some("1"));
370        assert_eq!(version("moving").as_deref(), Some("2"));
371        assert_eq!(version("unknown").as_deref(), Some("2"));
372    }
373
374    /// The cluster and catalog types as they were before clusters could carry their own image.
375    /// Nothing on the path from the deployment config to a cluster rejects unknown fields, so an
376    /// older reader keeps working when a newer writer sets the image.
377    #[derive(Debug, Deserialize, PartialEq)]
378    #[serde(rename_all = "camelCase")]
379    struct PreviousHorizonClusterConfig {
380        cluster_id: String,
381        management_token: String,
382    }
383
384    #[derive(Debug, Deserialize)]
385    #[serde(rename_all = "camelCase")]
386    struct PreviousHorizonConfig {
387        #[allow(dead_code)]
388        url: String,
389        #[serde(default)]
390        horizon_machine_image: Option<HorizonMachineImage>,
391        clusters: HashMap<String, PreviousHorizonClusterConfig>,
392    }
393
394    #[test]
395    fn readers_that_predate_cluster_machine_images_ignore_them() {
396        let config = HorizonConfig {
397            url: "https://horizon.example.com".to_string(),
398            horizon_machine_image: Some(serde_json::from_value(catalog_version("2")).unwrap()),
399            clusters: HashMap::from([(
400                "compute".to_string(),
401                HorizonClusterConfig {
402                    machine_url: None,
403                    cluster_id: "cluster-1".to_string(),
404                    management_token: "hm_test".to_string(),
405                    runtime_identity: None,
406                    horizon_machine_image: Some(
407                        serde_json::from_value(catalog_version("1")).unwrap(),
408                    ),
409                },
410            )]),
411        };
412        let written = serde_json::to_value(&config).unwrap();
413        assert!(written["clusters"]["compute"]["horizonMachineImage"].is_object());
414
415        let previous: PreviousHorizonConfig = serde_json::from_value(written)
416            .expect("an older reader must accept a cluster that carries its own image");
417        assert_eq!(
418            previous.clusters["compute"],
419            PreviousHorizonClusterConfig {
420                cluster_id: "cluster-1".to_string(),
421                management_token: "hm_test".to_string(),
422            }
423        );
424        assert_eq!(
425            previous
426                .horizon_machine_image
427                .map(|image| image.machine_image_version),
428            Some("2".to_string())
429        );
430    }
431
432    #[test]
433    fn cluster_machine_url_is_optional_and_ignored_by_older_readers() {
434        let config: HorizonConfig = serde_json::from_value(json!({
435            "url": "https://horizon.example.com",
436            "clusters": {
437                "relayed": {
438                    "clusterId": "cluster-1",
439                    "managementToken": "hm_test",
440                    "machineUrl": "https://relay.example.com/v1/horizon"
441                },
442                "direct": { "clusterId": "cluster-2", "managementToken": "hm_test" }
443            }
444        }))
445        .expect("a config written before the field existed must deserialize");
446
447        assert_eq!(
448            config.clusters["relayed"].machine_url.as_deref(),
449            Some("https://relay.example.com/v1/horizon")
450        );
451        assert_eq!(config.clusters["direct"].machine_url, None);
452        // A cluster without its own machine URL writes back exactly as before.
453        assert_eq!(
454            serde_json::to_value(&config.clusters["direct"]).unwrap(),
455            json!({ "clusterId": "cluster-2", "managementToken": "hm_test" })
456        );
457        // An older reader accepts a cluster that carries a machine URL.
458        let previous: PreviousHorizonConfig =
459            serde_json::from_value(serde_json::to_value(&config).unwrap()).unwrap();
460        assert_eq!(previous.clusters["relayed"].cluster_id, "cluster-1");
461    }
462}