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