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