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