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::{
9    is_false, ComputeBackend, DeletionPolicy, DomainMetadata, EnvironmentVariableType,
10    EnvironmentVariablesSnapshot,
11};
12
13/// Deployment configuration
14///
15/// Configuration for how to perform the deployment.
16/// A signed release and the chain that verifies it, carried to enforcers.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ReleaseStatements {
19    /// The `release/v2` statement for this deployment's platform.
20    pub release: crate::SignedStatement,
21    /// The project's signer list chain, oldest first.
22    pub signer_lists: Vec<crate::SignedStatement>,
23}
24
25/// Note: Credentials (ClientConfig) are passed separately to step() function.
26#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28#[serde(rename_all = "camelCase")]
29pub struct DeploymentConfig {
30    /// This invocation is an explicit setup run using the installer's credentials.
31    /// Not serialized: a release or stored configuration cannot request an identity refresh.
32    #[serde(skip)]
33    #[cfg_attr(feature = "openapi", schema(ignore))]
34    #[builder(default)]
35    pub setup_run: bool,
36    /// The deployment this configuration runs for. The runner sets it from the deployment it
37    /// holds on every step; a stored or supplied configuration cannot choose it. Controllers
38    /// put it in the ownership marker of what they create, so a second deployment that reuses
39    /// a resource prefix is never mistaken for the owner.
40    #[serde(skip)]
41    #[cfg_attr(feature = "openapi", schema(ignore))]
42    pub deployment_id: Option<String>,
43    /// Identifies this setup run, set together with `setup_run`. Every setup run gets a new
44    /// one, so a controller can tell a result recorded earlier in this run from one recorded in
45    /// an earlier run.
46    #[serde(skip)]
47    #[cfg_attr(feature = "openapi", schema(ignore))]
48    pub setup_run_id: Option<String>,
49    /// The target release's signed statement and the signer list chain, for
50    /// controllers that hand them to the deployment's enforcers unchanged.
51    /// Set by the deployment runner from the release being deployed; not
52    /// serialized, so stored configuration can't supply them.
53    #[serde(skip)]
54    #[cfg_attr(feature = "openapi", schema(ignore))]
55    pub release_statements: Option<ReleaseStatements>,
56    /// A protected deployment's newest signed `config/v1`, which controllers hand to the
57    /// enforcers with the release. The enforcers verify it against the install's own trust and
58    /// refuse one older than what they accepted, so it is carried as received.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub signed_config: Option<crate::SignedStatement>,
61    /// Site registry (`host[/path]`) every Kubernetes workload image is pulled from.
62    /// Set by the Operator from the installation's `global.imageRegistry`; never part of a
63    /// release, so a release cannot redirect where an installation pulls from.
64    #[serde(skip)]
65    #[cfg_attr(feature = "openapi", schema(ignore))]
66    pub image_registry: Option<String>,
67    /// Names of the installation's image pull Secrets (the chart's `runtime.imagePullSecrets`).
68    /// Set by the Operator; listed on every workload pod so a private mirror can be pulled from.
69    #[serde(skip)]
70    #[cfg_attr(feature = "openapi", schema(ignore))]
71    #[builder(default)]
72    pub image_pull_secrets: Vec<String>,
73    /// Human-readable deployment name for cloud console metadata.
74    ///
75    /// This is separate from the physical resource prefix in StackState. It is
76    /// used only for display text such as IAM role descriptions, service
77    /// account descriptions, and custom role titles.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub deployment_name: Option<String>,
80    /// User-customizable deployment settings (network, deployment model, approvals).
81    /// Provided by customer via CloudFormation, Terraform, CLI, or Helm.
82    #[serde(default)]
83    pub stack_settings: StackSettings,
84    /// Platform service account/role that will manage the infrastructure remotely.
85    /// Derived from Manager's ServiceAccount, not user-specified.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub management_config: Option<ManagementConfig>,
88    /// The `sts:ExternalId` the control plane issued for this deployment, which a setup Alien
89    /// runs writes into the trust of the extension identities it creates on AWS. The setup CLI
90    /// sets it from its install context, and the manager from its control plane when it runs
91    /// the setup. Not serialized, so it never travels with a stored configuration or to an
92    /// extension's controller; the applied trust is kept in the identity's controller state with
93    /// the value's SHA-256 in its place.
94    #[serde(skip)]
95    #[cfg_attr(feature = "openapi", schema(ignore))]
96    pub management_external_id: Option<crate::ManagementExternalId>,
97    /// Registered installation identity for target federation setup.
98    /// Callers derive this from registration, separately from display metadata.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub gcp_federation_scope: Option<crate::GcpFederationScope>,
101    /// Environment variables snapshot
102    pub environment_variables: EnvironmentVariablesSnapshot,
103    /// Deployer-provided stack input values, keyed by input id. A resource
104    /// gated with `.enabled(input)` and a Live lifecycle follows these
105    /// values; a missing key falls back to the input's declared boolean
106    /// default. Suppliers must not place secret-kind input values here:
107    /// this map serializes and debug-prints unredacted.
108    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
109    #[builder(default)]
110    pub input_values: HashMap<String, serde_json::Value>,
111    /// Values the manager holds for this deployment instead of the sender.
112    /// For each slot the sender gives the kind and a keyed digest, never the
113    /// value. The manager loads the value from its own store, refuses to run
114    /// when a digest differs, and merges the value into `environment_variables`
115    /// or `input_values` before the deployment steps.
116    #[serde(default, skip_serializing_if = "Vec::is_empty")]
117    #[builder(default)]
118    pub value_slots: Vec<ValueSlotRef>,
119    /// IDs of applicable secret inputs stored for this exact deployment target.
120    /// Trusted presence metadata only: never values, gate answers, or authority.
121    /// Absent on legacy targets; an explicit empty list means no stored secrets.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    #[cfg_attr(feature = "openapi", schema(nullable = false))]
124    pub stored_secret_input_ids: Option<Vec<String>>,
125    /// Allow frozen resource changes during updates
126    /// When true, skips the frozen resources compatibility check.
127    /// This requires running with elevated cloud credentials.
128    #[serde(default, skip_serializing_if = "is_false")]
129    pub allow_frozen_changes: bool,
130    /// Compute backend for Container and Worker resources.
131    /// When None, the platform default is used for cloud platforms.
132    /// Contains cluster IDs and management tokens for container orchestration.
133    /// Worker runtime credentials are provided through cloud identity and vault-backed secrets.
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub compute_backend: Option<ComputeBackend>,
136    /// External bindings for pre-existing services.
137    /// Required for Kubernetes platform (all infrastructure resources).
138    /// Optional for cloud platforms (override specific resources).
139    #[serde(default)]
140    pub external_bindings: ExternalBindings,
141    /// Cloud platform that owns imported base infrastructure for a Kubernetes
142    /// runtime deployment.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub base_platform: Option<crate::Platform>,
145    /// DNS-style label domain used for Kubernetes resource ownership labels.
146    ///
147    /// Defaults to `alien.dev` when absent. Whitelabeled Operator builds set this
148    /// so generated workloads and optional log collectors share the same label
149    /// namespace.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub label_domain: Option<String>,
152    /// Kubernetes label selector that narrows which raw resources the observe
153    /// pass reports (e.g. `app.kubernetes.io/part-of=my-app`). `None` observes
154    /// everything in the namespace. Ignored by cloud observers.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub observe_label_selector: Option<String>,
157    /// When true the observe pass reports raw resources across every namespace
158    /// (cluster scope); otherwise it stays within the operator's own namespace.
159    /// The label selector, if any, still filters within whichever scope applies.
160    /// Ignored by cloud observers.
161    #[serde(default)]
162    #[builder(default)]
163    pub observe_all_namespaces: bool,
164    /// Public endpoint URLs for exposed resources (optional override).
165    ///
166    /// Use this only when a caller already knows the public URL. Managed public
167    /// endpoint flows should prefer `domain_metadata` plus controller-reported
168    /// load balancer outputs so DNS, certificate renewal, and route readiness
169    /// stay tied to the resource state.
170    ///
171    /// If not set, platforms determine public endpoint URLs from other sources:
172    /// - Managed DNS/TLS flows: `domain_metadata` FQDN or load balancer DNS
173    /// - Local: `http://localhost:{allocated_port}`
174    /// - Custom or disabled exposure: no public endpoint URL unless a controller reports one
175    ///
176    /// Outer key: resource ID. Inner key: endpoint name. Value: public URL.
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub public_endpoints: Option<HashMap<String, HashMap<String, String>>>,
179    /// Domain metadata for auto-managed public resources.
180    ///
181    /// Contains generated hostnames, DNS record state, certificate material,
182    /// and renewal markers for platforms that use managed public endpoints.
183    /// Kubernetes uses this only when its exposure mode is `generated`; BYO and
184    /// disabled Kubernetes exposure do not receive managed domain metadata.
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub domain_metadata: Option<DomainMetadata>,
187    /// OTLP observability configuration for log export (optional).
188    ///
189    /// When set, worker runtimes export captured application logs through this
190    /// endpoint. Container orchestrators may use it for their node-level log
191    /// collectors, but app container configs must not receive the auth header.
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub monitoring: Option<OtlpConfig>,
194    /// Manager base URL (e.g., "https://manager.alien.dev").
195    ///
196    /// The manager IS the container registry — its `/v2/` endpoint serves as
197    /// the OCI Distribution API. Controllers derive the proxy host from this
198    /// to configure pull auth (RegistryCredentials, imagePullSecrets).
199    ///
200    /// When None (e.g., `alien dev`), controllers use image URIs as-is.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub manager_url: Option<String>,
203    /// Exact audience for bounded runtime identity exchange. When present,
204    /// runtimes must use identity exchange and cannot fall back to stored tokens.
205    /// Absence preserves the legacy mode for installs awaiting migration.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub runtime_identity_audience: Option<String>,
208    /// Deployment token for pull authentication with the manager's registry.
209    ///
210    /// Used by controllers to configure registry credentials so cloud platforms
211    /// and K8s can pull images from the manager's `/v2/` endpoint.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub deployment_token: Option<String>,
214    /// Native image registry host+prefix for platforms that require it.
215    ///
216    /// Lambda (ECR) and Cloud Run (GAR) require native registry URIs. Other
217    /// runtimes, including Azure Container Apps, pull through the manager's
218    /// registry proxy.
219    ///
220    /// Derived by the manager from the artifact registry binding:
221    /// - ECR: `{account_id}.dkr.ecr.{region}.amazonaws.com/{repository_prefix}`
222    /// - GAR: `{region}-docker.pkg.dev/{project_id}/{repository_name}`
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub native_image_host: Option<String>,
225    /// Operator requests to replace a replica's persistent volume with a new
226    /// volume made from a snapshot. A container controller performs each
227    /// request once, identified by its `request_id`, and reports it in
228    /// `ContainerOutputs.volumes`. Only a volume that a controller reports in
229    /// `ContainerOutputs.volumes` can be the target of a request.
230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
231    #[builder(default)]
232    pub volume_restores: Vec<VolumeRestoreRequest>,
233    /// How the deletion this run performs treats data. Under `Erase`, controllers also
234    /// delete what they would otherwise keep after the resource is gone, such as a
235    /// container's final volume snapshots.
236    /// Not serialized: deletion sets it from the policy persisted in runtime metadata,
237    /// so a stored configuration cannot request an erase.
238    #[serde(skip)]
239    #[cfg_attr(feature = "openapi", schema(ignore))]
240    #[builder(default)]
241    pub deletion_policy: DeletionPolicy,
242}
243
244/// A value the manager holds, named by slot, with the digest the sender expects.
245///
246/// The slot is `env:NAME` for an environment variable, `input:ID` for a stack
247/// input, or `cenv.<container>.<NAME>` for a dynamic container's variable. An
248/// input's stored value is the JSON text of the input value.
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
250#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
251#[serde(rename_all = "camelCase")]
252pub struct ValueSlotRef {
253    /// `env:NAME`, `input:ID` or `cenv.<container>.<NAME>`.
254    pub slot: String,
255    /// Whether the value is a secret. The manager checks it against the stored kind.
256    pub kind: EnvironmentVariableType,
257    /// Keyed digest of the value, as lowercase hex.
258    pub digest: String,
259    /// Variable name, repeated for display. The slot decides the name.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub env_name: Option<String>,
262    /// Target resource patterns for an environment variable. `None` means all resources.
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub targets: Option<Vec<String>>,
265}
266
267/// Replace one replica's persistent volume with a new volume made from a snapshot.
268///
269/// The controller stops the replica, snapshots the volume it is about to
270/// replace (so the restore can be undone), creates the new volume in the same
271/// zone, starts the replica on it, and deletes the replaced volume.
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
274#[serde(rename_all = "camelCase")]
275pub struct VolumeRestoreRequest {
276    /// Unique ID of this request. A controller performs each request once.
277    pub request_id: String,
278    /// ID of the container resource that owns the volume
279    pub resource_id: String,
280    /// Replica ordinal whose volume is replaced
281    pub ordinal: u32,
282    /// Cloud ID of the snapshot to restore: an EBS snapshot ID, a Compute
283    /// Engine snapshot name, or an Azure snapshot resource ID
284    pub snapshot_id: String,
285}
286
287/// Resource-attribute key marking OTLP telemetry as Alien system-component
288/// output (infrastructure daemons and internal runtimes) rather than user
289/// workload. Log consumers — the CLI log viewer and the dashboard — hide
290/// telemetry carrying this attribute by default. The value is the string
291/// `"true"`.
292///
293/// System components set this on their own telemetry's resource attributes so
294/// consumers can filter generically, without enumerating component names.
295pub const ALIEN_SYSTEM_RESOURCE_ATTRIBUTE: &str = "alien.system";
296
297/// Prefix that marks one captured output line of a Worker as Alien system output.
298///
299/// The worker runtime strips it from the line and records
300/// [`ALIEN_SYSTEM_RESOURCE_ATTRIBUTE`] on the exported record. Alien components that run as a
301/// Worker's application write it at the start of every line they print. Like the attribute, it
302/// only hides a line by default; it grants nothing.
303pub const ALIEN_SYSTEM_LOG_LINE_PREFIX: &str = "\u{1e}ALIEN_SYSTEM\u{1f}";
304
305/// OTLP log export configuration for a deployment.
306///
307/// When set, injected compute runtimes export captured application logs
308/// through the given endpoint via OTLP/HTTP; which resources are injected
309/// is platform-dependent. Workers read auth headers from a runtime-only
310/// secret. Runtime-less Containers and Daemons receive standard OTEL auth
311/// variables only at the final hosting boundary: Local passes them directly
312/// to the process and Kubernetes projects them from a per-workload Secret.
313#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
314#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
315#[serde(rename_all = "camelCase")]
316pub struct OtlpConfig {
317    /// Full OTLP logs endpoint URL.
318    /// Example: "https://<manager-host>/v1/logs"
319    pub logs_endpoint: String,
320    /// Auth header value in "key=value,..." format.
321    /// Example: "authorization=Bearer <write-token>"
322    pub logs_auth_header: String,
323    /// Full OTLP metrics endpoint URL (optional).
324    /// When set, the worker runtime exports its own VM/container orchestration metrics here.
325    /// Example: "https://api.axiom.co/v1/metrics"
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub metrics_endpoint: Option<String>,
328    /// Auth header value for the metrics endpoint in "key=value,..." format (optional).
329    ///
330    /// When absent, `logs_auth_header` is reused for metrics -- suitable when the same
331    /// credential covers both signals. When present (e.g. Axiom with separate datasets),
332    /// this value is used exclusively for metrics.
333    ///
334    /// Example: "authorization=Bearer <token>,x-axiom-dataset=<metrics-dataset>"
335    #[serde(skip_serializing_if = "Option::is_none")]
336    pub metrics_auth_header: Option<String>,
337    /// Resource attributes attached to every OTLP signal emitted for this deployment.
338    ///
339    /// Platform managers use this for stable identity such as `alien.workspace_id`,
340    /// `alien.project_id`, `alien.deployment_group_id`, and `alien.deployment_id`.
341    /// Runtime-specific resource attributes such as `service.name` remain owned by
342    /// the runtime/exporter.
343    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
344    pub resource_attributes: HashMap<String, String>,
345}
346
347#[cfg(test)]
348mod input_values_tests {
349    use super::*;
350
351    /// Older actors serialize configs without the field; it must deserialize
352    /// to an empty map, and an empty map must not serialize at all.
353    #[test]
354    fn input_values_default_to_empty_and_stay_off_the_wire() {
355        let json = serde_json::json!({
356            "stackSettings": serde_json::to_value(crate::StackSettings::default()).unwrap(),
357            "environmentVariables": {
358                "variables": [],
359                "hash": "hash",
360                "createdAt": "2026-01-01T00:00:00Z",
361            },
362            "externalBindings": {},
363        });
364        let config: DeploymentConfig =
365            serde_json::from_value(json).expect("old shape deserializes");
366        assert!(config.input_values.is_empty());
367        assert!(config.stored_secret_input_ids.is_none());
368
369        let round = serde_json::to_value(&config).expect("serializes");
370        assert!(round.get("storedSecretInputIds").is_none());
371        assert!(
372            round.get("inputValues").is_none(),
373            "empty map must not serialize"
374        );
375    }
376    #[test]
377    fn stored_secret_presence_roundtrips_without_values_or_gate_answers() {
378        let mut config = DeploymentConfig::builder()
379            .stack_settings(StackSettings::default())
380            .environment_variables(EnvironmentVariablesSnapshot {
381                variables: vec![],
382                hash: String::new(),
383                created_at: String::new(),
384            })
385            .allow_frozen_changes(false)
386            .external_bindings(ExternalBindings::default())
387            .build();
388        assert!(config.stored_secret_input_ids.is_none());
389        config.stored_secret_input_ids = Some(Vec::new());
390        let empty = serde_json::to_value(&config).unwrap();
391        assert_eq!(empty["storedSecretInputIds"], serde_json::json!([]));
392        assert_eq!(
393            serde_json::from_value::<DeploymentConfig>(empty)
394                .unwrap()
395                .stored_secret_input_ids,
396            Some(Vec::new())
397        );
398        config.stored_secret_input_ids =
399            Some(vec!["apiKey".to_string(), "enableFeature".to_string()]);
400        let wire = serde_json::to_value(&config).unwrap();
401        assert_eq!(
402            wire["storedSecretInputIds"],
403            serde_json::json!(["apiKey", "enableFeature"])
404        );
405        assert!(wire.get("inputValues").is_none());
406        let decoded: DeploymentConfig = serde_json::from_value(wire.clone()).unwrap();
407        assert_eq!(
408            decoded.stored_secret_input_ids,
409            config.stored_secret_input_ids
410        );
411        assert_eq!(serde_json::to_value(decoded.clone()).unwrap(), wire);
412        assert!(decoded.input_values.is_empty());
413        for default in [false, true] {
414            let input: crate::StackInputDefinition = serde_json::from_value(serde_json::json!({
415                "id": "enableFeature", "kind": "boolean", "providedBy": ["deployer"],
416                "required": false, "label": "Enable feature", "description": "", "default": crate::StackInputDefaultValue::Boolean(default)
417            }))
418            .unwrap();
419            assert_eq!(
420                crate::gate_resolves_true(
421                    &[input],
422                    "enableFeature",
423                    &decoded.input_values,
424                    "worker",
425                    crate::Platform::Aws
426                )
427                .unwrap(),
428                default
429            );
430        }
431        assert!(crate::gate_resolves_true(
432            &[],
433            "enableFeature",
434            &decoded.input_values,
435            "worker",
436            crate::Platform::Aws
437        )
438        .is_err());
439    }
440
441    fn deployment_config_with_cluster(
442        cluster_image: Option<serde_json::Value>,
443    ) -> serde_json::Value {
444        let config = DeploymentConfig::builder()
445            .stack_settings(StackSettings::default())
446            .environment_variables(EnvironmentVariablesSnapshot {
447                variables: vec![],
448                hash: String::new(),
449                created_at: String::new(),
450            })
451            .allow_frozen_changes(false)
452            .external_bindings(ExternalBindings::default())
453            .compute_backend(crate::ComputeBackend::Horizon(crate::HorizonConfig {
454                url: "https://horizon.example.com".to_string(),
455                horizon_machine_image: None,
456                clusters: HashMap::from([(
457                    "compute".to_string(),
458                    crate::HorizonClusterConfig {
459                        machine_url: None,
460                        cluster_id: "cluster-1".to_string(),
461                        management_token: "hm_test".to_string(),
462                        runtime_identity: None,
463                        horizon_machine_image: cluster_image
464                            .map(|image| serde_json::from_value(image).unwrap()),
465                    },
466                )]),
467            }))
468            .build();
469        serde_json::to_value(&config).unwrap()
470    }
471
472    fn machine_image(version: &str) -> serde_json::Value {
473        serde_json::json!({
474            "channel": "stable",
475            "machineImageVersion": version,
476            "horizondVersion": version,
477            "gitSha": "abc123",
478            "createdAt": "2026-01-01T00:00:00Z",
479            "baseImage": { "name": "linux", "version": "1" },
480            "horizondArtifacts": {}
481        })
482    }
483
484    /// A deployment config written before clusters could carry a machine image, as managers
485    /// receive and store it, reads back with no cluster image.
486    #[test]
487    fn deployment_config_without_cluster_machine_image_reads_as_before() {
488        let wire = deployment_config_with_cluster(None);
489        let cluster = &wire["computeBackend"]["clusters"]["compute"];
490        assert_eq!(
491            cluster,
492            &serde_json::json!({ "clusterId": "cluster-1", "managementToken": "hm_test" })
493        );
494
495        let config: DeploymentConfig = serde_json::from_value(wire).unwrap();
496        let Some(crate::ComputeBackend::Horizon(horizon)) = config.compute_backend else {
497            panic!("the Horizon backend reads back");
498        };
499        assert_eq!(horizon.clusters["compute"].horizon_machine_image, None);
500    }
501
502    /// The types on the path from the deployment config to a cluster as they were before the
503    /// cluster machine image existed: none of them rejects unknown fields.
504    #[derive(Debug, Deserialize)]
505    #[serde(rename_all = "camelCase")]
506    struct PreviousDeploymentConfig {
507        compute_backend: Option<PreviousComputeBackend>,
508    }
509
510    #[derive(Debug, Deserialize)]
511    #[serde(tag = "type", rename_all = "camelCase")]
512    enum PreviousComputeBackend {
513        Horizon(PreviousHorizonConfig),
514    }
515
516    #[derive(Debug, Deserialize)]
517    #[serde(rename_all = "camelCase")]
518    struct PreviousHorizonConfig {
519        clusters: HashMap<String, PreviousHorizonClusterConfig>,
520    }
521
522    #[derive(Debug, Deserialize, PartialEq)]
523    #[serde(rename_all = "camelCase")]
524    struct PreviousHorizonClusterConfig {
525        cluster_id: String,
526        management_token: String,
527    }
528
529    /// A manager built before the field reads a deployment config that sets it and ignores it.
530    #[test]
531    fn deployment_config_with_cluster_machine_image_reads_in_older_readers() {
532        let wire = deployment_config_with_cluster(Some(machine_image("1")));
533        assert!(wire["computeBackend"]["clusters"]["compute"]["horizonMachineImage"].is_object());
534
535        let previous: PreviousDeploymentConfig = serde_json::from_value(wire.clone())
536            .expect("an older reader must accept a cluster that carries its own image");
537        let Some(PreviousComputeBackend::Horizon(horizon)) = previous.compute_backend else {
538            panic!("the Horizon backend reads back");
539        };
540        assert_eq!(
541            horizon.clusters["compute"],
542            PreviousHorizonClusterConfig {
543                cluster_id: "cluster-1".to_string(),
544                management_token: "hm_test".to_string(),
545            }
546        );
547
548        let current: DeploymentConfig = serde_json::from_value(wire).unwrap();
549        let Some(crate::ComputeBackend::Horizon(horizon)) = current.compute_backend else {
550            panic!("the Horizon backend reads back");
551        };
552        assert_eq!(
553            horizon
554                .machine_image_for("compute")
555                .map(|image| image.machine_image_version.as_str()),
556            Some("1")
557        );
558    }
559}
560
561impl DeploymentConfig {
562    /// The reference a workload image is pulled from: the release's reference, moved to the
563    /// installation's site registry when one is configured.
564    pub fn workload_image(&self, image: &str) -> String {
565        match self.image_registry.as_deref().filter(|r| !r.is_empty()) {
566            Some(registry) => crate::image_rewrite::rewrite_to_site_registry(image, registry),
567            None => image.to_string(),
568        }
569    }
570}