Skip to main content

mz_cloud_resources/crd/
materialize.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10// The doc comments here become the descriptions in the generated CRD, which the
11// docs site renders through Hugo, so they contain shortcodes like
12// `{{<warning>}}`. Rustdoc reads the inner `<warning>` as an HTML tag and
13// reports it unclosed whenever a shortcode spans more than one Markdown
14// paragraph.
15#![allow(rustdoc::invalid_html_tags)]
16
17use std::collections::BTreeMap;
18use std::time::Duration;
19
20use k8s_openapi::{
21    api::core::v1::{EnvVar, Probe, ResourceRequirements},
22    apimachinery::pkg::{
23        api::resource::Quantity,
24        apis::meta::v1::{Condition, Time},
25    },
26    jiff::Timestamp,
27};
28use kube::{CustomResource, Resource, ResourceExt};
29use schemars::JsonSchema;
30use semver::Version;
31use serde::{Deserialize, Serialize};
32use sha2::{Digest, Sha256};
33use tracing::warn;
34use uuid::Uuid;
35
36use crate::crd::{ManagedResource, MaterializeCertSpec, is_valid_resource_id, new_resource_id};
37use mz_server_core::listeners::AuthenticatorKind;
38
39pub const LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION: &str =
40    "materialize.cloud/last-known-active-generation";
41/// Sets the resource ID of a new Materialize resource, so that a resource
42/// recreated on existing data, for example after a restore, keeps the names of
43/// the resource it replaces.
44///
45/// The operator refuses an ID that another Materialize resource still has.
46/// The prior resource must be entirely cleaned up (`--cascade=foreground`)
47/// before redeploying. Otherwise, you may hit collisions with resources that
48/// are actively being deleted.
49pub const LAST_KNOWN_RESOURCE_ID_ANNOTATION: &str = "materialize.cloud/last-known-resource-id";
50pub const FORCE_ROLLOUT_ANNOTATION: &str = "materialize.cloud/force-rollout";
51
52/// Values for a Materialize resource's initial status, taken from the old
53/// resource's status when a resource is recreated on existing data.
54///
55/// These are read from annotations only when the status is first created.
56/// Changing the annotations afterward has no effect. An invalid value is
57/// logged and ignored, as if the annotation weren't set.
58#[derive(Clone, Debug, Default, PartialEq, Eq)]
59pub struct InitialStatusAnnotations {
60    /// From [`LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION`]. Without it, the
61    /// environment would crash loop indefinitely, as its catalog durably
62    /// recorded a greater generation.
63    pub active_generation: Option<u64>,
64    /// From [`LAST_KNOWN_RESOURCE_ID_ANNOTATION`]. Without it, the resource
65    /// gets a new random ID, and so new names for everything named after it,
66    /// such as its services.
67    pub resource_id: Option<String>,
68}
69
70impl InitialStatusAnnotations {
71    pub fn parse(annotations: &BTreeMap<String, String>) -> Result<Self, anyhow::Error> {
72        let active_generation = annotations
73            .get(LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION)
74            .map(|generation| {
75                generation.parse().map_err(|_| {
76                    anyhow::anyhow!(
77                        "invalid {LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION} annotation {generation:?}: must be a non-negative integer"
78                    )
79                })
80            })
81            .transpose()?;
82        let resource_id = annotations
83            .get(LAST_KNOWN_RESOURCE_ID_ANNOTATION)
84            .map(|resource_id| {
85                if is_valid_resource_id(resource_id) {
86                    Ok(resource_id.clone())
87                } else {
88                    Err(anyhow::anyhow!(
89                        "invalid {LAST_KNOWN_RESOURCE_ID_ANNOTATION} annotation {resource_id:?}: must be the status.resourceId of a previous Materialize resource (10 lowercase letters or digits)"
90                    ))
91                }
92            })
93            .transpose()?;
94        Ok(Self {
95            active_generation,
96            resource_id,
97        })
98    }
99}
100
101#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema)]
102pub enum MaterializeRolloutStrategy {
103    /// Create a new generation of pods, leaving the old generation around until the
104    /// new ones are ready to take over.
105    /// This minimizes downtime, and is what almost everyone should use.
106    #[default]
107    WaitUntilReady,
108
109    /// Create a new generation of pods, leaving the old generation as the serving generation
110    /// until the user manually promotes the new generation.
111    ///
112    /// When using `ManuallyPromote`, the new generation can be promoted at any
113    /// time, even if it has dataflows that are not fully caught up, by setting
114    /// `forcePromote` to the current rollout identifier: in `v1`, the value of
115    /// `status.requestedRolloutHash`; in `v1alpha1`, the `requestRollout` value
116    /// in the spec.
117    ///
118    /// To minimize downtime, promotion should occur when the new generation
119    /// has caught up to the prior generation. To determine if the new
120    /// generation has caught up, consult the `UpToDate` condition in the
121    /// status of the Materialize Resource. If the condition's reason is
122    /// `ReadyToPromote` the new generation is ready to promote.
123    ///
124    /// {{<warning>}}
125    /// Do not leave new generations unpromoted indefinitely.
126    ///
127    /// The new generation keeps open read holds which prevent compaction. Once promoted or
128    /// cancelled, those read holds are released. If left unpromoted for an extended time, this
129    /// data can build up, and can cause extreme deletion load on the metadata backend database
130    /// when finally promoted or cancelled.
131    ///
132    /// To guard against this, a rollout that remains in progress longer
133    /// than `rolloutRequestTimeout` (default 24h) is automatically
134    /// cancelled.
135    /// {{</warning>}}
136    ManuallyPromote,
137
138    /// {{<warning>}}
139    /// THIS WILL CAUSE YOUR MATERIALIZE INSTANCE TO BE UNAVAILABLE FOR SOME TIME!!!
140    ///
141    /// This strategy should ONLY be used by customers with physical hardware who do not have
142    /// enough hardware for the `WaitUntilReady` strategy. If you think you want this, please
143    /// consult with Materialize engineering to discuss your situation.
144    /// {{</warning>}}
145    ///
146    /// Tear down the old generation of pods and promote the new generation of pods immediately,
147    /// without waiting for the new generation of pods to be ready.
148    ImmediatelyPromoteCausingDowntime,
149}
150
151/// Default for [`RolloutRequestTimeout`]. A new generation that sits
152/// un-promoted holds back compaction via read holds, and promoting it
153/// after a long delay can cause incident-inducing load; 24h is a
154/// conservative upper bound on how long any rollout should take.
155pub const DEFAULT_ROLLOUT_REQUEST_TIMEOUT: &str = "24h";
156
157/// The maximum time [`v1alpha1::MaterializeSpec::rollout_request_timeout`] allows a
158/// rollout to remain in progress.
159///
160/// A transparent wrapper around the duration string whose [`Default`] is
161/// [`DEFAULT_ROLLOUT_REQUEST_TIMEOUT`]. Routing the default through `Default`
162/// keeps a single source of truth: the derived `Default` for
163/// [`v1alpha1::MaterializeSpec`], serde's `#[serde(default)]` (applied when the field
164/// is omitted on deserialize), and the schema default surfaced in the
165/// generated CRD (so the API server fills it in and `kubectl explain` shows
166/// it) all resolve to the same value.
167#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)]
168#[serde(transparent)]
169pub struct RolloutRequestTimeout(pub String);
170
171impl Default for RolloutRequestTimeout {
172    fn default() -> Self {
173        RolloutRequestTimeout(DEFAULT_ROLLOUT_REQUEST_TIMEOUT.to_owned())
174    }
175}
176
177/// A key in a ConfigMap or Secret whose value holds one or more PEM-encoded
178/// CA certificates.
179///
180/// Set exactly one of `configMapKeyRef` or `secretKeyRef`. The ConfigMap or
181/// Secret must be in the same namespace as the Materialize resource. Only the
182/// referenced key is mounted into the pods.
183#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)]
184#[serde(rename_all = "camelCase")]
185pub struct AdditionalTrustBundle {
186    /// A key in a ConfigMap.
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub config_map_key_ref: Option<TrustBundleKeyRef>,
189    /// A key in a Secret.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub secret_key_ref: Option<TrustBundleKeyRef>,
192}
193
194impl AdditionalTrustBundle {
195    /// The ConfigMap or Secret key holding the certificates. Errors unless
196    /// exactly one of `configMapKeyRef` and `secretKeyRef` is set.
197    pub fn source(&self) -> Result<TrustBundleSource<'_>, anyhow::Error> {
198        match (&self.config_map_key_ref, &self.secret_key_ref) {
199            (Some(key_ref), None) => Ok(TrustBundleSource::ConfigMap(key_ref)),
200            (None, Some(key_ref)) => Ok(TrustBundleSource::Secret(key_ref)),
201            (Some(_), Some(_)) => {
202                anyhow::bail!("set only one of configMapKeyRef and secretKeyRef, not both")
203            }
204            (None, None) => anyhow::bail!("set one of configMapKeyRef or secretKeyRef"),
205        }
206    }
207}
208
209/// Where an [`AdditionalTrustBundle`] holds its certificates.
210#[derive(Clone, Copy, Debug, PartialEq)]
211pub enum TrustBundleSource<'a> {
212    ConfigMap(&'a TrustBundleKeyRef),
213    Secret(&'a TrustBundleKeyRef),
214}
215
216/// A key in a ConfigMap or Secret.
217#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)]
218#[serde(rename_all = "camelCase")]
219pub struct TrustBundleKeyRef {
220    /// The name of the ConfigMap or Secret.
221    pub name: String,
222    /// The key whose value holds the PEM-encoded certificates.
223    pub key: String,
224}
225
226pub mod v1alpha1 {
227    use super::*;
228
229    #[derive(
230        CustomResource,
231        Clone,
232        Debug,
233        Default,
234        PartialEq,
235        Deserialize,
236        Serialize,
237        JsonSchema
238    )]
239    #[serde(rename_all = "camelCase")]
240    #[kube(
241        namespaced,
242        group = "materialize.cloud",
243        version = "v1alpha1",
244        kind = "Materialize",
245        singular = "materialize",
246        plural = "materializes",
247        shortname = "mzs",
248        status = "MaterializeStatus",
249        printcolumn = r#"{"name": "ImageRefRunning", "type": "string", "description": "Reference to the Docker image that is currently in use.", "jsonPath": ".status.lastCompletedRolloutEnvironmentdImageRef", "priority": 1}"#,
250        printcolumn = r#"{"name": "ImageRefToDeploy", "type": "string", "description": "Reference to the Docker image which will be deployed on the next rollout.", "jsonPath": ".spec.environmentdImageRef", "priority": 1}"#,
251        printcolumn = r#"{"name": "UpToDate", "type": "string", "description": "Whether the spec has been applied", "jsonPath": ".status.conditions[?(@.type==\"UpToDate\")].status", "priority": 1}"#
252    )]
253    pub struct MaterializeSpec {
254        /// The environmentd image to run.
255        pub environmentd_image_ref: String,
256        /// Extra args to pass to the environmentd binary.
257        pub environmentd_extra_args: Option<Vec<String>>,
258        /// Extra environment variables to pass to the environmentd binary.
259        pub environmentd_extra_env: Option<Vec<EnvVar>>,
260        /// {{<warning>}}
261        /// Deprecated.
262        ///
263        /// Use `service_account_annotations` to set "eks.amazonaws.com/role-arn" instead.
264        /// {{</warning>}}
265        ///
266        /// If running in AWS, override the IAM role to use to give
267        /// environmentd access to the persist S3 bucket.
268        #[kube(deprecated)]
269        pub environmentd_iam_role_arn: Option<String>,
270        /// If running in AWS, override the IAM role to use to support
271        /// the CREATE CONNECTION feature.
272        pub environmentd_connection_role_arn: Option<String>,
273        /// Resource requirements for the environmentd pod.
274        pub environmentd_resource_requirements: Option<ResourceRequirements>,
275        /// Amount of disk to allocate, if a storage class is provided.
276        pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
277        /// Readiness probe for the environmentd container.
278        ///
279        /// Fields set here are overlaid onto the operator's default probe, so only the fields
280        /// being changed need to be set. If no handler (`exec`, `grpc`, `httpGet`, `tcpSocket`)
281        /// is set, the default TCP check against environmentd's SQL port is kept.
282        #[serde(skip_serializing_if = "Option::is_none")]
283        pub environmentd_readiness_probe: Option<Probe>,
284        /// Liveness probe for the environmentd container.
285        ///
286        /// Fields set here are overlaid onto the operator's default probe, so only the fields
287        /// being changed need to be set. If no handler (`exec`, `grpc`, `httpGet`, `tcpSocket`)
288        /// is set, the default TCP check against environmentd's SQL port is kept.
289        #[serde(skip_serializing_if = "Option::is_none")]
290        pub environmentd_liveness_probe: Option<Probe>,
291        /// Startup probe for the environmentd container. Liveness and readiness checks are held
292        /// off until it succeeds, so it can allow a long startup without loosening the liveness
293        /// probe.
294        ///
295        /// No startup probe runs unless this field or the operator's default sets one. Fields set
296        /// here are overlaid onto the operator's default probe, so only the fields being changed
297        /// need to be set. If no handler (`exec`, `grpc`, `httpGet`, `tcpSocket`) is set, the
298        /// default TCP check against environmentd's SQL port is used.
299        #[serde(skip_serializing_if = "Option::is_none")]
300        pub environmentd_startup_probe: Option<Probe>,
301        /// Resource requirements for the balancerd pod.
302        pub balancerd_resource_requirements: Option<ResourceRequirements>,
303        /// The name of an externally managed ConfigMap in this namespace containing
304        /// balancerd dynamic configuration as a JSON object in `config.json`.
305        /// Changes to its contents are applied at runtime. Changing this reference
306        /// restarts balancerd pods but does not trigger an environmentd rollout.
307        #[serde(skip_serializing_if = "Option::is_none")]
308        pub balancerd_configmap_name: Option<String>,
309        /// Resource requirements for the console pod.
310        pub console_resource_requirements: Option<ResourceRequirements>,
311        /// Number of balancerd pods to create.
312        pub balancerd_replicas: Option<i32>,
313        /// Leave the balancerd Deployment's replica count to an external
314        /// autoscaler, such as a HorizontalPodAutoscaler. `balancerd_replicas`
315        /// then only seeds the count when the Deployment is first created.
316        #[serde(skip_serializing_if = "Option::is_none")]
317        pub balancerd_externally_scaled: Option<bool>,
318        /// Number of console pods to create.
319        pub console_replicas: Option<i32>,
320
321        /// Name of the kubernetes service account to use.
322        /// If not set, we will create one with the same name as this Materialize object.
323        pub service_account_name: Option<String>,
324        /// Annotations to apply to the service account.
325        ///
326        /// Annotations on service accounts are commonly used by cloud providers for IAM.
327        /// AWS uses "eks.amazonaws.com/role-arn".
328        /// Azure uses "azure.workload.identity/client-id", but
329        /// additionally requires "azure.workload.identity/use": "true" on the pods.
330        pub service_account_annotations: Option<BTreeMap<String, String>>,
331        /// Labels to apply to the service account.
332        pub service_account_labels: Option<BTreeMap<String, String>>,
333        /// Annotations to apply to the pods.
334        pub pod_annotations: Option<BTreeMap<String, String>>,
335        /// Labels to apply to the pods.
336        pub pod_labels: Option<BTreeMap<String, String>>,
337
338        /// When changes are made to the environmentd resources (either via
339        /// modifying fields in the spec here or by deploying a new
340        /// orchestratord version which changes how resources are generated),
341        /// existing environmentd processes won't be automatically restarted.
342        /// In order to trigger a restart, the request_rollout field should be
343        /// set to a new (random) value. Once the rollout completes, the value
344        /// of `status.lastCompletedRolloutRequest` will be set to this value
345        /// to indicate completion.
346        ///
347        /// Defaults to a random value in order to ensure that the first
348        /// generation rollout is automatically triggered.
349        #[serde(default)]
350        pub request_rollout: Uuid,
351        /// If `forcePromote` is set to the same value as `requestRollout`, the
352        /// current rollout will skip waiting for clusters in the new
353        /// generation to rehydrate before promoting the new environmentd to
354        /// leader.
355        #[serde(default)]
356        pub force_promote: String,
357        /// This value will be written to an annotation in the generated
358        /// environmentd statefulset, in order to force the controller to
359        /// detect the generated resources as changed even if no other changes
360        /// happened. This can be used to force a rollout to a new generation
361        /// even without making any meaningful changes, by setting it to the
362        /// same value as `requestRollout`.
363        #[serde(default)]
364        pub force_rollout: Uuid,
365        /// {{<warning>}}
366        /// Deprecated and ignored. Use `rolloutStrategy` instead.
367        /// {{</warning>}}
368        #[kube(deprecated)]
369        #[serde(default)]
370        pub in_place_rollout: bool,
371        /// Rollout strategy to use when upgrading this Materialize instance.
372        #[serde(default)]
373        pub rollout_strategy: MaterializeRolloutStrategy,
374        /// The maximum amount of time a rollout may remain in progress before
375        /// it is automatically cancelled.
376        ///
377        /// While a rollout is in progress, the new generation of `environmentd`
378        /// runs in a read-only, un-promoted state and holds back compaction via
379        /// read holds. Leaving it in this state for too long can cause
380        /// incident-inducing load when it is eventually promoted, so the
381        /// operator cancels the rollout once this timeout is exceeded: the new
382        /// generation is torn down and the previously-active generation
383        /// continues serving. A new rollout can then be triggered by setting
384        /// `requestRollout` to a new value.
385        ///
386        /// This does not apply to the `ImmediatelyPromoteCausingDowntime`
387        /// rollout strategy or to force-promoted rollouts, since by the time
388        /// those are in progress the old generation may already be gone.
389        ///
390        /// The value is parsed as a human-readable duration, e.g. `24h`,
391        /// `90m`, or `1h 30m`. Defaults to [`DEFAULT_ROLLOUT_REQUEST_TIMEOUT`]
392        /// when omitted (the API server fills it in); an unparseable value also
393        /// falls back to that default.
394        #[serde(default)]
395        pub rollout_request_timeout: RolloutRequestTimeout,
396        /// The name of a secret containing `metadata_backend_url` and `persist_backend_url`.
397        /// It may also contain `external_login_password_mz_system`, which will be used as
398        /// the password for the `mz_system` user if `authenticatorKind` is `Password`,
399        /// `Sasl`, or `Oidc`.
400        pub backend_secret_name: String,
401        /// How to authenticate with Materialize.
402        #[serde(default)]
403        pub authenticator_kind: AuthenticatorKind,
404        /// Whether to enable role based access control. Defaults to false.
405        #[serde(default)]
406        pub enable_rbac: bool,
407
408        /// The value used by environmentd (via the --environment-id flag) to
409        /// uniquely identify this instance. Must be globally unique, and
410        /// is required if a license key is not provided.
411        /// NOTE: This value MUST NOT be changed in an existing instance,
412        /// since it affects things like the way data is stored in the persist
413        /// backend.
414        #[serde(default)]
415        pub environment_id: Uuid,
416
417        /// The name of a ConfigMap containing system parameters in JSON format.
418        /// The ConfigMap must contain a `system-params.json` key whose value
419        /// is a valid JSON object containing valid system parameters.
420        ///
421        /// Run `SHOW ALL` in SQL to see a subset of configurable system parameters.
422        ///
423        /// Example ConfigMap:
424        /// ```yaml
425        /// data:
426        ///   system-params.json: |
427        ///     {
428        ///       "max_connections": 1000
429        ///     }
430        /// ```
431        pub system_parameter_configmap_name: Option<String>,
432        /// PEM-encoded CA certificates that environmentd and clusterd trust for
433        /// outbound TLS connections, in addition to the CAs in their image.
434        /// Use this when an OIDC provider, a source, a sink, or object storage
435        /// presents a certificate signed by a private or self-signed CA.
436        ///
437        /// environmentd and clusterd read the certificates when they start, so
438        /// changes to the contents of the ConfigMap or Secret take effect the
439        /// next time their pods restart.
440        #[serde(skip_serializing_if = "Option::is_none")]
441        pub additional_trust_bundle: Option<AdditionalTrustBundle>,
442
443        /// The configuration for generating an x509 certificate using cert-manager for balancerd
444        /// to present to incoming connections.
445        /// The `dnsNames` and `issuerRef` fields are required.
446        pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
447        /// The configuration for generating an x509 certificate using cert-manager for the console
448        /// to present to incoming connections.
449        /// The `dnsNames` and `issuerRef` fields are required.
450        /// Not yet implemented.
451        pub console_external_certificate_spec: Option<MaterializeCertSpec>,
452        /// The cert-manager Issuer or ClusterIssuer to use for database internal communication.
453        /// The `issuerRef` field is required.
454        /// This currently is only used for environmentd, but will eventually support clusterd.
455        /// Not yet implemented.
456        pub internal_certificate_spec: Option<MaterializeCertSpec>,
457    }
458
459    impl Materialize {
460        pub fn backend_secret_name(&self) -> String {
461            self.spec.backend_secret_name.clone()
462        }
463
464        pub fn namespace(&self) -> String {
465            self.meta().namespace.clone().unwrap()
466        }
467
468        pub fn create_service_account(&self) -> bool {
469            self.spec.service_account_name.is_none()
470        }
471
472        pub fn service_account_name(&self) -> String {
473            self.spec
474                .service_account_name
475                .clone()
476                .unwrap_or_else(|| self.name_unchecked())
477        }
478
479        pub fn role_name(&self) -> String {
480            self.name_unchecked()
481        }
482
483        pub fn role_binding_name(&self) -> String {
484            self.name_unchecked()
485        }
486
487        pub fn environmentd_statefulset_name(&self, generation: u64) -> String {
488            self.name_prefixed(&format!("environmentd-{generation}"))
489        }
490
491        pub fn environmentd_app_name(&self) -> String {
492            "environmentd".to_owned()
493        }
494
495        pub fn environmentd_service_name(&self) -> String {
496            self.name_prefixed("environmentd")
497        }
498
499        pub fn environmentd_service_internal_fqdn(&self) -> String {
500            format!(
501                "{}.{}.svc.cluster.local",
502                self.environmentd_service_name(),
503                self.meta().namespace.as_ref().unwrap()
504            )
505        }
506
507        pub fn environmentd_generation_service_name(&self, generation: u64) -> String {
508            self.name_prefixed(&format!("environmentd-{generation}"))
509        }
510
511        pub fn balancerd_app_name(&self) -> String {
512            "balancerd".to_owned()
513        }
514
515        pub fn environmentd_certificate_name(&self) -> String {
516            self.name_prefixed("environmentd-external")
517        }
518
519        pub fn environmentd_certificate_secret_name(&self) -> String {
520            self.name_prefixed("environmentd-tls")
521        }
522
523        pub fn balancerd_deployment_name(&self) -> String {
524            self.name_prefixed("balancerd")
525        }
526
527        pub fn balancerd_service_name(&self) -> String {
528            self.name_prefixed("balancerd")
529        }
530
531        pub fn console_app_name(&self) -> String {
532            "console".to_owned()
533        }
534
535        pub fn balancerd_external_certificate_name(&self) -> String {
536            self.name_prefixed("balancerd-external")
537        }
538
539        pub fn balancerd_external_certificate_secret_name(&self) -> String {
540            self.name_prefixed("balancerd-external-tls")
541        }
542
543        pub fn balancerd_replicas(&self) -> i32 {
544            self.spec.balancerd_replicas.unwrap_or(2)
545        }
546
547        pub fn console_replicas(&self) -> i32 {
548            self.spec.console_replicas.unwrap_or(2)
549        }
550
551        pub fn console_configmap_name(&self) -> String {
552            self.name_prefixed("console")
553        }
554
555        pub fn console_deployment_name(&self) -> String {
556            self.name_prefixed("console")
557        }
558
559        pub fn console_service_name(&self) -> String {
560            self.name_prefixed("console")
561        }
562
563        pub fn console_external_certificate_name(&self) -> String {
564            self.name_prefixed("console-external")
565        }
566
567        pub fn console_external_certificate_secret_name(&self) -> String {
568            self.name_prefixed("console-external-tls")
569        }
570
571        pub fn persist_pubsub_service_name(&self, generation: u64) -> String {
572            self.name_prefixed(&format!("persist-pubsub-{generation}"))
573        }
574
575        pub fn listeners_configmap_name(&self, generation: u64) -> String {
576            self.name_prefixed(&format!("listeners-{generation}"))
577        }
578
579        pub fn name_prefixed(&self, suffix: &str) -> String {
580            format!("mz{}-{}", self.resource_id(), suffix)
581        }
582
583        pub fn resource_id(&self) -> &str {
584            &self.status.as_ref().unwrap().resource_id
585        }
586
587        pub fn system_parameter_configmap_name(&self) -> Option<String> {
588            self.spec.system_parameter_configmap_name.clone()
589        }
590
591        pub fn environmentd_scratch_volume_storage_requirement(&self) -> Quantity {
592            self.spec
593                .environmentd_scratch_volume_storage_requirement
594                .clone()
595                .unwrap_or_else(|| {
596                    self.spec
597                        .environmentd_resource_requirements
598                        .as_ref()
599                        .and_then(|requirements| {
600                            requirements
601                                .requests
602                                .as_ref()
603                                .or(requirements.limits.as_ref())
604                        })
605                        // TODO: in cloud, we've been defaulting to twice the
606                        // memory limit, but k8s-openapi doesn't seem to
607                        // provide any way to parse Quantity values, so there
608                        // isn't an easy way to do arithmetic on it
609                        .and_then(|requirements| requirements.get("memory").cloned())
610                        // TODO: is there a better default to use here?
611                        .unwrap_or_else(|| Quantity("4096Mi".to_string()))
612                })
613        }
614
615        pub fn environment_id(&self, cloud_provider: &str, region: &str) -> String {
616            format!(
617                "{}-{}-{}-0",
618                cloud_provider, region, self.spec.environment_id,
619            )
620        }
621
622        pub fn requested_reconciliation_id(&self) -> Uuid {
623            self.spec.request_rollout
624        }
625
626        /// The value used to force the generated per-generation resources to
627        /// be detected as changed even when nothing else in the spec changed,
628        /// so that a requested rollout actually creates a new generation of
629        /// pods rather than completing as a no-op.
630        ///
631        /// Combines `spec.forceRollout` with the
632        /// [`FORCE_ROLLOUT_ANNOTATION`] annotation; changing either forces a
633        /// new generation. The annotation exists so that automation (e.g. the
634        /// GCP node upgrade watcher in orchestratord) can force a rollout
635        /// without touching spec fields that may be managed by tools like
636        /// Terraform.
637        pub fn force_rollout_value(&self) -> String {
638            match self
639                .meta()
640                .annotations
641                .as_ref()
642                .and_then(|annotations| annotations.get(FORCE_ROLLOUT_ANNOTATION))
643            {
644                Some(annotation) => format!("{}/{}", self.spec.force_rollout, annotation),
645                None => self.spec.force_rollout.to_string(),
646            }
647        }
648
649        pub fn rollout_requested(&self) -> bool {
650            self.requested_reconciliation_id()
651                != self
652                    .status
653                    .as_ref()
654                    .map_or_else(Uuid::nil, |status| status.last_completed_rollout_request)
655        }
656
657        /// The maximum amount of time a rollout may remain in progress before
658        /// it is automatically cancelled. Parsed from
659        /// [`MaterializeSpec::rollout_request_timeout`], falling back to
660        /// [`DEFAULT_ROLLOUT_REQUEST_TIMEOUT`] when unset or unparseable.
661        pub fn rollout_request_timeout(&self) -> Duration {
662            let timeout = &self.spec.rollout_request_timeout.0;
663            humantime::parse_duration(timeout)
664                .or_else(|e| {
665                    tracing::warn!(
666                        rollout_request_timeout = %timeout,
667                        "failed to parse rolloutRequestTimeout, using default: {e}",
668                    );
669                    humantime::parse_duration(DEFAULT_ROLLOUT_REQUEST_TIMEOUT)
670                })
671                .expect("DEFAULT_ROLLOUT_REQUEST_TIMEOUT must be a valid duration")
672        }
673
674        /// If a timeout-eligible rollout is currently in progress, returns the
675        /// time at which it entered the in-progress (`Unknown`) state. Used to
676        /// enforce the rollout timeout.
677        ///
678        /// The `Applying` and `ReadyToPromote` phases are both reported as a
679        /// single in-progress window: [`Self::up_to_date_transition_time`]
680        /// carries the timestamp forward across them (they share the `Unknown`
681        /// status), so the timeout spans the whole pre-promotion rollout rather
682        /// than resetting at each phase.
683        ///
684        /// The `Promoting` phase is deliberately excluded even though it is
685        /// also `Unknown`: once a rollout has reached promotion it must never
686        /// be cancelled by the timeout, since the previously-active generation
687        /// may already be torn down, leaving nothing to fall back to. (The
688        /// controller also never reaches the timeout check while promoting,
689        /// because `is_promoting` takes priority; this is belt-and-suspenders.)
690        pub fn rollout_in_progress_since(&self) -> Option<Timestamp> {
691            self.status
692                .as_ref()?
693                .conditions
694                .iter()
695                .find_map(|condition| {
696                    if condition.type_ == "UpToDate"
697                        && condition.status == "Unknown"
698                        && condition.reason != "Promoting"
699                    {
700                        Some(condition.last_transition_time.0)
701                    } else {
702                        None
703                    }
704                })
705        }
706
707        /// The `last_transition_time` to record for a new `UpToDate` condition
708        /// with `new_status`, following the Kubernetes convention that
709        /// `last_transition_time` marks when the condition's *status* last
710        /// changed — not its reason or message. While the status is unchanged
711        /// the existing timestamp is carried forward; it only resets to `now`
712        /// when the status actually changes (or there is no prior condition).
713        ///
714        /// This is what lets a rollout that moves through several same-status
715        /// phases (`Applying` -> `ReadyToPromote`, both `Unknown`) be measured
716        /// from when it first entered that status, so the rollout timeout
717        /// covers the phases together instead of restarting at each one.
718        pub fn up_to_date_transition_time(&self, new_status: &str, now: Timestamp) -> Timestamp {
719            self.status
720                .as_ref()
721                .and_then(|status| {
722                    status
723                        .conditions
724                        .iter()
725                        .find(|condition| condition.type_ == "UpToDate")
726                })
727                .filter(|condition| condition.status == new_status)
728                .map_or(now, |condition| condition.last_transition_time.0)
729        }
730
731        /// Returns the environmentd image ref of the currently-active
732        /// generation: the image of the last completed rollout, falling back
733        /// to the spec image when no rollout has completed yet. Downstream
734        /// resources (balancerd, console) should track this rather than
735        /// [`MaterializeSpec::environmentd_image_ref`] so they stay aligned
736        /// with the running environmentd when the spec is mid-rollout or has
737        /// been partially reverted (DEP-42).
738        pub fn active_environmentd_image_ref(&self) -> &str {
739            self.status
740                .as_ref()
741                .and_then(|s| s.last_completed_rollout_environmentd_image_ref.as_deref())
742                .unwrap_or(&self.spec.environmentd_image_ref)
743        }
744
745        pub fn set_force_promote(&mut self) {
746            self.spec.force_promote = self.spec.request_rollout.hyphenated().to_string();
747        }
748
749        pub fn should_force_promote(&self) -> bool {
750            self.spec.force_promote == self.spec.request_rollout.hyphenated().to_string()
751                || self.spec.force_promote
752                    == super::v1::Materialize::from(self.clone()).generate_rollout_hash()
753                || self.spec.rollout_strategy
754                    == MaterializeRolloutStrategy::ImmediatelyPromoteCausingDowntime
755        }
756
757        pub fn conditions_need_update(&self) -> bool {
758            let Some(status) = self.status.as_ref() else {
759                return true;
760            };
761            if status.conditions.is_empty() {
762                return true;
763            }
764            for condition in &status.conditions {
765                if condition.observed_generation != self.meta().generation {
766                    return true;
767                }
768            }
769            false
770        }
771
772        pub fn is_ready_to_promote(&self, resources_hash: &str) -> bool {
773            let Some(status) = self.status.as_ref() else {
774                return false;
775            };
776            if status.conditions.is_empty() {
777                return false;
778            }
779            status
780                .conditions
781                .iter()
782                .any(|condition| condition.reason == "ReadyToPromote")
783                && &status.resources_hash == resources_hash
784        }
785
786        pub fn is_promoting(&self) -> bool {
787            let Some(status) = self.status.as_ref() else {
788                return false;
789            };
790            if status.conditions.is_empty() {
791                return false;
792            }
793            status
794                .conditions
795                .iter()
796                .any(|condition| condition.reason == "Promoting")
797        }
798
799        pub fn update_in_progress(&self) -> bool {
800            let Some(status) = self.status.as_ref() else {
801                return false;
802            };
803            if status.conditions.is_empty() {
804                return false;
805            }
806            for condition in &status.conditions {
807                if condition.type_ == "UpToDate" && condition.status == "Unknown" {
808                    return true;
809                }
810            }
811            false
812        }
813
814        /// Checks that the given version is greater than or equal
815        /// to the existing version, if the existing version
816        /// can be parsed.
817        pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
818            let version = parse_image_ref(&self.spec.environmentd_image_ref);
819            match version {
820                // Use cmp_precedence() to ignore build metadata per SemVer 2.0.0 spec
821                Some(version) => version.cmp_precedence(minimum).is_ge(),
822                // In the rare case that we see an image reference
823                // that we can't parse, we assume that it satisfies all
824                // version checks. Usually these are custom images that have
825                // been by a developer on a branch forked from a recent copy
826                // of main, and so this works out reasonably well in practice.
827                None => {
828                    tracing::warn!(
829                        image_ref = %self.spec.environmentd_image_ref,
830                        "failed to parse image ref",
831                    );
832                    true
833                }
834            }
835        }
836
837        /// This check isn't strictly required since environmentd will still be able to determine
838        /// if the upgrade is allowed or not. However, doing this check allows us to provide
839        /// the error as soon as possible and in a more user friendly way.
840        pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
841            // Don't allow rolling back
842            // Note: semver comparison handles RC versions correctly:
843            // v26.0.0-rc.1 < v26.0.0-rc.2 < v26.0.0
844            // Use cmp_precedence() to ignore build metadata
845            if next_version.cmp_precedence(active_version) == std::cmp::Ordering::Less {
846                return false;
847            }
848
849            if active_version.major == 0 {
850                if next_version.major != active_version.major {
851                    if next_version.major == 26 {
852                        // We require customers to upgrade from 0.147.20 (Self Managed 25.2) or v0.164.X (Cloud)
853                        // before upgrading to 26.0.0
854                        return (active_version.minor == 147 && active_version.patch >= 20)
855                            || active_version.minor >= 164;
856                    } else {
857                        return false;
858                    }
859                }
860                // Self managed 25.1 to 25.2
861                if next_version.minor == 147 && active_version.minor == 130 {
862                    return true;
863                }
864                // only allow upgrading a single minor version at a time
865                return next_version.minor <= active_version.minor + 1;
866            } else if active_version.major >= 26 {
867                // For versions 26.X.X and onwards, we deny upgrades past 1 major version of the active version
868                return next_version.major <= active_version.major + 1;
869            }
870
871            true
872        }
873
874        /// Checks if the current environmentd image ref is within the upgrade window of the last
875        /// successful rollout.
876        pub fn within_upgrade_window(&self) -> bool {
877            let active_environmentd_version = self
878                .status
879                .as_ref()
880                .and_then(|status| {
881                    status
882                        .last_completed_rollout_environmentd_image_ref
883                        .as_ref()
884                })
885                .and_then(|image_ref| parse_image_ref(image_ref));
886
887            if let (Some(next_environmentd_version), Some(active_environmentd_version)) = (
888                parse_image_ref(&self.spec.environmentd_image_ref),
889                active_environmentd_version,
890            ) {
891                Self::is_valid_upgrade_version(
892                    &active_environmentd_version,
893                    &next_environmentd_version,
894                )
895            } else {
896                // If we fail to parse either version,
897                // we still allow the upgrade since environmentd will still error if the upgrade is not allowed.
898                true
899            }
900        }
901
902        pub fn status(&self) -> MaterializeStatus {
903            self.status.clone().unwrap_or_else(|| {
904                let mut status = MaterializeStatus::default();
905
906                // If we're creating the initial status on a recreated
907                // Environment, restore what the old resource's status held.
908                let initial =
909                    InitialStatusAnnotations::parse(self.annotations()).unwrap_or_else(|e| {
910                        warn!("ignoring initial status annotations: {e}");
911                        InitialStatusAnnotations::default()
912                    });
913
914                status.resource_id = initial.resource_id.unwrap_or_else(new_resource_id);
915
916                if let Some(active_generation) = initial.active_generation {
917                    status.active_generation = active_generation;
918                }
919
920                // Initialize the last completed rollout environmentd image ref to
921                // the current image ref if not already set.
922                status.last_completed_rollout_environmentd_image_ref =
923                    Some(self.spec.environmentd_image_ref.clone());
924
925                status
926            })
927        }
928    }
929
930    #[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema, PartialEq)]
931    #[serde(rename_all = "camelCase")]
932    pub struct MaterializeStatus {
933        /// Resource identifier used as a name prefix to avoid pod name collisions.
934        pub resource_id: String,
935        /// The generation of Materialize pods actively capable of servicing requests.
936        pub active_generation: u64,
937        /// The UUID of the last successfully completed rollout.
938        pub last_completed_rollout_request: Uuid,
939        /// The image ref of the environmentd image that was last successfully rolled out.
940        /// Used to deny upgrades past 1 major version from the last successful rollout.
941        /// When None, we upgrade anyways.
942        pub last_completed_rollout_environmentd_image_ref: Option<String>,
943        /// A hash calculated from the spec of resources to be created based on this Materialize
944        /// spec. This is used for detecting when the existing resources are up to date.
945        /// If you want to trigger a rollout without making other changes that would cause this
946        /// hash to change, you must set forceRollout to the same UUID as requestRollout.
947        pub resources_hash: String,
948        /// The last completed rollout hash from v1.
949        /// This exists on this older version only for round-trip conversion support.
950        pub last_completed_rollout_hash: Option<String>,
951        pub conditions: Vec<Condition>,
952    }
953
954    impl MaterializeStatus {
955        pub fn needs_update(&self, other: &Self) -> bool {
956            let now = Timestamp::now();
957            let mut a = self.clone();
958            for condition in &mut a.conditions {
959                condition.last_transition_time = Time(now);
960            }
961            let mut b = other.clone();
962            for condition in &mut b.conditions {
963                condition.last_transition_time = Time(now);
964            }
965            a != b
966        }
967    }
968
969    impl ManagedResource for Materialize {
970        fn default_labels(&self) -> BTreeMap<String, String> {
971            BTreeMap::from_iter([
972                (
973                    "materialize.cloud/organization-name".to_owned(),
974                    self.name_unchecked(),
975                ),
976                (
977                    "materialize.cloud/organization-namespace".to_owned(),
978                    self.namespace(),
979                ),
980                (
981                    "materialize.cloud/mz-resource-id".to_owned(),
982                    self.resource_id().to_owned(),
983                ),
984            ])
985        }
986
987        fn app_name(&self) -> Option<&str> {
988            Some("environmentd")
989        }
990    }
991
992    impl From<v1::Materialize> for Materialize {
993        fn from(value: v1::Materialize) -> Self {
994            let rollout_hash = value.generate_rollout_hash();
995            // Derive a deterministic UUID from the rollout hash so that the
996            // same v1 spec always produces the same requestRollout,
997            // making re-applies of an unchanged spec idempotent.
998            let request_rollout = Uuid::new_v5(&Uuid::NAMESPACE_OID, rollout_hash.as_bytes());
999            Materialize {
1000                metadata: value.metadata,
1001                spec: MaterializeSpec {
1002                    environmentd_image_ref: value.spec.environmentd_image_ref,
1003                    environmentd_extra_args: value.spec.environmentd_extra_args,
1004                    environmentd_extra_env: value.spec.environmentd_extra_env,
1005                    environmentd_iam_role_arn: None,
1006                    environmentd_connection_role_arn: value.spec.environmentd_connection_role_arn,
1007                    environmentd_resource_requirements: value
1008                        .spec
1009                        .environmentd_resource_requirements,
1010                    environmentd_scratch_volume_storage_requirement: value
1011                        .spec
1012                        .environmentd_scratch_volume_storage_requirement,
1013                    environmentd_readiness_probe: value.spec.environmentd_readiness_probe,
1014                    environmentd_liveness_probe: value.spec.environmentd_liveness_probe,
1015                    environmentd_startup_probe: value.spec.environmentd_startup_probe,
1016                    balancerd_resource_requirements: value.spec.balancerd_resource_requirements,
1017                    balancerd_configmap_name: value.spec.balancerd_configmap_name,
1018                    console_resource_requirements: value.spec.console_resource_requirements,
1019                    balancerd_replicas: value.spec.balancerd_replicas,
1020                    balancerd_externally_scaled: value.spec.balancerd_externally_scaled,
1021                    console_replicas: value.spec.console_replicas,
1022                    service_account_name: value.spec.service_account_name,
1023                    service_account_annotations: value.spec.service_account_annotations,
1024                    service_account_labels: value.spec.service_account_labels,
1025                    pod_annotations: value.spec.pod_annotations,
1026                    pod_labels: value.spec.pod_labels,
1027                    force_promote: value.spec.force_promote.unwrap_or_default(),
1028                    force_rollout: value.spec.force_rollout,
1029                    rollout_strategy: value.spec.rollout_strategy,
1030                    rollout_request_timeout: value.spec.rollout_request_timeout,
1031                    backend_secret_name: value.spec.backend_secret_name,
1032                    authenticator_kind: value.spec.authenticator_kind,
1033                    enable_rbac: value.spec.enable_rbac,
1034                    environment_id: value.spec.environment_id,
1035                    system_parameter_configmap_name: value.spec.system_parameter_configmap_name,
1036                    additional_trust_bundle: value.spec.additional_trust_bundle,
1037                    balancerd_external_certificate_spec: value
1038                        .spec
1039                        .balancerd_external_certificate_spec,
1040                    console_external_certificate_spec: value.spec.console_external_certificate_spec,
1041                    internal_certificate_spec: value.spec.internal_certificate_spec,
1042                    request_rollout,
1043                    in_place_rollout: false,
1044                },
1045                status: value.status.map(|status| MaterializeStatus {
1046                    resource_id: status.resource_id,
1047                    active_generation: status.active_generation,
1048                    last_completed_rollout_environmentd_image_ref: status
1049                        .last_completed_rollout_environmentd_image_ref,
1050                    conditions: status.conditions,
1051                    // Derive the same deterministic UUID from the last
1052                    // completed hash so that request_rollout == this value
1053                    // when the spec hasn't changed (no rollout needed).
1054                    last_completed_rollout_request: status
1055                        .last_completed_rollout_hash
1056                        .as_ref()
1057                        .map(|hash| Uuid::new_v5(&Uuid::NAMESPACE_OID, hash.as_bytes()))
1058                        .unwrap_or(Uuid::nil()),
1059                    last_completed_rollout_hash: status.last_completed_rollout_hash,
1060                    resources_hash: "".to_owned(),
1061                }),
1062            }
1063        }
1064    }
1065
1066    /// Partial mirror of [`MaterializeSpec`] for field-wise conversion of
1067    /// objects that may be incomplete. See [`super::convert_v1_to_v1alpha1`].
1068    ///
1069    /// Each field is a [`PartialField`], distinguishing absent from explicit
1070    /// null from a value, and unknown fields pass through via `extra`, so
1071    /// serializing reproduces exactly what was deserialized. Adding a field
1072    /// to [`MaterializeSpec`] breaks the exhaustive destructures in the
1073    /// `From` impls below until its conversion is decided.
1074    #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
1075    #[serde(rename_all = "camelCase")]
1076    pub struct PartialMaterializeSpec {
1077        #[serde(
1078            default,
1079            with = "double_option",
1080            skip_serializing_if = "Option::is_none"
1081        )]
1082        pub environmentd_image_ref: PartialField,
1083        #[serde(
1084            default,
1085            with = "double_option",
1086            skip_serializing_if = "Option::is_none"
1087        )]
1088        pub environmentd_extra_args: PartialField,
1089        #[serde(
1090            default,
1091            with = "double_option",
1092            skip_serializing_if = "Option::is_none"
1093        )]
1094        pub environmentd_extra_env: PartialField,
1095        #[serde(
1096            default,
1097            with = "double_option",
1098            skip_serializing_if = "Option::is_none"
1099        )]
1100        pub environmentd_iam_role_arn: PartialField,
1101        #[serde(
1102            default,
1103            with = "double_option",
1104            skip_serializing_if = "Option::is_none"
1105        )]
1106        pub environmentd_connection_role_arn: PartialField,
1107        #[serde(
1108            default,
1109            with = "double_option",
1110            skip_serializing_if = "Option::is_none"
1111        )]
1112        pub environmentd_resource_requirements: PartialField,
1113        #[serde(
1114            default,
1115            with = "double_option",
1116            skip_serializing_if = "Option::is_none"
1117        )]
1118        pub environmentd_scratch_volume_storage_requirement: PartialField,
1119        #[serde(
1120            default,
1121            with = "double_option",
1122            skip_serializing_if = "Option::is_none"
1123        )]
1124        pub environmentd_readiness_probe: PartialField,
1125        #[serde(
1126            default,
1127            with = "double_option",
1128            skip_serializing_if = "Option::is_none"
1129        )]
1130        pub environmentd_liveness_probe: PartialField,
1131        #[serde(
1132            default,
1133            with = "double_option",
1134            skip_serializing_if = "Option::is_none"
1135        )]
1136        pub environmentd_startup_probe: PartialField,
1137        #[serde(
1138            default,
1139            with = "double_option",
1140            skip_serializing_if = "Option::is_none"
1141        )]
1142        pub balancerd_resource_requirements: PartialField,
1143        #[serde(
1144            default,
1145            with = "double_option",
1146            skip_serializing_if = "Option::is_none"
1147        )]
1148        pub balancerd_configmap_name: PartialField,
1149        #[serde(
1150            default,
1151            with = "double_option",
1152            skip_serializing_if = "Option::is_none"
1153        )]
1154        pub console_resource_requirements: PartialField,
1155        #[serde(
1156            default,
1157            with = "double_option",
1158            skip_serializing_if = "Option::is_none"
1159        )]
1160        pub balancerd_replicas: PartialField,
1161        #[serde(
1162            default,
1163            with = "double_option",
1164            skip_serializing_if = "Option::is_none"
1165        )]
1166        pub balancerd_externally_scaled: PartialField,
1167        #[serde(
1168            default,
1169            with = "double_option",
1170            skip_serializing_if = "Option::is_none"
1171        )]
1172        pub console_replicas: PartialField,
1173        #[serde(
1174            default,
1175            with = "double_option",
1176            skip_serializing_if = "Option::is_none"
1177        )]
1178        pub service_account_name: PartialField,
1179        #[serde(
1180            default,
1181            with = "double_option",
1182            skip_serializing_if = "Option::is_none"
1183        )]
1184        pub service_account_annotations: PartialField,
1185        #[serde(
1186            default,
1187            with = "double_option",
1188            skip_serializing_if = "Option::is_none"
1189        )]
1190        pub service_account_labels: PartialField,
1191        #[serde(
1192            default,
1193            with = "double_option",
1194            skip_serializing_if = "Option::is_none"
1195        )]
1196        pub pod_annotations: PartialField,
1197        #[serde(
1198            default,
1199            with = "double_option",
1200            skip_serializing_if = "Option::is_none"
1201        )]
1202        pub pod_labels: PartialField,
1203        #[serde(
1204            default,
1205            with = "double_option",
1206            skip_serializing_if = "Option::is_none"
1207        )]
1208        pub request_rollout: PartialField,
1209        #[serde(
1210            default,
1211            with = "double_option",
1212            skip_serializing_if = "Option::is_none"
1213        )]
1214        pub force_promote: PartialField,
1215        #[serde(
1216            default,
1217            with = "double_option",
1218            skip_serializing_if = "Option::is_none"
1219        )]
1220        pub force_rollout: PartialField,
1221        #[serde(
1222            default,
1223            with = "double_option",
1224            skip_serializing_if = "Option::is_none"
1225        )]
1226        pub in_place_rollout: PartialField,
1227        #[serde(
1228            default,
1229            with = "double_option",
1230            skip_serializing_if = "Option::is_none"
1231        )]
1232        pub rollout_strategy: PartialField,
1233        #[serde(
1234            default,
1235            with = "double_option",
1236            skip_serializing_if = "Option::is_none"
1237        )]
1238        pub rollout_request_timeout: PartialField,
1239        #[serde(
1240            default,
1241            with = "double_option",
1242            skip_serializing_if = "Option::is_none"
1243        )]
1244        pub backend_secret_name: PartialField,
1245        #[serde(
1246            default,
1247            with = "double_option",
1248            skip_serializing_if = "Option::is_none"
1249        )]
1250        pub authenticator_kind: PartialField,
1251        #[serde(
1252            default,
1253            with = "double_option",
1254            skip_serializing_if = "Option::is_none"
1255        )]
1256        pub enable_rbac: PartialField,
1257        #[serde(
1258            default,
1259            with = "double_option",
1260            skip_serializing_if = "Option::is_none"
1261        )]
1262        pub environment_id: PartialField,
1263        #[serde(
1264            default,
1265            with = "double_option",
1266            skip_serializing_if = "Option::is_none"
1267        )]
1268        pub system_parameter_configmap_name: PartialField,
1269        #[serde(
1270            default,
1271            with = "double_option",
1272            skip_serializing_if = "Option::is_none"
1273        )]
1274        pub additional_trust_bundle: PartialField,
1275        #[serde(
1276            default,
1277            with = "double_option",
1278            skip_serializing_if = "Option::is_none"
1279        )]
1280        pub balancerd_external_certificate_spec: PartialField,
1281        #[serde(
1282            default,
1283            with = "double_option",
1284            skip_serializing_if = "Option::is_none"
1285        )]
1286        pub console_external_certificate_spec: PartialField,
1287        #[serde(
1288            default,
1289            with = "double_option",
1290            skip_serializing_if = "Option::is_none"
1291        )]
1292        pub internal_certificate_spec: PartialField,
1293        #[serde(flatten)]
1294        pub extra: serde_json::Map<String, serde_json::Value>,
1295    }
1296
1297    /// Partial mirror of [`MaterializeStatus`], see [`PartialMaterializeSpec`].
1298    #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
1299    #[serde(rename_all = "camelCase")]
1300    pub struct PartialMaterializeStatus {
1301        #[serde(
1302            default,
1303            with = "double_option",
1304            skip_serializing_if = "Option::is_none"
1305        )]
1306        pub resource_id: PartialField,
1307        #[serde(
1308            default,
1309            with = "double_option",
1310            skip_serializing_if = "Option::is_none"
1311        )]
1312        pub active_generation: PartialField,
1313        #[serde(
1314            default,
1315            with = "double_option",
1316            skip_serializing_if = "Option::is_none"
1317        )]
1318        pub last_completed_rollout_request: PartialField,
1319        #[serde(
1320            default,
1321            with = "double_option",
1322            skip_serializing_if = "Option::is_none"
1323        )]
1324        pub last_completed_rollout_environmentd_image_ref: PartialField,
1325        #[serde(
1326            default,
1327            with = "double_option",
1328            skip_serializing_if = "Option::is_none"
1329        )]
1330        pub resources_hash: PartialField,
1331        #[serde(
1332            default,
1333            with = "double_option",
1334            skip_serializing_if = "Option::is_none"
1335        )]
1336        pub last_completed_rollout_hash: PartialField,
1337        #[serde(
1338            default,
1339            with = "double_option",
1340            skip_serializing_if = "Option::is_none"
1341        )]
1342        pub conditions: PartialField,
1343        #[serde(flatten)]
1344        pub extra: serde_json::Map<String, serde_json::Value>,
1345    }
1346
1347    /// Partial mirror of [`Materialize`], see [`PartialMaterializeSpec`].
1348    #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
1349    #[serde(rename_all = "camelCase")]
1350    pub struct PartialMaterialize {
1351        #[serde(skip_serializing_if = "Option::is_none")]
1352        pub api_version: Option<String>,
1353        #[serde(skip_serializing_if = "Option::is_none")]
1354        pub kind: Option<serde_json::Value>,
1355        #[serde(skip_serializing_if = "Option::is_none")]
1356        pub metadata: Option<serde_json::Value>,
1357        #[serde(skip_serializing_if = "Option::is_none")]
1358        pub spec: Option<PartialMaterializeSpec>,
1359        #[serde(skip_serializing_if = "Option::is_none")]
1360        pub status: Option<PartialMaterializeStatus>,
1361        #[serde(flatten)]
1362        pub extra: serde_json::Map<String, serde_json::Value>,
1363    }
1364
1365    impl From<MaterializeSpec> for PartialMaterializeSpec {
1366        fn from(spec: MaterializeSpec) -> Self {
1367            let MaterializeSpec {
1368                environmentd_image_ref,
1369                environmentd_extra_args,
1370                environmentd_extra_env,
1371                environmentd_iam_role_arn,
1372                environmentd_connection_role_arn,
1373                environmentd_resource_requirements,
1374                environmentd_scratch_volume_storage_requirement,
1375                environmentd_readiness_probe,
1376                environmentd_liveness_probe,
1377                environmentd_startup_probe,
1378                balancerd_resource_requirements,
1379                balancerd_configmap_name,
1380                console_resource_requirements,
1381                balancerd_replicas,
1382                balancerd_externally_scaled,
1383                console_replicas,
1384                service_account_name,
1385                service_account_annotations,
1386                service_account_labels,
1387                pod_annotations,
1388                pod_labels,
1389                request_rollout,
1390                force_promote,
1391                force_rollout,
1392                in_place_rollout,
1393                rollout_strategy,
1394                rollout_request_timeout,
1395                backend_secret_name,
1396                authenticator_kind,
1397                enable_rbac,
1398                environment_id,
1399                system_parameter_configmap_name,
1400                additional_trust_bundle,
1401                balancerd_external_certificate_spec,
1402                console_external_certificate_spec,
1403                internal_certificate_spec,
1404            } = spec;
1405            Self {
1406                environmentd_image_ref: present(environmentd_image_ref),
1407                environmentd_extra_args: present_opt(environmentd_extra_args),
1408                environmentd_extra_env: present_opt(environmentd_extra_env),
1409                environmentd_iam_role_arn: present_opt(environmentd_iam_role_arn),
1410                environmentd_connection_role_arn: present_opt(environmentd_connection_role_arn),
1411                environmentd_resource_requirements: present_opt(environmentd_resource_requirements),
1412                environmentd_scratch_volume_storage_requirement: present_opt(
1413                    environmentd_scratch_volume_storage_requirement,
1414                ),
1415                environmentd_readiness_probe: present_opt(environmentd_readiness_probe),
1416                environmentd_liveness_probe: present_opt(environmentd_liveness_probe),
1417                environmentd_startup_probe: present_opt(environmentd_startup_probe),
1418                balancerd_resource_requirements: present_opt(balancerd_resource_requirements),
1419                balancerd_configmap_name: present_opt(balancerd_configmap_name),
1420                console_resource_requirements: present_opt(console_resource_requirements),
1421                balancerd_replicas: present_opt(balancerd_replicas),
1422                balancerd_externally_scaled: present_opt(balancerd_externally_scaled),
1423                console_replicas: present_opt(console_replicas),
1424                service_account_name: present_opt(service_account_name),
1425                service_account_annotations: present_opt(service_account_annotations),
1426                service_account_labels: present_opt(service_account_labels),
1427                pod_annotations: present_opt(pod_annotations),
1428                pod_labels: present_opt(pod_labels),
1429                request_rollout: present(request_rollout),
1430                force_promote: present(force_promote),
1431                force_rollout: present(force_rollout),
1432                in_place_rollout: present(in_place_rollout),
1433                rollout_strategy: present(rollout_strategy),
1434                rollout_request_timeout: present(rollout_request_timeout),
1435                backend_secret_name: present(backend_secret_name),
1436                authenticator_kind: present(authenticator_kind),
1437                enable_rbac: present(enable_rbac),
1438                environment_id: present(environment_id),
1439                system_parameter_configmap_name: present_opt(system_parameter_configmap_name),
1440                additional_trust_bundle: present_opt(additional_trust_bundle),
1441                balancerd_external_certificate_spec: present_opt(
1442                    balancerd_external_certificate_spec,
1443                ),
1444                console_external_certificate_spec: present_opt(console_external_certificate_spec),
1445                internal_certificate_spec: present_opt(internal_certificate_spec),
1446                extra: serde_json::Map::new(),
1447            }
1448        }
1449    }
1450
1451    impl From<MaterializeStatus> for PartialMaterializeStatus {
1452        fn from(status: MaterializeStatus) -> Self {
1453            let MaterializeStatus {
1454                resource_id,
1455                active_generation,
1456                last_completed_rollout_request,
1457                last_completed_rollout_environmentd_image_ref,
1458                resources_hash,
1459                last_completed_rollout_hash,
1460                conditions,
1461            } = status;
1462            Self {
1463                resource_id: present(resource_id),
1464                active_generation: present(active_generation),
1465                last_completed_rollout_request: present(last_completed_rollout_request),
1466                last_completed_rollout_environmentd_image_ref: present_opt(
1467                    last_completed_rollout_environmentd_image_ref,
1468                ),
1469                resources_hash: present(resources_hash),
1470                last_completed_rollout_hash: present_opt(last_completed_rollout_hash),
1471                conditions: present(conditions),
1472                extra: serde_json::Map::new(),
1473            }
1474        }
1475    }
1476
1477    impl From<Materialize> for PartialMaterialize {
1478        fn from(mz: Materialize) -> Self {
1479            let Materialize {
1480                metadata,
1481                spec,
1482                status,
1483            } = mz;
1484            Self {
1485                api_version: Some("materialize.cloud/v1alpha1".to_owned()),
1486                kind: Some("Materialize".into()),
1487                metadata: Some(
1488                    serde_json::to_value(metadata).expect("ObjectMeta serializes to JSON"),
1489                ),
1490                spec: Some(spec.into()),
1491                status: status.map(Into::into),
1492                extra: serde_json::Map::new(),
1493            }
1494        }
1495    }
1496
1497    impl From<super::v1::PartialMaterializeSpec> for PartialMaterializeSpec {
1498        fn from(spec: super::v1::PartialMaterializeSpec) -> Self {
1499            let super::v1::PartialMaterializeSpec {
1500                environmentd_image_ref,
1501                environmentd_extra_args,
1502                environmentd_extra_env,
1503                environmentd_connection_role_arn,
1504                environmentd_resource_requirements,
1505                environmentd_scratch_volume_storage_requirement,
1506                environmentd_readiness_probe,
1507                environmentd_liveness_probe,
1508                environmentd_startup_probe,
1509                balancerd_resource_requirements,
1510                balancerd_configmap_name,
1511                console_resource_requirements,
1512                balancerd_replicas,
1513                balancerd_externally_scaled,
1514                console_replicas,
1515                service_account_name,
1516                service_account_annotations,
1517                service_account_labels,
1518                pod_annotations,
1519                pod_labels,
1520                force_promote,
1521                force_rollout,
1522                rollout_strategy,
1523                rollout_request_timeout,
1524                backend_secret_name,
1525                authenticator_kind,
1526                enable_rbac,
1527                environment_id,
1528                system_parameter_configmap_name,
1529                additional_trust_bundle,
1530                balancerd_external_certificate_spec,
1531                console_external_certificate_spec,
1532                internal_certificate_spec,
1533                extra,
1534            } = spec;
1535            Self {
1536                environmentd_image_ref,
1537                environmentd_extra_args,
1538                environmentd_extra_env,
1539                environmentd_iam_role_arn: None,
1540                environmentd_connection_role_arn,
1541                environmentd_resource_requirements,
1542                environmentd_scratch_volume_storage_requirement,
1543                environmentd_readiness_probe,
1544                environmentd_liveness_probe,
1545                environmentd_startup_probe,
1546                balancerd_resource_requirements,
1547                balancerd_configmap_name,
1548                console_resource_requirements,
1549                balancerd_replicas,
1550                balancerd_externally_scaled,
1551                console_replicas,
1552                service_account_name,
1553                service_account_annotations,
1554                service_account_labels,
1555                pod_annotations,
1556                pod_labels,
1557                // Derived from the complete spec. Spliced in by
1558                // `convert_v1_to_v1alpha1` when the input is complete, left
1559                // absent for partial objects so a field manager cannot gain
1560                // ownership of a field it never set.
1561                request_rollout: None,
1562                force_promote,
1563                force_rollout,
1564                in_place_rollout: None,
1565                rollout_strategy,
1566                rollout_request_timeout,
1567                backend_secret_name,
1568                authenticator_kind,
1569                enable_rbac,
1570                environment_id,
1571                system_parameter_configmap_name,
1572                additional_trust_bundle,
1573                balancerd_external_certificate_spec,
1574                console_external_certificate_spec,
1575                internal_certificate_spec,
1576                extra,
1577            }
1578        }
1579    }
1580
1581    impl From<super::v1::PartialMaterializeStatus> for PartialMaterializeStatus {
1582        fn from(status: super::v1::PartialMaterializeStatus) -> Self {
1583            let super::v1::PartialMaterializeStatus {
1584                resource_id,
1585                active_generation,
1586                last_completed_rollout_environmentd_image_ref,
1587                last_completed_rollout_hash,
1588                requested_rollout_hash: _,
1589                conditions,
1590                extra,
1591            } = status;
1592            Self {
1593                resource_id,
1594                active_generation,
1595                // Derived from the complete object, spliced in by
1596                // `convert_v1_to_v1alpha1` when the input is complete, left
1597                // absent for partial objects so a field manager cannot gain
1598                // ownership of fields it never set.
1599                last_completed_rollout_request: None,
1600                resources_hash: None,
1601                last_completed_rollout_environmentd_image_ref,
1602                last_completed_rollout_hash,
1603                conditions,
1604                extra,
1605            }
1606        }
1607    }
1608
1609    impl From<super::v1::PartialMaterialize> for PartialMaterialize {
1610        fn from(mz: super::v1::PartialMaterialize) -> Self {
1611            let super::v1::PartialMaterialize {
1612                api_version: _,
1613                kind,
1614                metadata,
1615                spec,
1616                status,
1617                extra,
1618            } = mz;
1619            Self {
1620                api_version: Some("materialize.cloud/v1alpha1".to_owned()),
1621                kind,
1622                metadata,
1623                spec: spec.map(Into::into),
1624                status: status.map(Into::into),
1625                extra,
1626            }
1627        }
1628    }
1629}
1630
1631pub mod v1 {
1632    use super::*;
1633
1634    #[derive(
1635        CustomResource,
1636        Clone,
1637        Debug,
1638        Default,
1639        PartialEq,
1640        Deserialize,
1641        Serialize,
1642        JsonSchema
1643    )]
1644    #[serde(rename_all = "camelCase")]
1645    #[kube(
1646        namespaced,
1647        group = "materialize.cloud",
1648        version = "v1",
1649        kind = "Materialize",
1650        singular = "materialize",
1651        plural = "materializes",
1652        shortname = "mzs",
1653        status = "MaterializeStatus",
1654        printcolumn = r#"{"name": "ImageRefRunning", "type": "string", "description": "Reference to the Docker image that is currently in use.", "jsonPath": ".status.lastCompletedRolloutEnvironmentdImageRef", "priority": 1}"#,
1655        printcolumn = r#"{"name": "ImageRefToDeploy", "type": "string", "description": "Reference to the Docker image which will be deployed on the next rollout.", "jsonPath": ".spec.environmentdImageRef", "priority": 1}"#,
1656        printcolumn = r#"{"name": "UpToDate", "type": "string", "description": "Whether the spec has been applied", "jsonPath": ".status.conditions[?(@.type==\"UpToDate\")].status", "priority": 1}"#
1657    )]
1658    pub struct MaterializeSpec {
1659        /// The environmentd image to run.
1660        pub environmentd_image_ref: String,
1661        /// Extra args to pass to the environmentd binary.
1662        pub environmentd_extra_args: Option<Vec<String>>,
1663        /// Extra environment variables to pass to the environmentd binary.
1664        pub environmentd_extra_env: Option<Vec<EnvVar>>,
1665        /// If running in AWS, override the IAM role to use to support
1666        /// the CREATE CONNECTION feature.
1667        pub environmentd_connection_role_arn: Option<String>,
1668        /// Resource requirements for the environmentd pod.
1669        pub environmentd_resource_requirements: Option<ResourceRequirements>,
1670        /// Amount of disk to allocate, if a storage class is provided.
1671        pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
1672        /// Readiness probe for the environmentd container.
1673        ///
1674        /// Fields set here are overlaid onto the operator's default probe, so only the fields
1675        /// being changed need to be set. If no handler (`exec`, `grpc`, `httpGet`, `tcpSocket`)
1676        /// is set, the default TCP check against environmentd's SQL port is kept.
1677        #[serde(skip_serializing_if = "Option::is_none")]
1678        pub environmentd_readiness_probe: Option<Probe>,
1679        /// Liveness probe for the environmentd container.
1680        ///
1681        /// Fields set here are overlaid onto the operator's default probe, so only the fields
1682        /// being changed need to be set. If no handler (`exec`, `grpc`, `httpGet`, `tcpSocket`)
1683        /// is set, the default TCP check against environmentd's SQL port is kept.
1684        #[serde(skip_serializing_if = "Option::is_none")]
1685        pub environmentd_liveness_probe: Option<Probe>,
1686        /// Startup probe for the environmentd container. Liveness and readiness checks are held
1687        /// off until it succeeds, so it can allow a long startup without loosening the liveness
1688        /// probe.
1689        ///
1690        /// No startup probe runs unless this field or the operator's default sets one. Fields set
1691        /// here are overlaid onto the operator's default probe, so only the fields being changed
1692        /// need to be set. If no handler (`exec`, `grpc`, `httpGet`, `tcpSocket`) is set, the
1693        /// default TCP check against environmentd's SQL port is used.
1694        #[serde(skip_serializing_if = "Option::is_none")]
1695        pub environmentd_startup_probe: Option<Probe>,
1696        /// Resource requirements for the balancerd pod.
1697        ///
1698        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1699        pub balancerd_resource_requirements: Option<ResourceRequirements>,
1700        /// The name of an externally managed ConfigMap in this namespace containing
1701        /// balancerd dynamic configuration as a JSON object in `config.json`.
1702        /// Changes to its contents are applied at runtime. Changing this reference
1703        /// restarts balancerd pods but does not trigger an environmentd rollout.
1704        #[serde(skip_serializing_if = "Option::is_none")]
1705        pub balancerd_configmap_name: Option<String>,
1706        /// Resource requirements for the console pod.
1707        ///
1708        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1709        pub console_resource_requirements: Option<ResourceRequirements>,
1710        /// Number of balancerd pods to create.
1711        ///
1712        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1713        pub balancerd_replicas: Option<i32>,
1714        /// Leave the balancerd Deployment's replica count to an external
1715        /// autoscaler, such as a HorizontalPodAutoscaler. `balancerd_replicas`
1716        /// then only seeds the count when the Deployment is first created.
1717        ///
1718        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1719        #[serde(skip_serializing_if = "Option::is_none")]
1720        pub balancerd_externally_scaled: Option<bool>,
1721        /// Number of console pods to create.
1722        ///
1723        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1724        pub console_replicas: Option<i32>,
1725
1726        /// Name of the kubernetes service account to use.
1727        /// If not set, we will create one with the same name as this Materialize object.
1728        pub service_account_name: Option<String>,
1729        /// Annotations to apply to the service account.
1730        ///
1731        /// Annotations on service accounts are commonly used by cloud providers for IAM.
1732        /// AWS uses "eks.amazonaws.com/role-arn".
1733        /// Azure uses "azure.workload.identity/client-id", but
1734        /// additionally requires "azure.workload.identity/use": "true" on the pods.
1735        pub service_account_annotations: Option<BTreeMap<String, String>>,
1736        /// Labels to apply to the service account.
1737        pub service_account_labels: Option<BTreeMap<String, String>>,
1738        /// Annotations to apply to the pods.
1739        pub pod_annotations: Option<BTreeMap<String, String>>,
1740        /// Labels to apply to the pods.
1741        pub pod_labels: Option<BTreeMap<String, String>>,
1742
1743        /// If `forcePromote` is set to the same value as the `status.requestedRolloutHash`,
1744        /// current rollout will skip waiting for clusters in the new
1745        /// generation to rehydrate before promoting the new environmentd to
1746        /// leader.
1747        ///
1748        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1749        pub force_promote: Option<String>,
1750        /// This value will force the controller to detect the spec as changed
1751        /// even if no other changes happened. This can be used to force a rollout
1752        /// to a new generation even without making any meaningful changes.
1753        #[serde(default)]
1754        pub force_rollout: Uuid,
1755        /// Rollout strategy to use when upgrading this Materialize instance.
1756        #[serde(default)]
1757        pub rollout_strategy: MaterializeRolloutStrategy,
1758        /// The maximum amount of time a rollout may remain in progress before
1759        /// it is automatically cancelled.
1760        ///
1761        /// While a rollout is in progress, the new generation of `environmentd`
1762        /// runs in a read-only, un-promoted state and holds back compaction via
1763        /// read holds. Leaving it in this state for too long can cause
1764        /// incident-inducing load when it is eventually promoted, so the
1765        /// operator cancels the rollout once this timeout is exceeded: the new
1766        /// generation is torn down and the previously-active generation
1767        /// continues serving. A new rollout can then be triggered by setting
1768        /// `forceRollout` to a new value.
1769        ///
1770        /// This does not apply to the `ImmediatelyPromoteCausingDowntime`
1771        /// rollout strategy or to force-promoted rollouts, since by the time
1772        /// those are in progress the old generation may already be gone.
1773        ///
1774        /// The value is parsed as a human-readable duration, e.g. `24h`,
1775        /// `90m`, or `1h 30m`. Defaults to [`DEFAULT_ROLLOUT_REQUEST_TIMEOUT`]
1776        /// when omitted (the API server fills it in); an unparseable value also
1777        /// falls back to that default.
1778        #[serde(default)]
1779        pub rollout_request_timeout: RolloutRequestTimeout,
1780        /// The name of a secret containing `metadata_backend_url` and `persist_backend_url`.
1781        /// It may also contain `external_login_password_mz_system`, which will be used as
1782        /// the password for the `mz_system` user if `authenticatorKind` is `Password`.
1783        pub backend_secret_name: String,
1784        /// How to authenticate with Materialize.
1785        #[serde(default)]
1786        pub authenticator_kind: AuthenticatorKind,
1787        /// Whether to enable role based access control. Defaults to false.
1788        #[serde(default)]
1789        pub enable_rbac: bool,
1790
1791        /// The value used by environmentd (via the --environment-id flag) to
1792        /// uniquely identify this instance. Must be globally unique, and
1793        /// is required if a license key is not provided.
1794        /// NOTE: This value MUST NOT be changed in an existing instance,
1795        /// since it affects things like the way data is stored in the persist
1796        /// backend.
1797        #[serde(default)]
1798        pub environment_id: Uuid,
1799
1800        /// The name of a ConfigMap containing system parameters in JSON format.
1801        /// The ConfigMap must contain a `system-params.json` key whose value
1802        /// is a valid JSON object containing valid system parameters.
1803        ///
1804        /// Run `SHOW ALL` in SQL to see a subset of configurable system parameters.
1805        ///
1806        /// Example ConfigMap:
1807        /// ```yaml
1808        /// data:
1809        ///   system-params.json: |
1810        ///     {
1811        ///       "max_connections": 1000
1812        ///     }
1813        /// ```
1814        pub system_parameter_configmap_name: Option<String>,
1815        /// PEM-encoded CA certificates that environmentd and clusterd trust for
1816        /// outbound TLS connections, in addition to the CAs in their image.
1817        /// Use this when an OIDC provider, a source, a sink, or object storage
1818        /// presents a certificate signed by a private or self-signed CA.
1819        ///
1820        /// environmentd and clusterd read the certificates when they start, so
1821        /// changes to the contents of the ConfigMap or Secret take effect the
1822        /// next time their pods restart.
1823        #[serde(skip_serializing_if = "Option::is_none")]
1824        pub additional_trust_bundle: Option<AdditionalTrustBundle>,
1825
1826        /// The configuration for generating an x509 certificate using cert-manager for balancerd
1827        /// to present to incoming connections.
1828        /// The `dnsNames` and `issuerRef` fields are required.
1829        ///
1830        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1831        pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
1832        /// The configuration for generating an x509 certificate using cert-manager for the console
1833        /// to present to incoming connections.
1834        /// The `dnsNames` and `issuerRef` fields are required.
1835        /// Not yet implemented.
1836        ///
1837        /// This field is excluded from the rollout hash and changes will not trigger a rollout.
1838        pub console_external_certificate_spec: Option<MaterializeCertSpec>,
1839        /// The cert-manager Issuer or ClusterIssuer to use for database internal communication.
1840        /// The `issuerRef` field is required.
1841        /// This currently is only used for environmentd, but will eventually support clusterd.
1842        /// Not yet implemented.
1843        pub internal_certificate_spec: Option<MaterializeCertSpec>,
1844    }
1845
1846    impl Materialize {
1847        pub fn generate_rollout_hash(&self) -> String {
1848            let mut hasher = Sha256::new();
1849            // Remove fields that don't affect the resources generated per generation,
1850            // and we don't want to trigger a rollout from.
1851            let spec = MaterializeSpec {
1852                environmentd_image_ref: self.spec.environmentd_image_ref.clone(),
1853                environmentd_extra_args: self.spec.environmentd_extra_args.clone(),
1854                environmentd_extra_env: self.spec.environmentd_extra_env.clone(),
1855                environmentd_connection_role_arn: self
1856                    .spec
1857                    .environmentd_connection_role_arn
1858                    .clone(),
1859                environmentd_resource_requirements: self
1860                    .spec
1861                    .environmentd_resource_requirements
1862                    .clone(),
1863                environmentd_scratch_volume_storage_requirement: self
1864                    .spec
1865                    .environmentd_scratch_volume_storage_requirement
1866                    .clone(),
1867                environmentd_readiness_probe: self.spec.environmentd_readiness_probe.clone(),
1868                environmentd_liveness_probe: self.spec.environmentd_liveness_probe.clone(),
1869                environmentd_startup_probe: self.spec.environmentd_startup_probe.clone(),
1870                balancerd_resource_requirements: None,
1871                balancerd_configmap_name: None,
1872                console_resource_requirements: None,
1873                balancerd_replicas: None,
1874                balancerd_externally_scaled: None,
1875                console_replicas: None,
1876                service_account_name: self.spec.service_account_name.clone(),
1877                service_account_annotations: self.spec.service_account_annotations.clone(),
1878                service_account_labels: self.spec.service_account_labels.clone(),
1879                pod_annotations: self.spec.pod_annotations.clone(),
1880                pod_labels: self.spec.pod_labels.clone(),
1881                force_promote: None,
1882                force_rollout: self.spec.force_rollout,
1883                rollout_strategy: self.spec.rollout_strategy.clone(),
1884                rollout_request_timeout: self.spec.rollout_request_timeout.clone(),
1885                backend_secret_name: self.spec.backend_secret_name.clone(),
1886                authenticator_kind: self.spec.authenticator_kind,
1887                enable_rbac: self.spec.enable_rbac,
1888                environment_id: self.spec.environment_id,
1889                system_parameter_configmap_name: self.spec.system_parameter_configmap_name.clone(),
1890                additional_trust_bundle: self.spec.additional_trust_bundle.clone(),
1891                balancerd_external_certificate_spec: None,
1892                console_external_certificate_spec: None,
1893                internal_certificate_spec: self.spec.internal_certificate_spec.clone(),
1894            };
1895            hasher.update(&serde_json::to_vec(&spec).unwrap());
1896            if let Some(annotation) = self
1897                .metadata
1898                .annotations
1899                .as_ref()
1900                .and_then(|annotations| annotations.get(FORCE_ROLLOUT_ANNOTATION))
1901            {
1902                hasher.update(annotation);
1903            }
1904            hex::encode(hasher.finalize())
1905        }
1906
1907        pub fn backend_secret_name(&self) -> String {
1908            self.spec.backend_secret_name.clone()
1909        }
1910
1911        pub fn namespace(&self) -> String {
1912            self.meta().namespace.clone().unwrap()
1913        }
1914
1915        pub fn create_service_account(&self) -> bool {
1916            self.spec.service_account_name.is_none()
1917        }
1918
1919        pub fn service_account_name(&self) -> String {
1920            self.spec
1921                .service_account_name
1922                .clone()
1923                .unwrap_or_else(|| self.name_unchecked())
1924        }
1925
1926        pub fn role_name(&self) -> String {
1927            self.name_unchecked()
1928        }
1929
1930        pub fn role_binding_name(&self) -> String {
1931            self.name_unchecked()
1932        }
1933
1934        pub fn environmentd_statefulset_name(&self, generation: u64) -> String {
1935            self.name_prefixed(&format!("environmentd-{generation}"))
1936        }
1937
1938        pub fn environmentd_app_name(&self) -> String {
1939            "environmentd".to_owned()
1940        }
1941
1942        pub fn environmentd_service_name(&self) -> String {
1943            self.name_prefixed("environmentd")
1944        }
1945
1946        pub fn environmentd_service_internal_fqdn(&self) -> String {
1947            format!(
1948                "{}.{}.svc.cluster.local",
1949                self.environmentd_service_name(),
1950                self.meta().namespace.as_ref().unwrap()
1951            )
1952        }
1953
1954        pub fn environmentd_generation_service_name(&self, generation: u64) -> String {
1955            self.name_prefixed(&format!("environmentd-{generation}"))
1956        }
1957
1958        pub fn balancerd_app_name(&self) -> String {
1959            "balancerd".to_owned()
1960        }
1961
1962        pub fn environmentd_certificate_name(&self) -> String {
1963            self.name_prefixed("environmentd-external")
1964        }
1965
1966        pub fn environmentd_certificate_secret_name(&self) -> String {
1967            self.name_prefixed("environmentd-tls")
1968        }
1969
1970        pub fn balancerd_deployment_name(&self) -> String {
1971            self.name_prefixed("balancerd")
1972        }
1973
1974        pub fn balancerd_service_name(&self) -> String {
1975            self.name_prefixed("balancerd")
1976        }
1977
1978        pub fn console_app_name(&self) -> String {
1979            "console".to_owned()
1980        }
1981
1982        pub fn balancerd_external_certificate_name(&self) -> String {
1983            self.name_prefixed("balancerd-external")
1984        }
1985
1986        pub fn balancerd_external_certificate_secret_name(&self) -> String {
1987            self.name_prefixed("balancerd-external-tls")
1988        }
1989
1990        pub fn balancerd_replicas(&self) -> i32 {
1991            self.spec.balancerd_replicas.unwrap_or(2)
1992        }
1993
1994        pub fn console_replicas(&self) -> i32 {
1995            self.spec.console_replicas.unwrap_or(2)
1996        }
1997
1998        pub fn console_configmap_name(&self) -> String {
1999            self.name_prefixed("console")
2000        }
2001
2002        pub fn console_deployment_name(&self) -> String {
2003            self.name_prefixed("console")
2004        }
2005
2006        pub fn console_service_name(&self) -> String {
2007            self.name_prefixed("console")
2008        }
2009
2010        pub fn console_external_certificate_name(&self) -> String {
2011            self.name_prefixed("console-external")
2012        }
2013
2014        pub fn console_external_certificate_secret_name(&self) -> String {
2015            self.name_prefixed("console-external-tls")
2016        }
2017
2018        pub fn persist_pubsub_service_name(&self, generation: u64) -> String {
2019            self.name_prefixed(&format!("persist-pubsub-{generation}"))
2020        }
2021
2022        pub fn listeners_configmap_name(&self, generation: u64) -> String {
2023            self.name_prefixed(&format!("listeners-{generation}"))
2024        }
2025
2026        pub fn name_prefixed(&self, suffix: &str) -> String {
2027            format!("mz{}-{}", self.resource_id(), suffix)
2028        }
2029
2030        pub fn resource_id(&self) -> &str {
2031            &self.status.as_ref().unwrap().resource_id
2032        }
2033
2034        pub fn system_parameter_configmap_name(&self) -> Option<String> {
2035            self.spec.system_parameter_configmap_name.clone()
2036        }
2037
2038        pub fn environmentd_scratch_volume_storage_requirement(&self) -> Quantity {
2039            self.spec
2040                .environmentd_scratch_volume_storage_requirement
2041                .clone()
2042                .unwrap_or_else(|| {
2043                    self.spec
2044                        .environmentd_resource_requirements
2045                        .as_ref()
2046                        .and_then(|requirements| {
2047                            requirements
2048                                .requests
2049                                .as_ref()
2050                                .or(requirements.limits.as_ref())
2051                        })
2052                        // TODO: in cloud, we've been defaulting to twice the
2053                        // memory limit, but k8s-openapi doesn't seem to
2054                        // provide any way to parse Quantity values, so there
2055                        // isn't an easy way to do arithmetic on it
2056                        .and_then(|requirements| requirements.get("memory").cloned())
2057                        // TODO: is there a better default to use here?
2058                        .unwrap_or_else(|| Quantity("4096Mi".to_string()))
2059                })
2060        }
2061
2062        pub fn environment_id(&self, cloud_provider: &str, region: &str) -> String {
2063            format!(
2064                "{}-{}-{}-0",
2065                cloud_provider, region, self.spec.environment_id,
2066            )
2067        }
2068
2069        pub fn rollout_requested(&self) -> bool {
2070            self.status
2071                .as_ref()
2072                .map(|status| status.last_completed_rollout_hash != status.requested_rollout_hash)
2073                .unwrap_or(false)
2074        }
2075
2076        pub fn set_force_promote(&mut self) {
2077            self.spec.force_promote = Some(self.generate_rollout_hash());
2078        }
2079
2080        pub fn should_force_promote(&self) -> bool {
2081            self.spec.force_promote.as_ref()
2082                == self
2083                    .status
2084                    .as_ref()
2085                    .and_then(|status| status.requested_rollout_hash.as_ref())
2086                || self.spec.rollout_strategy
2087                    == MaterializeRolloutStrategy::ImmediatelyPromoteCausingDowntime
2088        }
2089
2090        pub fn conditions_need_update(&self) -> bool {
2091            let Some(status) = self.status.as_ref() else {
2092                return true;
2093            };
2094            if status.conditions.is_empty() {
2095                return true;
2096            }
2097            for condition in &status.conditions {
2098                if condition.observed_generation != self.meta().generation {
2099                    return true;
2100                }
2101            }
2102            false
2103        }
2104
2105        pub fn is_ready_to_promote(&self, rollout_hash: &str) -> bool {
2106            let Some(status) = self.status.as_ref() else {
2107                return false;
2108            };
2109            if status.conditions.is_empty() {
2110                return false;
2111            }
2112            status
2113                .conditions
2114                .iter()
2115                .any(|condition| condition.reason == "ReadyToPromote")
2116                && status.requested_rollout_hash.as_deref() == Some(rollout_hash)
2117        }
2118
2119        pub fn is_promoting(&self) -> bool {
2120            let Some(status) = self.status.as_ref() else {
2121                return false;
2122            };
2123            if status.conditions.is_empty() {
2124                return false;
2125            }
2126            status
2127                .conditions
2128                .iter()
2129                .any(|condition| condition.reason == "Promoting")
2130        }
2131
2132        pub fn update_in_progress(&self) -> bool {
2133            let Some(status) = self.status.as_ref() else {
2134                return false;
2135            };
2136            if status.conditions.is_empty() {
2137                return false;
2138            }
2139            for condition in &status.conditions {
2140                if condition.type_ == "UpToDate" && condition.status == "Unknown" {
2141                    return true;
2142                }
2143            }
2144            false
2145        }
2146
2147        /// Checks that the given version is greater than or equal
2148        /// to the existing version, if the existing version
2149        /// can be parsed.
2150        pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
2151            let version = parse_image_ref(&self.spec.environmentd_image_ref);
2152            match version {
2153                // Use cmp_precedence() to ignore build metadata per SemVer 2.0.0 spec
2154                Some(version) => version.cmp_precedence(minimum).is_ge(),
2155                // In the rare case that we see an image reference
2156                // that we can't parse, we assume that it satisfies all
2157                // version checks. Usually these are custom images that have
2158                // been by a developer on a branch forked from a recent copy
2159                // of main, and so this works out reasonably well in practice.
2160                None => {
2161                    tracing::warn!(
2162                        image_ref = %self.spec.environmentd_image_ref,
2163                        "failed to parse image ref",
2164                    );
2165                    true
2166                }
2167            }
2168        }
2169
2170        /// This check isn't strictly required since environmentd will still be able to determine
2171        /// if the upgrade is allowed or not. However, doing this check allows us to provide
2172        /// the error as soon as possible and in a more user friendly way.
2173        pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
2174            // Don't allow rolling back
2175            // Note: semver comparison handles RC versions correctly:
2176            // v26.0.0-rc.1 < v26.0.0-rc.2 < v26.0.0
2177            // Use cmp_precedence() to ignore build metadata
2178            if next_version.cmp_precedence(active_version) == std::cmp::Ordering::Less {
2179                return false;
2180            }
2181
2182            if active_version.major == 0 {
2183                if next_version.major != active_version.major {
2184                    if next_version.major == 26 {
2185                        // We require customers to upgrade from 0.147.20 (Self Managed 25.2) or v0.164.X (Cloud)
2186                        // before upgrading to 26.0.0
2187
2188                        return (active_version.minor == 147 && active_version.patch >= 20)
2189                            || active_version.minor >= 164;
2190                    } else {
2191                        return false;
2192                    }
2193                }
2194                // Self managed 25.1 to 25.2
2195                if next_version.minor == 147 && active_version.minor == 130 {
2196                    return true;
2197                }
2198                // only allow upgrading a single minor version at a time
2199                return next_version.minor <= active_version.minor + 1;
2200            } else if active_version.major >= 26 {
2201                // For versions 26.X.X and onwards, we deny upgrades past 1 major version of the active version
2202                return next_version.major <= active_version.major + 1;
2203            }
2204
2205            true
2206        }
2207
2208        /// Checks if the current environmentd image ref is within the upgrade window of the last
2209        /// successful rollout.
2210        pub fn within_upgrade_window(&self) -> bool {
2211            let active_environmentd_version = self
2212                .status
2213                .as_ref()
2214                .and_then(|status| {
2215                    status
2216                        .last_completed_rollout_environmentd_image_ref
2217                        .as_ref()
2218                })
2219                .and_then(|image_ref| parse_image_ref(image_ref));
2220
2221            if let (Some(next_environmentd_version), Some(active_environmentd_version)) = (
2222                parse_image_ref(&self.spec.environmentd_image_ref),
2223                active_environmentd_version,
2224            ) {
2225                Self::is_valid_upgrade_version(
2226                    &active_environmentd_version,
2227                    &next_environmentd_version,
2228                )
2229            } else {
2230                // If we fail to parse either version,
2231                // we still allow the upgrade since environmentd will still error if the upgrade is not allowed.
2232                true
2233            }
2234        }
2235
2236        pub fn status(&self) -> MaterializeStatus {
2237            self.status.clone().unwrap_or_else(|| {
2238                let mut status = MaterializeStatus::default();
2239
2240                // If we're creating the initial status on a recreated
2241                // Environment, restore what the old resource's status held.
2242                let initial =
2243                    InitialStatusAnnotations::parse(self.annotations()).unwrap_or_else(|e| {
2244                        warn!("ignoring initial status annotations: {e}");
2245                        InitialStatusAnnotations::default()
2246                    });
2247
2248                status.resource_id = initial.resource_id.unwrap_or_else(new_resource_id);
2249
2250                if let Some(active_generation) = initial.active_generation {
2251                    status.active_generation = active_generation;
2252                }
2253
2254                // Initialize the last completed rollout environmentd image ref to
2255                // the current image ref if not already set.
2256                status.last_completed_rollout_environmentd_image_ref =
2257                    Some(self.spec.environmentd_image_ref.clone());
2258
2259                status
2260            })
2261        }
2262    }
2263
2264    #[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema, PartialEq)]
2265    #[serde(rename_all = "camelCase")]
2266    pub struct MaterializeStatus {
2267        /// Resource identifier used as a name prefix to avoid pod name collisions.
2268        pub resource_id: String,
2269        /// The generation of Materialize pods actively capable of servicing requests.
2270        pub active_generation: u64,
2271        /// The image ref of the environmentd image that was last successfully rolled out.
2272        /// Used to deny upgrades past 1 major version from the last successful rollout.
2273        /// When None, we upgrade anyways.
2274        pub last_completed_rollout_environmentd_image_ref: Option<String>,
2275        /// The last completed rollout's requestedRolloutHash.
2276        pub last_completed_rollout_hash: Option<String>,
2277        /// Hash of a subset of the Materialize spec and other fields.
2278        /// This is used to determine when the spec has changed and we need to rollout.
2279        pub requested_rollout_hash: Option<String>,
2280        pub conditions: Vec<Condition>,
2281    }
2282
2283    impl MaterializeStatus {
2284        pub fn needs_update(&self, other: &Self) -> bool {
2285            let now = Timestamp::now();
2286            let mut a = self.clone();
2287            for condition in &mut a.conditions {
2288                condition.last_transition_time = Time(now);
2289            }
2290            let mut b = other.clone();
2291            for condition in &mut b.conditions {
2292                condition.last_transition_time = Time(now);
2293            }
2294            a != b
2295        }
2296    }
2297
2298    impl ManagedResource for Materialize {
2299        fn default_labels(&self) -> BTreeMap<String, String> {
2300            BTreeMap::from_iter([
2301                (
2302                    "materialize.cloud/organization-name".to_owned(),
2303                    self.name_unchecked(),
2304                ),
2305                (
2306                    "materialize.cloud/organization-namespace".to_owned(),
2307                    self.namespace(),
2308                ),
2309                (
2310                    "materialize.cloud/mz-resource-id".to_owned(),
2311                    self.resource_id().to_owned(),
2312                ),
2313            ])
2314        }
2315
2316        fn app_name(&self) -> Option<&str> {
2317            Some("environmentd")
2318        }
2319    }
2320
2321    impl From<v1alpha1::Materialize> for Materialize {
2322        fn from(value: v1alpha1::Materialize) -> Self {
2323            let is_promoting = value.is_promoting();
2324            let service_account_annotations = if let Some(environmentd_iam_role_arn) =
2325                value.spec.environmentd_iam_role_arn
2326            {
2327                let mut annotations = value.spec.service_account_annotations.unwrap_or_default();
2328                annotations
2329                    .entry("eks.amazonaws.com/role-arn".to_owned())
2330                    .or_insert(environmentd_iam_role_arn);
2331                Some(annotations)
2332            } else {
2333                value.spec.service_account_annotations
2334            };
2335            let mut mz = Materialize {
2336                metadata: value.metadata,
2337                spec: MaterializeSpec {
2338                    environmentd_image_ref: value.spec.environmentd_image_ref,
2339                    environmentd_extra_args: value.spec.environmentd_extra_args,
2340                    environmentd_extra_env: value.spec.environmentd_extra_env,
2341                    environmentd_connection_role_arn: value.spec.environmentd_connection_role_arn,
2342                    environmentd_resource_requirements: value
2343                        .spec
2344                        .environmentd_resource_requirements,
2345                    environmentd_scratch_volume_storage_requirement: value
2346                        .spec
2347                        .environmentd_scratch_volume_storage_requirement,
2348                    environmentd_readiness_probe: value.spec.environmentd_readiness_probe,
2349                    environmentd_liveness_probe: value.spec.environmentd_liveness_probe,
2350                    environmentd_startup_probe: value.spec.environmentd_startup_probe,
2351                    balancerd_resource_requirements: value.spec.balancerd_resource_requirements,
2352                    balancerd_configmap_name: value.spec.balancerd_configmap_name,
2353                    console_resource_requirements: value.spec.console_resource_requirements,
2354                    balancerd_replicas: value.spec.balancerd_replicas,
2355                    balancerd_externally_scaled: value.spec.balancerd_externally_scaled,
2356                    console_replicas: value.spec.console_replicas,
2357                    service_account_name: value.spec.service_account_name,
2358                    service_account_annotations,
2359                    service_account_labels: value.spec.service_account_labels,
2360                    pod_annotations: value.spec.pod_annotations,
2361                    pod_labels: value.spec.pod_labels,
2362                    force_promote: if value.spec.force_promote.is_empty()
2363                        || &value.spec.force_promote == "00000000-0000-0000-0000-000000000000"
2364                    {
2365                        None
2366                    } else {
2367                        Some(value.spec.force_promote.to_string())
2368                    },
2369                    force_rollout: value.spec.force_rollout,
2370                    rollout_strategy: value.spec.rollout_strategy,
2371                    rollout_request_timeout: value.spec.rollout_request_timeout,
2372                    backend_secret_name: value.spec.backend_secret_name,
2373                    authenticator_kind: value.spec.authenticator_kind,
2374                    enable_rbac: value.spec.enable_rbac,
2375                    environment_id: value.spec.environment_id,
2376                    system_parameter_configmap_name: value.spec.system_parameter_configmap_name,
2377                    additional_trust_bundle: value.spec.additional_trust_bundle,
2378                    balancerd_external_certificate_spec: value
2379                        .spec
2380                        .balancerd_external_certificate_spec,
2381                    console_external_certificate_spec: value.spec.console_external_certificate_spec,
2382                    internal_certificate_spec: value.spec.internal_certificate_spec,
2383                },
2384                status: None,
2385            };
2386            let calculated_rollout_hash = mz.generate_rollout_hash();
2387            let last_completed_rollout_hash = match value
2388                .status
2389                .as_ref()
2390                .and_then(|status| status.last_completed_rollout_hash.to_owned())
2391            {
2392                Some(last_completed_rollout_hash) => Some(last_completed_rollout_hash),
2393                None => {
2394                    let currently_rolling_out = value
2395                        .status
2396                        .as_ref()
2397                        .map(|status| {
2398                            status.last_completed_rollout_request != value.spec.request_rollout
2399                                // If this is the first apply,
2400                                // these could both be nil and we still need to do a rollout.
2401                                || status.last_completed_rollout_request.is_nil()
2402                        })
2403                        .unwrap_or(true);
2404                    if currently_rolling_out {
2405                        // If they store a change, we're going to start over on a new rollout.
2406                        None
2407                    } else {
2408                        Some(calculated_rollout_hash.clone())
2409                    }
2410                }
2411            };
2412            let requested_rollout_hash = if is_promoting {
2413                None
2414            } else {
2415                Some(calculated_rollout_hash)
2416            };
2417            mz.status = value.status.map(|status| MaterializeStatus {
2418                resource_id: status.resource_id,
2419                active_generation: status.active_generation,
2420                last_completed_rollout_environmentd_image_ref: status
2421                    .last_completed_rollout_environmentd_image_ref,
2422                last_completed_rollout_hash,
2423                requested_rollout_hash,
2424                conditions: status.conditions,
2425            });
2426            mz
2427        }
2428    }
2429
2430    /// Partial mirror of [`MaterializeSpec`] for field-wise conversion of
2431    /// objects that may be incomplete. See [`super::convert_v1alpha1_to_v1`].
2432    ///
2433    /// Each field is a [`PartialField`], distinguishing absent from explicit
2434    /// null from a value, and unknown fields pass through via `extra`, so
2435    /// serializing reproduces exactly what was deserialized. Adding a field
2436    /// to [`MaterializeSpec`] breaks the exhaustive destructures in the
2437    /// `From` impls below until its conversion is decided.
2438    #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
2439    #[serde(rename_all = "camelCase")]
2440    pub struct PartialMaterializeSpec {
2441        #[serde(
2442            default,
2443            with = "double_option",
2444            skip_serializing_if = "Option::is_none"
2445        )]
2446        pub environmentd_image_ref: PartialField,
2447        #[serde(
2448            default,
2449            with = "double_option",
2450            skip_serializing_if = "Option::is_none"
2451        )]
2452        pub environmentd_extra_args: PartialField,
2453        #[serde(
2454            default,
2455            with = "double_option",
2456            skip_serializing_if = "Option::is_none"
2457        )]
2458        pub environmentd_extra_env: PartialField,
2459        #[serde(
2460            default,
2461            with = "double_option",
2462            skip_serializing_if = "Option::is_none"
2463        )]
2464        pub environmentd_connection_role_arn: PartialField,
2465        #[serde(
2466            default,
2467            with = "double_option",
2468            skip_serializing_if = "Option::is_none"
2469        )]
2470        pub environmentd_resource_requirements: PartialField,
2471        #[serde(
2472            default,
2473            with = "double_option",
2474            skip_serializing_if = "Option::is_none"
2475        )]
2476        pub environmentd_scratch_volume_storage_requirement: PartialField,
2477        #[serde(
2478            default,
2479            with = "double_option",
2480            skip_serializing_if = "Option::is_none"
2481        )]
2482        pub environmentd_readiness_probe: PartialField,
2483        #[serde(
2484            default,
2485            with = "double_option",
2486            skip_serializing_if = "Option::is_none"
2487        )]
2488        pub environmentd_liveness_probe: PartialField,
2489        #[serde(
2490            default,
2491            with = "double_option",
2492            skip_serializing_if = "Option::is_none"
2493        )]
2494        pub environmentd_startup_probe: PartialField,
2495        #[serde(
2496            default,
2497            with = "double_option",
2498            skip_serializing_if = "Option::is_none"
2499        )]
2500        pub balancerd_resource_requirements: PartialField,
2501        #[serde(
2502            default,
2503            with = "double_option",
2504            skip_serializing_if = "Option::is_none"
2505        )]
2506        pub balancerd_configmap_name: PartialField,
2507        #[serde(
2508            default,
2509            with = "double_option",
2510            skip_serializing_if = "Option::is_none"
2511        )]
2512        pub console_resource_requirements: PartialField,
2513        #[serde(
2514            default,
2515            with = "double_option",
2516            skip_serializing_if = "Option::is_none"
2517        )]
2518        pub balancerd_replicas: PartialField,
2519        #[serde(
2520            default,
2521            with = "double_option",
2522            skip_serializing_if = "Option::is_none"
2523        )]
2524        pub balancerd_externally_scaled: PartialField,
2525        #[serde(
2526            default,
2527            with = "double_option",
2528            skip_serializing_if = "Option::is_none"
2529        )]
2530        pub console_replicas: PartialField,
2531        #[serde(
2532            default,
2533            with = "double_option",
2534            skip_serializing_if = "Option::is_none"
2535        )]
2536        pub service_account_name: PartialField,
2537        #[serde(
2538            default,
2539            with = "double_option",
2540            skip_serializing_if = "Option::is_none"
2541        )]
2542        pub service_account_annotations: PartialField,
2543        #[serde(
2544            default,
2545            with = "double_option",
2546            skip_serializing_if = "Option::is_none"
2547        )]
2548        pub service_account_labels: PartialField,
2549        #[serde(
2550            default,
2551            with = "double_option",
2552            skip_serializing_if = "Option::is_none"
2553        )]
2554        pub pod_annotations: PartialField,
2555        #[serde(
2556            default,
2557            with = "double_option",
2558            skip_serializing_if = "Option::is_none"
2559        )]
2560        pub pod_labels: PartialField,
2561        #[serde(
2562            default,
2563            with = "double_option",
2564            skip_serializing_if = "Option::is_none"
2565        )]
2566        pub force_promote: PartialField,
2567        #[serde(
2568            default,
2569            with = "double_option",
2570            skip_serializing_if = "Option::is_none"
2571        )]
2572        pub force_rollout: PartialField,
2573        #[serde(
2574            default,
2575            with = "double_option",
2576            skip_serializing_if = "Option::is_none"
2577        )]
2578        pub rollout_strategy: PartialField,
2579        #[serde(
2580            default,
2581            with = "double_option",
2582            skip_serializing_if = "Option::is_none"
2583        )]
2584        pub rollout_request_timeout: PartialField,
2585        #[serde(
2586            default,
2587            with = "double_option",
2588            skip_serializing_if = "Option::is_none"
2589        )]
2590        pub backend_secret_name: PartialField,
2591        #[serde(
2592            default,
2593            with = "double_option",
2594            skip_serializing_if = "Option::is_none"
2595        )]
2596        pub authenticator_kind: PartialField,
2597        #[serde(
2598            default,
2599            with = "double_option",
2600            skip_serializing_if = "Option::is_none"
2601        )]
2602        pub enable_rbac: PartialField,
2603        #[serde(
2604            default,
2605            with = "double_option",
2606            skip_serializing_if = "Option::is_none"
2607        )]
2608        pub environment_id: PartialField,
2609        #[serde(
2610            default,
2611            with = "double_option",
2612            skip_serializing_if = "Option::is_none"
2613        )]
2614        pub system_parameter_configmap_name: PartialField,
2615        #[serde(
2616            default,
2617            with = "double_option",
2618            skip_serializing_if = "Option::is_none"
2619        )]
2620        pub additional_trust_bundle: PartialField,
2621        #[serde(
2622            default,
2623            with = "double_option",
2624            skip_serializing_if = "Option::is_none"
2625        )]
2626        pub balancerd_external_certificate_spec: PartialField,
2627        #[serde(
2628            default,
2629            with = "double_option",
2630            skip_serializing_if = "Option::is_none"
2631        )]
2632        pub console_external_certificate_spec: PartialField,
2633        #[serde(
2634            default,
2635            with = "double_option",
2636            skip_serializing_if = "Option::is_none"
2637        )]
2638        pub internal_certificate_spec: PartialField,
2639        #[serde(flatten)]
2640        pub extra: serde_json::Map<String, serde_json::Value>,
2641    }
2642
2643    /// Partial mirror of [`MaterializeStatus`], see [`PartialMaterializeSpec`].
2644    #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
2645    #[serde(rename_all = "camelCase")]
2646    pub struct PartialMaterializeStatus {
2647        #[serde(
2648            default,
2649            with = "double_option",
2650            skip_serializing_if = "Option::is_none"
2651        )]
2652        pub resource_id: PartialField,
2653        #[serde(
2654            default,
2655            with = "double_option",
2656            skip_serializing_if = "Option::is_none"
2657        )]
2658        pub active_generation: PartialField,
2659        #[serde(
2660            default,
2661            with = "double_option",
2662            skip_serializing_if = "Option::is_none"
2663        )]
2664        pub last_completed_rollout_environmentd_image_ref: PartialField,
2665        #[serde(
2666            default,
2667            with = "double_option",
2668            skip_serializing_if = "Option::is_none"
2669        )]
2670        pub last_completed_rollout_hash: PartialField,
2671        #[serde(
2672            default,
2673            with = "double_option",
2674            skip_serializing_if = "Option::is_none"
2675        )]
2676        pub requested_rollout_hash: PartialField,
2677        #[serde(
2678            default,
2679            with = "double_option",
2680            skip_serializing_if = "Option::is_none"
2681        )]
2682        pub conditions: PartialField,
2683        #[serde(flatten)]
2684        pub extra: serde_json::Map<String, serde_json::Value>,
2685    }
2686
2687    /// Partial mirror of [`Materialize`], see [`PartialMaterializeSpec`].
2688    #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
2689    #[serde(rename_all = "camelCase")]
2690    pub struct PartialMaterialize {
2691        #[serde(skip_serializing_if = "Option::is_none")]
2692        pub api_version: Option<String>,
2693        #[serde(skip_serializing_if = "Option::is_none")]
2694        pub kind: Option<serde_json::Value>,
2695        #[serde(skip_serializing_if = "Option::is_none")]
2696        pub metadata: Option<serde_json::Value>,
2697        #[serde(skip_serializing_if = "Option::is_none")]
2698        pub spec: Option<PartialMaterializeSpec>,
2699        #[serde(skip_serializing_if = "Option::is_none")]
2700        pub status: Option<PartialMaterializeStatus>,
2701        #[serde(flatten)]
2702        pub extra: serde_json::Map<String, serde_json::Value>,
2703    }
2704
2705    impl From<MaterializeSpec> for PartialMaterializeSpec {
2706        fn from(spec: MaterializeSpec) -> Self {
2707            let MaterializeSpec {
2708                environmentd_image_ref,
2709                environmentd_extra_args,
2710                environmentd_extra_env,
2711                environmentd_connection_role_arn,
2712                environmentd_resource_requirements,
2713                environmentd_scratch_volume_storage_requirement,
2714                environmentd_readiness_probe,
2715                environmentd_liveness_probe,
2716                environmentd_startup_probe,
2717                balancerd_resource_requirements,
2718                balancerd_configmap_name,
2719                console_resource_requirements,
2720                balancerd_replicas,
2721                balancerd_externally_scaled,
2722                console_replicas,
2723                service_account_name,
2724                service_account_annotations,
2725                service_account_labels,
2726                pod_annotations,
2727                pod_labels,
2728                force_promote,
2729                force_rollout,
2730                rollout_strategy,
2731                rollout_request_timeout,
2732                backend_secret_name,
2733                authenticator_kind,
2734                enable_rbac,
2735                environment_id,
2736                system_parameter_configmap_name,
2737                additional_trust_bundle,
2738                balancerd_external_certificate_spec,
2739                console_external_certificate_spec,
2740                internal_certificate_spec,
2741            } = spec;
2742            Self {
2743                environmentd_image_ref: present(environmentd_image_ref),
2744                environmentd_extra_args: present_opt(environmentd_extra_args),
2745                environmentd_extra_env: present_opt(environmentd_extra_env),
2746                environmentd_connection_role_arn: present_opt(environmentd_connection_role_arn),
2747                environmentd_resource_requirements: present_opt(environmentd_resource_requirements),
2748                environmentd_scratch_volume_storage_requirement: present_opt(
2749                    environmentd_scratch_volume_storage_requirement,
2750                ),
2751                environmentd_readiness_probe: present_opt(environmentd_readiness_probe),
2752                environmentd_liveness_probe: present_opt(environmentd_liveness_probe),
2753                environmentd_startup_probe: present_opt(environmentd_startup_probe),
2754                balancerd_resource_requirements: present_opt(balancerd_resource_requirements),
2755                balancerd_configmap_name: present_opt(balancerd_configmap_name),
2756                console_resource_requirements: present_opt(console_resource_requirements),
2757                balancerd_replicas: present_opt(balancerd_replicas),
2758                balancerd_externally_scaled: present_opt(balancerd_externally_scaled),
2759                console_replicas: present_opt(console_replicas),
2760                service_account_name: present_opt(service_account_name),
2761                service_account_annotations: present_opt(service_account_annotations),
2762                service_account_labels: present_opt(service_account_labels),
2763                pod_annotations: present_opt(pod_annotations),
2764                pod_labels: present_opt(pod_labels),
2765                force_promote: present_opt(force_promote),
2766                force_rollout: present(force_rollout),
2767                rollout_strategy: present(rollout_strategy),
2768                rollout_request_timeout: present(rollout_request_timeout),
2769                backend_secret_name: present(backend_secret_name),
2770                authenticator_kind: present(authenticator_kind),
2771                enable_rbac: present(enable_rbac),
2772                environment_id: present(environment_id),
2773                system_parameter_configmap_name: present_opt(system_parameter_configmap_name),
2774                additional_trust_bundle: present_opt(additional_trust_bundle),
2775                balancerd_external_certificate_spec: present_opt(
2776                    balancerd_external_certificate_spec,
2777                ),
2778                console_external_certificate_spec: present_opt(console_external_certificate_spec),
2779                internal_certificate_spec: present_opt(internal_certificate_spec),
2780                extra: serde_json::Map::new(),
2781            }
2782        }
2783    }
2784
2785    impl From<MaterializeStatus> for PartialMaterializeStatus {
2786        fn from(status: MaterializeStatus) -> Self {
2787            let MaterializeStatus {
2788                resource_id,
2789                active_generation,
2790                last_completed_rollout_environmentd_image_ref,
2791                last_completed_rollout_hash,
2792                requested_rollout_hash,
2793                conditions,
2794            } = status;
2795            Self {
2796                resource_id: present(resource_id),
2797                active_generation: present(active_generation),
2798                last_completed_rollout_environmentd_image_ref: present_opt(
2799                    last_completed_rollout_environmentd_image_ref,
2800                ),
2801                last_completed_rollout_hash: present_opt(last_completed_rollout_hash),
2802                requested_rollout_hash: present_opt(requested_rollout_hash),
2803                conditions: present(conditions),
2804                extra: serde_json::Map::new(),
2805            }
2806        }
2807    }
2808
2809    impl From<Materialize> for PartialMaterialize {
2810        fn from(mz: Materialize) -> Self {
2811            let Materialize {
2812                metadata,
2813                spec,
2814                status,
2815            } = mz;
2816            Self {
2817                api_version: Some("materialize.cloud/v1".to_owned()),
2818                kind: Some("Materialize".into()),
2819                metadata: Some(
2820                    serde_json::to_value(metadata).expect("ObjectMeta serializes to JSON"),
2821                ),
2822                spec: Some(spec.into()),
2823                status: status.map(Into::into),
2824                extra: serde_json::Map::new(),
2825            }
2826        }
2827    }
2828
2829    impl From<super::v1alpha1::PartialMaterializeSpec> for PartialMaterializeSpec {
2830        fn from(spec: super::v1alpha1::PartialMaterializeSpec) -> Self {
2831            let super::v1alpha1::PartialMaterializeSpec {
2832                environmentd_image_ref,
2833                environmentd_extra_args,
2834                environmentd_extra_env,
2835                environmentd_iam_role_arn,
2836                environmentd_connection_role_arn,
2837                environmentd_resource_requirements,
2838                environmentd_scratch_volume_storage_requirement,
2839                environmentd_readiness_probe,
2840                environmentd_liveness_probe,
2841                environmentd_startup_probe,
2842                balancerd_resource_requirements,
2843                balancerd_configmap_name,
2844                console_resource_requirements,
2845                balancerd_replicas,
2846                balancerd_externally_scaled,
2847                console_replicas,
2848                service_account_name,
2849                service_account_annotations,
2850                service_account_labels,
2851                pod_annotations,
2852                pod_labels,
2853                request_rollout: _,
2854                force_promote,
2855                force_rollout,
2856                in_place_rollout: _,
2857                rollout_strategy,
2858                rollout_request_timeout,
2859                backend_secret_name,
2860                authenticator_kind,
2861                enable_rbac,
2862                environment_id,
2863                system_parameter_configmap_name,
2864                additional_trust_bundle,
2865                balancerd_external_certificate_spec,
2866                console_external_certificate_spec,
2867                internal_certificate_spec,
2868                extra,
2869            } = spec;
2870            let service_account_annotations = merge_environmentd_iam_role_arn(
2871                service_account_annotations,
2872                environmentd_iam_role_arn,
2873            );
2874            // "" and the nil UUID mean "not force promoting" in v1alpha1,
2875            // which v1 spells as an absent field.
2876            let force_promote = match force_promote {
2877                Some(Some(value)) if value == "" || value == NIL_UUID_STR => None,
2878                other => other,
2879            };
2880            Self {
2881                environmentd_image_ref,
2882                environmentd_extra_args,
2883                environmentd_extra_env,
2884                environmentd_connection_role_arn,
2885                environmentd_resource_requirements,
2886                environmentd_scratch_volume_storage_requirement,
2887                environmentd_readiness_probe,
2888                environmentd_liveness_probe,
2889                environmentd_startup_probe,
2890                balancerd_resource_requirements,
2891                balancerd_configmap_name,
2892                console_resource_requirements,
2893                balancerd_replicas,
2894                balancerd_externally_scaled,
2895                console_replicas,
2896                service_account_name,
2897                service_account_annotations,
2898                service_account_labels,
2899                pod_annotations,
2900                pod_labels,
2901                force_promote,
2902                force_rollout,
2903                rollout_strategy,
2904                rollout_request_timeout,
2905                backend_secret_name,
2906                authenticator_kind,
2907                enable_rbac,
2908                environment_id,
2909                system_parameter_configmap_name,
2910                additional_trust_bundle,
2911                balancerd_external_certificate_spec,
2912                console_external_certificate_spec,
2913                internal_certificate_spec,
2914                extra,
2915            }
2916        }
2917    }
2918
2919    impl From<super::v1alpha1::PartialMaterializeStatus> for PartialMaterializeStatus {
2920        fn from(status: super::v1alpha1::PartialMaterializeStatus) -> Self {
2921            let super::v1alpha1::PartialMaterializeStatus {
2922                resource_id,
2923                active_generation,
2924                last_completed_rollout_request: _,
2925                last_completed_rollout_environmentd_image_ref,
2926                resources_hash: _,
2927                last_completed_rollout_hash,
2928                conditions,
2929                extra,
2930            } = status;
2931            Self {
2932                resource_id,
2933                active_generation,
2934                last_completed_rollout_environmentd_image_ref,
2935                last_completed_rollout_hash,
2936                // Derived from the complete object, spliced in by
2937                // `convert_v1alpha1_to_v1` when the input is complete, left
2938                // absent for partial objects so a field manager cannot gain
2939                // ownership of a field it never set.
2940                requested_rollout_hash: None,
2941                conditions,
2942                extra,
2943            }
2944        }
2945    }
2946
2947    impl From<super::v1alpha1::PartialMaterialize> for PartialMaterialize {
2948        fn from(mz: super::v1alpha1::PartialMaterialize) -> Self {
2949            let super::v1alpha1::PartialMaterialize {
2950                api_version: _,
2951                kind,
2952                metadata,
2953                spec,
2954                status,
2955                extra,
2956            } = mz;
2957            Self {
2958                api_version: Some("materialize.cloud/v1".to_owned()),
2959                kind,
2960                metadata,
2961                spec: spec.map(Into::into),
2962                status: status.map(Into::into),
2963                extra,
2964            }
2965        }
2966    }
2967}
2968
2969/// The nil UUID rendered the way it appears in JSON-encoded specs.
2970const NIL_UUID_STR: &str = "00000000-0000-0000-0000-000000000000";
2971
2972/// One field of a partial object: absent (`None`), explicit null
2973/// (`Some(None)`), or a value (`Some(Some(_))`).
2974///
2975/// Values are untyped [`serde_json::Value`]s because conversion must be a
2976/// total function over anything schema-shaped, including values that do not
2977/// validate. The type system is used for field *names*: the partial mirror
2978/// structs convert via exhaustive destructures, so adding a field to a spec
2979/// without deciding its conversion does not compile.
2980pub type PartialField = Option<Option<serde_json::Value>>;
2981
2982/// Serde adapter for [`PartialField`] distinguishing explicit null from an
2983/// absent field. Use with `#[serde(default, with = "double_option",
2984/// skip_serializing_if = "Option::is_none")]`.
2985mod double_option {
2986    use serde::{Deserialize, Deserializer, Serialize, Serializer};
2987
2988    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
2989    where
2990        T: Deserialize<'de>,
2991        D: Deserializer<'de>,
2992    {
2993        Option::<T>::deserialize(deserializer).map(Some)
2994    }
2995
2996    pub fn serialize<T, S>(value: &Option<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
2997    where
2998        T: Serialize,
2999        S: Serializer,
3000    {
3001        match value {
3002            Some(inner) => inner.serialize(serializer),
3003            // Unreachable under skip_serializing_if = "Option::is_none".
3004            None => serializer.serialize_none(),
3005        }
3006    }
3007}
3008
3009/// A [`PartialField`] holding a value that is always present in the typed
3010/// struct.
3011fn present<T: Serialize>(value: T) -> PartialField {
3012    Some(Some(
3013        serde_json::to_value(value).expect("CRD field serializes to JSON"),
3014    ))
3015}
3016
3017/// A [`PartialField`] from a typed optional field, absent when `None`.
3018fn present_opt<T: Serialize>(value: Option<T>) -> PartialField {
3019    value.map(|value| Some(serde_json::to_value(value).expect("CRD field serializes to JSON")))
3020}
3021
3022/// Merges a v1alpha1 `environmentdIamRoleArn` value into the
3023/// `serviceAccountAnnotations` map as `eks.amazonaws.com/role-arn`, matching
3024/// the typed conversion. An existing annotation wins. Annotations that are
3025/// not an object pass through untouched.
3026fn merge_environmentd_iam_role_arn(
3027    annotations: PartialField,
3028    role_arn: PartialField,
3029) -> PartialField {
3030    let Some(Some(role_arn)) = role_arn else {
3031        return annotations;
3032    };
3033    let mut map = match annotations {
3034        Some(Some(serde_json::Value::Object(map))) => map,
3035        Some(Some(other)) => return Some(Some(other)),
3036        Some(None) | None => serde_json::Map::new(),
3037    };
3038    map.entry("eks.amazonaws.com/role-arn").or_insert(role_arn);
3039    Some(Some(serde_json::Value::Object(map)))
3040}
3041
3042/// Converts a JSON-encoded v1alpha1 Materialize object to v1, for use by the
3043/// CRD conversion webhook.
3044///
3045/// Output fields are exactly the input fields, mapped field-wise, plus
3046/// derived fields when the input is complete. Server-side apply round-trips
3047/// each field manager's owned subset of an object through the conversion
3048/// webhook when it reconciles managed fields recorded at another version.
3049/// Those subsets routinely lack required fields, so conversion must accept
3050/// partial objects, and it must not add fields the input did not carry,
3051/// since a field manager must not gain ownership of fields it never set.
3052///
3053/// Fields derived from the complete spec (`status.requestedRolloutHash`
3054/// here, `spec.requestRollout` in the other direction) cannot be computed
3055/// from a subset, so they are spliced in from the typed conversion only when
3056/// the input deserializes as a complete object. The request carries no
3057/// indicator of partialness, so a subset that happens to contain every
3058/// required field also gains the derived fields. That is the irreducible
3059/// ambiguity, and it is limited to exactly those fields.
3060pub fn convert_v1alpha1_to_v1(
3061    value: serde_json::Value,
3062) -> Result<serde_json::Value, anyhow::Error> {
3063    let complete = serde_json::from_value::<v1alpha1::Materialize>(value.clone()).ok();
3064    let partial: v1alpha1::PartialMaterialize = serde_json::from_value(value)?;
3065    let mut converted = v1::PartialMaterialize::from(partial);
3066    if let Some(complete) = complete {
3067        let typed = v1::Materialize::from(complete);
3068        if let (Some(status), Some(typed_status)) = (converted.status.as_mut(), typed.status) {
3069            status.requested_rollout_hash = present_opt(typed_status.requested_rollout_hash);
3070            status.last_completed_rollout_hash =
3071                present_opt(typed_status.last_completed_rollout_hash);
3072        }
3073    }
3074    Ok(serde_json::to_value(converted)?)
3075}
3076
3077/// Converts a JSON-encoded v1 Materialize object to v1alpha1, for use by the
3078/// CRD conversion webhook.
3079///
3080/// See [`convert_v1alpha1_to_v1`] for the conversion contract. In this
3081/// direction the derived fields are `spec.requestRollout` and
3082/// `status.lastCompletedRolloutRequest`, both deterministic UUIDs derived
3083/// from rollout hashes of the complete object, and `status.resourcesHash`,
3084/// which has no v1 counterpart but is required by the v1alpha1 schema
3085/// whenever a status is present, so complete conversions must carry the
3086/// typed conversion's placeholder to stay valid at the storage version.
3087pub fn convert_v1_to_v1alpha1(
3088    value: serde_json::Value,
3089) -> Result<serde_json::Value, anyhow::Error> {
3090    let complete = serde_json::from_value::<v1::Materialize>(value.clone()).ok();
3091    let partial: v1::PartialMaterialize = serde_json::from_value(value)?;
3092    let mut converted = v1alpha1::PartialMaterialize::from(partial);
3093    if let Some(complete) = complete {
3094        let typed = v1alpha1::Materialize::from(complete);
3095        if let Some(spec) = converted.spec.as_mut() {
3096            spec.request_rollout = present(typed.spec.request_rollout);
3097        }
3098        if let (Some(status), Some(typed_status)) = (converted.status.as_mut(), typed.status) {
3099            status.last_completed_rollout_request =
3100                present(typed_status.last_completed_rollout_request);
3101            status.resources_hash = present(typed_status.resources_hash);
3102        }
3103    }
3104    Ok(serde_json::to_value(converted)?)
3105}
3106
3107fn parse_image_ref(image_ref: &str) -> Option<Version> {
3108    image_ref
3109        .rsplit_once(':')
3110        .and_then(|(_repo, tag)| tag.strip_prefix('v'))
3111        .and_then(|tag| {
3112            // To work around Docker tag restrictions, build metadata in
3113            // a Docker tag is delimited by `--` rather than the SemVer
3114            // `+` delimiter. So we need to swap the delimiter back to
3115            // `+` before parsing it as SemVer.
3116            let tag = tag.replace("--", "+");
3117            Version::parse(&tag).ok()
3118        })
3119}
3120
3121#[cfg(test)]
3122mod tests {
3123    use std::time::Duration;
3124
3125    use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, Time};
3126    use k8s_openapi::jiff::Timestamp;
3127    use kube::core::ObjectMeta;
3128    use semver::Version;
3129
3130    use super::v1alpha1::{Materialize, MaterializeSpec, MaterializeStatus};
3131    use super::{
3132        AdditionalTrustBundle, DEFAULT_ROLLOUT_REQUEST_TIMEOUT, FORCE_ROLLOUT_ANNOTATION,
3133        InitialStatusAnnotations, LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION,
3134        LAST_KNOWN_RESOURCE_ID_ANNOTATION, RolloutRequestTimeout, TrustBundleKeyRef,
3135        TrustBundleSource,
3136    };
3137
3138    #[mz_ore::test]
3139    fn initial_status_from_annotations() {
3140        let mz = |annotations: &[(&str, &str)]| Materialize {
3141            spec: MaterializeSpec {
3142                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3143                ..Default::default()
3144            },
3145            metadata: ObjectMeta {
3146                annotations: Some(
3147                    annotations
3148                        .iter()
3149                        .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
3150                        .collect(),
3151                ),
3152                ..Default::default()
3153            },
3154            status: None,
3155        };
3156
3157        // Without the annotations, the resource ID is random and the
3158        // generation starts at 0.
3159        let status = mz(&[]).status();
3160        assert!(crate::crd::is_valid_resource_id(&status.resource_id));
3161        assert_eq!(status.active_generation, 0);
3162
3163        // Both annotations seed the initial status.
3164        let restored = mz(&[
3165            (LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION, "3"),
3166            (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "abcde01234"),
3167        ]);
3168        InitialStatusAnnotations::parse(restored.metadata.annotations.as_ref().unwrap()).unwrap();
3169        let status = restored.status();
3170        assert_eq!(status.resource_id, "abcde01234");
3171        assert_eq!(status.active_generation, 3);
3172
3173        // The v1 resource reads them the same way.
3174        let status = super::v1::Materialize {
3175            spec: Default::default(),
3176            metadata: restored.metadata.clone(),
3177            status: None,
3178        }
3179        .status();
3180        assert_eq!(status.resource_id, "abcde01234");
3181        assert_eq!(status.active_generation, 3);
3182
3183        // An existing status wins over the annotations.
3184        let mut existing = restored.clone();
3185        existing.status = Some(MaterializeStatus {
3186            resource_id: "zzzzz99999".to_owned(),
3187            active_generation: 7,
3188            ..Default::default()
3189        });
3190        let status = existing.status();
3191        assert_eq!(status.resource_id, "zzzzz99999");
3192        assert_eq!(status.active_generation, 7);
3193
3194        // Invalid values are reported, and never panic or reach the status.
3195        for (annotation, value) in [
3196            (LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION, "two"),
3197            (LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION, "-1"),
3198            (LAST_KNOWN_RESOURCE_ID_ANNOTATION, ""),
3199            (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "short"),
3200            (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "ABCDE01234"),
3201            (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "abcde-1234"),
3202            (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "abcde012345"),
3203        ] {
3204            let invalid = mz(&[(annotation, value)]);
3205            let err =
3206                InitialStatusAnnotations::parse(invalid.metadata.annotations.as_ref().unwrap())
3207                    .unwrap_err();
3208            assert!(err.to_string().contains(annotation), "{err}");
3209            let status = invalid.status();
3210            assert!(crate::crd::is_valid_resource_id(&status.resource_id));
3211            assert_ne!(status.resource_id, value);
3212            assert_eq!(status.active_generation, 0);
3213        }
3214    }
3215
3216    #[mz_ore::test]
3217    #[cfg_attr(miri, ignore)] // can't call foreign function `sha256_compress` on OS `linux`
3218    fn force_rollout_annotation_forces_new_generation() {
3219        // The force-rollout annotation must feed into both the v1 rollout
3220        // hash (so that a rollout is requested) and the v1alpha1 force
3221        // rollout value stamped onto the generated statefulset (so that the
3222        // requested rollout actually creates a new generation rather than
3223        // completing as a no-op).
3224        let mut mz = super::v1::Materialize {
3225            spec: super::v1::MaterializeSpec {
3226                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3227                ..Default::default()
3228            },
3229            metadata: ObjectMeta::default(),
3230            status: None,
3231        };
3232        let hash_without_annotation = mz.generate_rollout_hash();
3233        let force_without_annotation = Materialize::from(mz.clone()).force_rollout_value();
3234
3235        mz.metadata.annotations = Some(std::collections::BTreeMap::from_iter([(
3236            FORCE_ROLLOUT_ANNOTATION.to_owned(),
3237            "a4b56cbb-a13e-4f95-8a9d-425c9ba28576".to_owned(),
3238        )]));
3239        assert_ne!(mz.generate_rollout_hash(), hash_without_annotation);
3240        assert_ne!(
3241            Materialize::from(mz.clone()).force_rollout_value(),
3242            force_without_annotation
3243        );
3244
3245        // Changing the annotation's value changes both again.
3246        let hash = mz.generate_rollout_hash();
3247        let force = Materialize::from(mz.clone()).force_rollout_value();
3248        mz.metadata.annotations.as_mut().unwrap().insert(
3249            FORCE_ROLLOUT_ANNOTATION.to_owned(),
3250            "3f61bf8d-0714-462c-8b3b-3d9a68d0bcba".to_owned(),
3251        );
3252        assert_ne!(mz.generate_rollout_hash(), hash);
3253        assert_ne!(Materialize::from(mz.clone()).force_rollout_value(), force);
3254    }
3255
3256    #[mz_ore::test]
3257    #[cfg_attr(miri, ignore)]
3258    fn balancerd_configmap_reference_preserves_rollout_hash_and_conversion() {
3259        let mut mz = super::v1::Materialize {
3260            spec: super::v1::MaterializeSpec {
3261                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3262                ..Default::default()
3263            },
3264            metadata: ObjectMeta::default(),
3265            status: None,
3266        };
3267        let hash = mz.generate_rollout_hash();
3268        // Omitting the new field also preserves hashes calculated by older operators.
3269        assert!(
3270            serde_json::to_value(&mz.spec)
3271                .unwrap()
3272                .get("balancerdConfigmapName")
3273                .is_none()
3274        );
3275        mz.spec.balancerd_configmap_name = Some("balancerd-settings".to_owned());
3276        assert_eq!(mz.generate_rollout_hash(), hash);
3277        let alpha = Materialize::from(mz.clone());
3278        assert_eq!(
3279            alpha.spec.balancerd_configmap_name,
3280            mz.spec.balancerd_configmap_name
3281        );
3282        assert_eq!(
3283            super::v1::Materialize::from(alpha)
3284                .spec
3285                .balancerd_configmap_name,
3286            mz.spec.balancerd_configmap_name,
3287        );
3288        for value in [
3289            serde_json::json!("balancerd-settings"),
3290            serde_json::Value::Null,
3291        ] {
3292            let subset = serde_json::json!({
3293                "apiVersion": "materialize.cloud/v1alpha1",
3294                "kind": "Materialize",
3295                "metadata": {"name": "mz"},
3296                "spec": {"balancerdConfigmapName": value},
3297            });
3298            let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3299            assert_eq!(v1["spec"]["balancerdConfigmapName"], value);
3300            let roundtrip = super::convert_v1_to_v1alpha1(v1).unwrap();
3301            assert_eq!(roundtrip, subset);
3302        }
3303    }
3304
3305    #[mz_ore::test]
3306    #[cfg_attr(miri, ignore)]
3307    fn balancerd_externally_scaled_preserves_rollout_hash_and_conversion() {
3308        let mut mz = super::v1::Materialize {
3309            spec: super::v1::MaterializeSpec {
3310                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3311                ..Default::default()
3312            },
3313            metadata: ObjectMeta::default(),
3314            status: None,
3315        };
3316        let hash = mz.generate_rollout_hash();
3317        // Omitting the new field also preserves hashes calculated by older operators.
3318        assert!(
3319            serde_json::to_value(&mz.spec)
3320                .unwrap()
3321                .get("balancerdExternallyScaled")
3322                .is_none()
3323        );
3324        mz.spec.balancerd_externally_scaled = Some(true);
3325        assert_eq!(mz.generate_rollout_hash(), hash);
3326        let alpha = Materialize::from(mz.clone());
3327        assert_eq!(alpha.spec.balancerd_externally_scaled, Some(true));
3328        assert_eq!(
3329            super::v1::Materialize::from(alpha)
3330                .spec
3331                .balancerd_externally_scaled,
3332            Some(true),
3333        );
3334        for value in [serde_json::json!(true), serde_json::Value::Null] {
3335            let subset = serde_json::json!({
3336                "apiVersion": "materialize.cloud/v1alpha1",
3337                "kind": "Materialize",
3338                "metadata": {"name": "mz"},
3339                "spec": {"balancerdExternallyScaled": value},
3340            });
3341            let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3342            assert_eq!(v1["spec"]["balancerdExternallyScaled"], value);
3343            let roundtrip = super::convert_v1_to_v1alpha1(v1).unwrap();
3344            assert_eq!(roundtrip, subset);
3345        }
3346    }
3347
3348    #[mz_ore::test]
3349    #[cfg_attr(miri, ignore)]
3350    fn environmentd_probes_trigger_rollout_and_survive_conversion() {
3351        let mut mz = super::v1::Materialize {
3352            spec: super::v1::MaterializeSpec {
3353                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3354                ..Default::default()
3355            },
3356            metadata: ObjectMeta::default(),
3357            status: None,
3358        };
3359        let hash = mz.generate_rollout_hash();
3360        // Omitting unset probes preserves hashes calculated by older operators.
3361        let spec = serde_json::to_value(&mz.spec).unwrap();
3362        assert!(spec.get("environmentdReadinessProbe").is_none());
3363        assert!(spec.get("environmentdLivenessProbe").is_none());
3364        assert!(spec.get("environmentdStartupProbe").is_none());
3365
3366        let probe = k8s_openapi::api::core::v1::Probe {
3367            failure_threshold: Some(60),
3368            ..Default::default()
3369        };
3370        mz.spec.environmentd_readiness_probe = Some(probe.clone());
3371        let readiness_hash = mz.generate_rollout_hash();
3372        assert_ne!(readiness_hash, hash);
3373        mz.spec.environmentd_liveness_probe = Some(probe.clone());
3374        let liveness_hash = mz.generate_rollout_hash();
3375        assert_ne!(liveness_hash, readiness_hash);
3376        mz.spec.environmentd_startup_probe = Some(probe);
3377        assert_ne!(mz.generate_rollout_hash(), liveness_hash);
3378
3379        let alpha = Materialize::from(mz.clone());
3380        assert_eq!(
3381            alpha.spec.environmentd_readiness_probe,
3382            mz.spec.environmentd_readiness_probe
3383        );
3384        assert_eq!(
3385            alpha.spec.environmentd_liveness_probe,
3386            mz.spec.environmentd_liveness_probe
3387        );
3388        assert_eq!(
3389            alpha.spec.environmentd_startup_probe,
3390            mz.spec.environmentd_startup_probe
3391        );
3392        let v1 = super::v1::Materialize::from(alpha);
3393        assert_eq!(
3394            v1.spec.environmentd_readiness_probe,
3395            mz.spec.environmentd_readiness_probe
3396        );
3397        assert_eq!(
3398            v1.spec.environmentd_liveness_probe,
3399            mz.spec.environmentd_liveness_probe
3400        );
3401        assert_eq!(
3402            v1.spec.environmentd_startup_probe,
3403            mz.spec.environmentd_startup_probe
3404        );
3405
3406        let subset = serde_json::json!({
3407            "apiVersion": "materialize.cloud/v1alpha1",
3408            "kind": "Materialize",
3409            "metadata": {"name": "mz"},
3410            "spec": {
3411                "environmentdReadinessProbe": {"periodSeconds": 5},
3412                "environmentdLivenessProbe": null,
3413                "environmentdStartupProbe": {"failureThreshold": 360},
3414            },
3415        });
3416        let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3417        assert_eq!(v1["spec"], subset["spec"]);
3418        assert_eq!(super::convert_v1_to_v1alpha1(v1).unwrap(), subset);
3419    }
3420
3421    #[mz_ore::test]
3422    #[cfg_attr(miri, ignore)]
3423    fn additional_trust_bundle_triggers_rollout_and_survives_conversion() {
3424        let mut mz = super::v1::Materialize {
3425            spec: super::v1::MaterializeSpec {
3426                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3427                ..Default::default()
3428            },
3429            metadata: ObjectMeta::default(),
3430            status: None,
3431        };
3432        let hash = mz.generate_rollout_hash();
3433        // Omitting the unset field preserves hashes calculated by older operators.
3434        assert!(
3435            serde_json::to_value(&mz.spec)
3436                .unwrap()
3437                .get("additionalTrustBundle")
3438                .is_none()
3439        );
3440
3441        mz.spec.additional_trust_bundle = Some(AdditionalTrustBundle {
3442            config_map_key_ref: Some(TrustBundleKeyRef {
3443                name: "private-ca".to_owned(),
3444                key: "ca.crt".to_owned(),
3445            }),
3446            secret_key_ref: None,
3447        });
3448        assert_ne!(mz.generate_rollout_hash(), hash);
3449
3450        let alpha = Materialize::from(mz.clone());
3451        assert_eq!(
3452            alpha.spec.additional_trust_bundle,
3453            mz.spec.additional_trust_bundle
3454        );
3455        assert_eq!(
3456            super::v1::Materialize::from(alpha)
3457                .spec
3458                .additional_trust_bundle,
3459            mz.spec.additional_trust_bundle
3460        );
3461
3462        let key_ref = TrustBundleKeyRef {
3463            name: "private-ca".to_owned(),
3464            key: "ca.crt".to_owned(),
3465        };
3466        let both = AdditionalTrustBundle {
3467            config_map_key_ref: Some(key_ref.clone()),
3468            secret_key_ref: Some(key_ref.clone()),
3469        };
3470        assert!(both.source().is_err(), "both refs set must be rejected");
3471        let neither = AdditionalTrustBundle {
3472            config_map_key_ref: None,
3473            secret_key_ref: None,
3474        };
3475        assert!(neither.source().is_err(), "no ref set must be rejected");
3476        let secret = AdditionalTrustBundle {
3477            config_map_key_ref: None,
3478            secret_key_ref: Some(key_ref.clone()),
3479        };
3480        assert_eq!(
3481            secret.source().unwrap(),
3482            TrustBundleSource::Secret(&key_ref)
3483        );
3484
3485        for value in [
3486            serde_json::json!({"secretKeyRef": {"name": "private-ca", "key": "ca.crt"}}),
3487            serde_json::Value::Null,
3488        ] {
3489            let subset = serde_json::json!({
3490                "apiVersion": "materialize.cloud/v1alpha1",
3491                "kind": "Materialize",
3492                "metadata": {"name": "mz"},
3493                "spec": {"additionalTrustBundle": value},
3494            });
3495            let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3496            assert_eq!(v1["spec"]["additionalTrustBundle"], value);
3497            assert_eq!(super::convert_v1_to_v1alpha1(v1).unwrap(), subset);
3498        }
3499    }
3500
3501    #[mz_ore::test]
3502    fn meets_minimum_version() {
3503        let mut mz = Materialize {
3504            spec: MaterializeSpec {
3505                environmentd_image_ref:
3506                    "materialize/environmentd:devel-47116c24b8d0df33d3f60a9ee476aa8d7bce5953"
3507                        .to_owned(),
3508                ..Default::default()
3509            },
3510            metadata: ObjectMeta {
3511                ..Default::default()
3512            },
3513            status: None,
3514        };
3515
3516        // true cases
3517        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3518        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
3519        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3520        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.35.0".to_owned();
3521        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3522        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.3".to_owned();
3523        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3524        mz.spec.environmentd_image_ref = "materialize/environmentd@41af286dc0b172ed2f1ca934fd2278de4a1192302ffa07087cea2682e7d372e3".to_owned();
3525        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3526        mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.34.3".to_owned();
3527        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3528        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.asdf.0".to_owned();
3529        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3530        mz.spec.environmentd_image_ref =
3531            "materialize/environmentd:v0.146.0-dev.0--pr.g5a05a9e4ba873be8adaa528644aaae6e4c7cd29b"
3532                .to_owned();
3533        assert!(mz.meets_minimum_version(&Version::parse("0.146.0-dev.0").unwrap()));
3534
3535        // false cases
3536        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0-dev".to_owned();
3537        assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3538        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.33.0".to_owned();
3539        assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3540        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
3541        assert!(!mz.meets_minimum_version(&Version::parse("1.0.0").unwrap()));
3542        mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.33.3".to_owned();
3543        assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3544    }
3545
3546    #[mz_ore::test]
3547    fn within_upgrade_window() {
3548        let mut mz = Materialize {
3549            spec: MaterializeSpec {
3550                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3551                ..Default::default()
3552            },
3553            metadata: ObjectMeta {
3554                ..Default::default()
3555            },
3556            status: Some(MaterializeStatus {
3557                last_completed_rollout_environmentd_image_ref: Some(
3558                    "materialize/environmentd:v26.0.0".to_owned(),
3559                ),
3560                ..Default::default()
3561            }),
3562        };
3563
3564        // Pass: upgrading from 26.0.0 to 27.7.3 (within 1 major version)
3565        mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.3".to_owned();
3566        assert!(mz.within_upgrade_window());
3567
3568        // Pass: upgrading from 26.0.0 to 27.7.8-dev.0 (within 1 major version, pre-release)
3569        mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.8-dev.0".to_owned();
3570        assert!(mz.within_upgrade_window());
3571
3572        // Fail: upgrading from 26.0.0 to 28.0.1 (more than 1 major version)
3573        mz.spec.environmentd_image_ref = "materialize/environmentd:v28.0.1".to_owned();
3574        assert!(!mz.within_upgrade_window());
3575
3576        // Pass: upgrading from 26.0.0 to 28.0.1.not_a_valid_version (invalid version, defaults to true)
3577        mz.spec.environmentd_image_ref =
3578            "materialize/environmentd:v28.0.1.not_a_valid_version".to_owned();
3579        assert!(mz.within_upgrade_window());
3580
3581        // Pass: upgrading from 0.164.0 to 26.1.0 (self managed 25.2 to 26.0)
3582        mz.status
3583            .as_mut()
3584            .unwrap()
3585            .last_completed_rollout_environmentd_image_ref =
3586            Some("materialize/environmentd:v0.147.20".to_owned());
3587        mz.spec.environmentd_image_ref = "materialize/environmentd:v26.1.0".to_owned();
3588        assert!(mz.within_upgrade_window());
3589
3590        // Pass: upgrading from 26.11.0-dev.0+b to 26.11.0-dev.0+a (same major.minor.patch.prerelease, different build metadata)
3591        mz.status
3592            .as_mut()
3593            .unwrap()
3594            .last_completed_rollout_environmentd_image_ref =
3595            Some("materialize/environmentd:v26.11.0-dev.0+b".to_owned());
3596        mz.spec.environmentd_image_ref = "materialize/environmentd:v26.11.0-dev.0+a".to_owned();
3597        assert!(mz.within_upgrade_window());
3598    }
3599
3600    #[mz_ore::test]
3601    fn is_valid_upgrade_version() {
3602        let success_tests = [
3603            (Version::new(0, 83, 0), Version::new(0, 83, 0)),
3604            (Version::new(0, 83, 0), Version::new(0, 84, 0)),
3605            (Version::new(0, 9, 0), Version::new(0, 10, 0)),
3606            (Version::new(0, 99, 0), Version::new(0, 100, 0)),
3607            (Version::new(0, 83, 0), Version::new(0, 83, 1)),
3608            (Version::new(0, 83, 0), Version::new(0, 83, 2)),
3609            (Version::new(0, 83, 2), Version::new(0, 83, 10)),
3610            // 0.147.20 to 26.0.0 represents the Self Managed 25.2 to 26.0 upgrade
3611            (Version::new(0, 147, 20), Version::new(26, 0, 0)),
3612            (Version::new(0, 164, 0), Version::new(26, 0, 0)),
3613            (Version::new(26, 0, 0), Version::new(26, 1, 0)),
3614            (Version::new(26, 5, 3), Version::new(26, 10, 0)),
3615            (Version::new(0, 130, 0), Version::new(0, 147, 0)),
3616        ];
3617        for (active_version, next_version) in success_tests {
3618            assert!(
3619                Materialize::is_valid_upgrade_version(&active_version, &next_version),
3620                "v{active_version} can upgrade to v{next_version}"
3621            );
3622        }
3623
3624        let failure_tests = [
3625            (Version::new(0, 83, 0), Version::new(0, 82, 0)),
3626            (Version::new(0, 83, 3), Version::new(0, 83, 2)),
3627            (Version::new(0, 83, 3), Version::new(1, 83, 3)),
3628            (Version::new(0, 83, 0), Version::new(0, 85, 0)),
3629            (Version::new(26, 0, 0), Version::new(28, 0, 0)),
3630            (Version::new(0, 130, 0), Version::new(26, 1, 0)),
3631            // Disallow anything before 0.147.20 to upgrade
3632            (Version::new(0, 147, 1), Version::new(26, 0, 0)),
3633            // Disallow anything between 0.148.0 and 0.164.0 to upgrade
3634            (Version::new(0, 148, 0), Version::new(26, 0, 0)),
3635        ];
3636        for (active_version, next_version) in failure_tests {
3637            assert!(
3638                !Materialize::is_valid_upgrade_version(&active_version, &next_version),
3639                "v{active_version} can't upgrade to v{next_version}"
3640            );
3641        }
3642    }
3643
3644    #[mz_ore::test]
3645    fn rollout_request_timeout() {
3646        let mz_with = |timeout: &str| Materialize {
3647            spec: MaterializeSpec {
3648                rollout_request_timeout: RolloutRequestTimeout(timeout.to_owned()),
3649                ..Default::default()
3650            },
3651            metadata: ObjectMeta::default(),
3652            status: None,
3653        };
3654
3655        // The default const is a valid duration and resolves to 24h.
3656        let default = humantime::parse_duration(DEFAULT_ROLLOUT_REQUEST_TIMEOUT).unwrap();
3657        assert_eq!(default, Duration::from_secs(24 * 60 * 60));
3658
3659        // The field's Default (used by `MaterializeSpec::default()` and serde's
3660        // `#[serde(default)]`) is the 24h default, with no empty intermediate.
3661        assert_eq!(
3662            RolloutRequestTimeout::default().0,
3663            DEFAULT_ROLLOUT_REQUEST_TIMEOUT
3664        );
3665        assert_eq!(
3666            Materialize {
3667                spec: MaterializeSpec::default(),
3668                metadata: ObjectMeta::default(),
3669                status: None,
3670            }
3671            .rollout_request_timeout(),
3672            default
3673        );
3674
3675        // Parseable values are honored.
3676        assert_eq!(
3677            mz_with("1h").rollout_request_timeout(),
3678            Duration::from_secs(60 * 60)
3679        );
3680        assert_eq!(
3681            mz_with("90m").rollout_request_timeout(),
3682            Duration::from_secs(90 * 60)
3683        );
3684        assert_eq!(
3685            mz_with("1h 30m").rollout_request_timeout(),
3686            Duration::from_secs(90 * 60)
3687        );
3688        // Unparseable values fall back to the default.
3689        assert_eq!(mz_with("not a duration").rollout_request_timeout(), default);
3690    }
3691
3692    #[mz_ore::test]
3693    fn rollout_request_timeout_schema_default() {
3694        // The default must be surfaced in the generated CRD's OpenAPI schema
3695        // (not just in the Rust helper), so the Kubernetes API server defaults
3696        // omitted fields and `kubectl explain` shows it.
3697        let crd = serde_json::to_value(<Materialize as kube::CustomResourceExt>::crd())
3698            .expect("CRD serializes");
3699        let default = &crd["spec"]["versions"][0]["schema"]["openAPIV3Schema"]["properties"]["spec"]
3700            ["properties"]["rolloutRequestTimeout"]["default"];
3701        assert_eq!(
3702            default,
3703            &serde_json::json!(DEFAULT_ROLLOUT_REQUEST_TIMEOUT),
3704            "rolloutRequestTimeout schema default missing/wrong in generated CRD",
3705        );
3706    }
3707
3708    #[mz_ore::test]
3709    fn rollout_in_progress_since() {
3710        let now = Timestamp::now();
3711        let condition = |type_: &str, status: &str| Condition {
3712            type_: type_.to_owned(),
3713            status: status.to_owned(),
3714            last_transition_time: Time(now),
3715            message: String::new(),
3716            observed_generation: None,
3717            reason: "Test".to_owned(),
3718        };
3719        let mz_with = |conditions: Vec<Condition>| Materialize {
3720            spec: MaterializeSpec::default(),
3721            metadata: ObjectMeta::default(),
3722            status: Some(MaterializeStatus {
3723                conditions,
3724                ..Default::default()
3725            }),
3726        };
3727
3728        // No status at all.
3729        let mz = Materialize {
3730            spec: MaterializeSpec::default(),
3731            metadata: ObjectMeta::default(),
3732            status: None,
3733        };
3734        assert_eq!(mz.rollout_in_progress_since(), None);
3735
3736        // A timeout-eligible rollout in progress is signalled by an `Unknown`
3737        // `UpToDate` condition (the Applying and ReadyToPromote phases).
3738        assert_eq!(
3739            mz_with(vec![condition("UpToDate", "Unknown")]).rollout_in_progress_since(),
3740            Some(now)
3741        );
3742
3743        // The `Promoting` phase is also `Unknown`, but must NOT be reported:
3744        // once promoting, the rollout can no longer be cancelled by the
3745        // timeout.
3746        assert_eq!(
3747            mz_with(vec![Condition {
3748                reason: "Promoting".to_owned(),
3749                ..condition("UpToDate", "Unknown")
3750            }])
3751            .rollout_in_progress_since(),
3752            None
3753        );
3754
3755        // A settled rollout (True/False) is not in progress.
3756        assert_eq!(
3757            mz_with(vec![condition("UpToDate", "True")]).rollout_in_progress_since(),
3758            None
3759        );
3760        assert_eq!(
3761            mz_with(vec![condition("UpToDate", "False")]).rollout_in_progress_since(),
3762            None
3763        );
3764    }
3765
3766    #[mz_ore::test]
3767    fn up_to_date_transition_time() {
3768        // Two distinct, fixed instants so we can tell "carried the old
3769        // timestamp" apart from "reset to now".
3770        let stored = Timestamp::from_second(1_000).unwrap();
3771        let now = Timestamp::from_second(2_000).unwrap();
3772
3773        let condition = |status: &str| Condition {
3774            type_: "UpToDate".to_owned(),
3775            status: status.to_owned(),
3776            last_transition_time: Time(stored),
3777            message: String::new(),
3778            observed_generation: None,
3779            reason: "Test".to_owned(),
3780        };
3781        let mz_with = |conditions: Vec<Condition>| Materialize {
3782            spec: MaterializeSpec::default(),
3783            metadata: ObjectMeta::default(),
3784            status: Some(MaterializeStatus {
3785                conditions,
3786                ..Default::default()
3787            }),
3788        };
3789
3790        // No prior condition: use `now`.
3791        let mz = Materialize {
3792            spec: MaterializeSpec::default(),
3793            metadata: ObjectMeta::default(),
3794            status: None,
3795        };
3796        assert_eq!(mz.up_to_date_transition_time("Unknown", now), now);
3797
3798        // Same status as the prior condition: carry its timestamp forward, so
3799        // consecutive same-status phases (Applying -> ReadyToPromote) share one
3800        // timer.
3801        assert_eq!(
3802            mz_with(vec![condition("Unknown")]).up_to_date_transition_time("Unknown", now),
3803            stored
3804        );
3805
3806        // Status changed: reset to `now`.
3807        assert_eq!(
3808            mz_with(vec![condition("Unknown")]).up_to_date_transition_time("True", now),
3809            now
3810        );
3811    }
3812
3813    #[mz_ore::test]
3814    fn active_environmentd_image_ref() {
3815        const OLD: &str = "materialize/environmentd:v26.0.0";
3816        const NEW: &str = "materialize/environmentd:v27.0.0";
3817
3818        let mz_with = |spec_image: &str, status: Option<MaterializeStatus>| Materialize {
3819            spec: MaterializeSpec {
3820                environmentd_image_ref: spec_image.to_owned(),
3821                ..Default::default()
3822            },
3823            metadata: ObjectMeta::default(),
3824            status,
3825        };
3826
3827        // No status yet (pre-initial-reconcile): fall back to spec.
3828        let mz = mz_with(NEW, None);
3829        assert_eq!(mz.active_environmentd_image_ref(), NEW);
3830
3831        // Status present but last_completed_rollout_environmentd_image_ref
3832        // unset (e.g. resource upgraded from older orchestratord that didn't
3833        // populate the field): fall back to spec.
3834        let mz = mz_with(
3835            NEW,
3836            Some(MaterializeStatus {
3837                last_completed_rollout_environmentd_image_ref: None,
3838                ..Default::default()
3839            }),
3840        );
3841        assert_eq!(mz.active_environmentd_image_ref(), NEW);
3842
3843        // Steady state: spec image == last completed image. Either source is
3844        // fine; the method must return that image.
3845        let mz = mz_with(
3846            NEW,
3847            Some(MaterializeStatus {
3848                last_completed_rollout_environmentd_image_ref: Some(NEW.to_owned()),
3849                ..Default::default()
3850            }),
3851        );
3852        assert_eq!(mz.active_environmentd_image_ref(), NEW);
3853
3854        // DEP-42 / mid-rollout: spec image == NEW but last_completed_* still
3855        // holds OLD — either because the user canceled the rollout by
3856        // reverting only requestRollout, or because the new generation has
3857        // not yet been promoted. The active environmentd is still OLD, so
3858        // downstream resources must track OLD. Without this method,
3859        // balancerd would inherit the spec's NEW image while environmentd
3860        // still runs OLD, leaving balancerd pods skewed from the running
3861        // env.
3862        let mz = mz_with(
3863            NEW,
3864            Some(MaterializeStatus {
3865                last_completed_rollout_environmentd_image_ref: Some(OLD.to_owned()),
3866                ..Default::default()
3867            }),
3868        );
3869        assert_eq!(mz.active_environmentd_image_ref(), OLD);
3870    }
3871
3872    // Server-side apply round-trips each field manager's owned subset of an
3873    // object through the conversion webhook. Such subsets lack required
3874    // fields, so conversion must map them field-wise instead of erroring.
3875    #[mz_ore::test]
3876    fn convert_partial_v1alpha1_to_v1() {
3877        let subset = serde_json::json!({
3878            "apiVersion": "materialize.cloud/v1alpha1",
3879            "kind": "Materialize",
3880            "metadata": {"name": "mz", "namespace": "materialize"},
3881            "spec": {
3882                "environmentdIamRoleArn": "arn:aws:iam::123456789012:role/mz",
3883                "requestRollout": "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6",
3884                "inPlaceRollout": false,
3885                "forcePromote": "",
3886                "serviceAccountLabels": {"team": "data"},
3887            },
3888            "status": {
3889                "activeGeneration": 3,
3890                "lastCompletedRolloutRequest": "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6",
3891                "resourcesHash": "abc123",
3892            },
3893        });
3894        let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
3895        assert_eq!(converted["apiVersion"], "materialize.cloud/v1");
3896        assert_eq!(converted["kind"], "Materialize");
3897        assert_eq!(converted["metadata"]["name"], "mz");
3898        let spec = converted["spec"].as_object().unwrap();
3899        assert!(!spec.contains_key("requestRollout"));
3900        assert!(!spec.contains_key("inPlaceRollout"));
3901        assert!(!spec.contains_key("forcePromote"));
3902        assert!(!spec.contains_key("environmentdIamRoleArn"));
3903        assert_eq!(
3904            spec["serviceAccountAnnotations"]["eks.amazonaws.com/role-arn"],
3905            "arn:aws:iam::123456789012:role/mz"
3906        );
3907        assert_eq!(spec["serviceAccountLabels"]["team"], "data");
3908        let status = converted["status"].as_object().unwrap();
3909        assert_eq!(status["activeGeneration"], 3);
3910        assert!(!status.contains_key("lastCompletedRolloutRequest"));
3911        assert!(!status.contains_key("resourcesHash"));
3912        assert!(!status.contains_key("requestedRolloutHash"));
3913
3914        // A meaningful forcePromote value survives the conversion.
3915        let subset = serde_json::json!({
3916            "apiVersion": "materialize.cloud/v1alpha1",
3917            "kind": "Materialize",
3918            "metadata": {"name": "mz"},
3919            "spec": {"forcePromote": "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6"},
3920        });
3921        let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
3922        assert_eq!(
3923            converted["spec"]["forcePromote"],
3924            "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6"
3925        );
3926    }
3927
3928    #[mz_ore::test]
3929    fn convert_partial_v1_to_v1alpha1() {
3930        let subset = serde_json::json!({
3931            "apiVersion": "materialize.cloud/v1",
3932            "kind": "Materialize",
3933            "metadata": {"name": "mz"},
3934            "spec": {"environmentdImageRef": "materialize/environmentd:v26.0.0"},
3935            "status": {"requestedRolloutHash": "abc123", "activeGeneration": 1},
3936        });
3937        let converted = super::convert_v1_to_v1alpha1(subset).unwrap();
3938        assert_eq!(converted["apiVersion"], "materialize.cloud/v1alpha1");
3939        assert_eq!(
3940            converted["spec"]["environmentdImageRef"],
3941            "materialize/environmentd:v26.0.0"
3942        );
3943        let status = converted["status"].as_object().unwrap();
3944        assert_eq!(status["activeGeneration"], 1);
3945        assert!(!status.contains_key("requestedRolloutHash"));
3946        assert!(!status.contains_key("resourcesHash"));
3947        // Derived fields must not be invented for partial objects, a field
3948        // manager must not gain ownership of fields it never set.
3949        assert!(
3950            !converted["spec"]
3951                .as_object()
3952                .unwrap()
3953                .contains_key("requestRollout")
3954        );
3955    }
3956
3957    #[mz_ore::test]
3958    #[cfg_attr(miri, ignore)] // can't call foreign function `sha256_compress` on OS `linux`
3959    fn convert_full_v1alpha1_to_v1_derives_fields() {
3960        let mz = Materialize {
3961            metadata: ObjectMeta {
3962                name: Some("mz".to_owned()),
3963                namespace: Some("materialize".to_owned()),
3964                ..Default::default()
3965            },
3966            spec: MaterializeSpec {
3967                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3968                backend_secret_name: "mz-backend".to_owned(),
3969                ..Default::default()
3970            },
3971            status: Some(MaterializeStatus::default()),
3972        };
3973        let value = serde_json::to_value(&mz).unwrap();
3974        let converted = super::convert_v1alpha1_to_v1(value).unwrap();
3975        assert_eq!(converted["apiVersion"], "materialize.cloud/v1");
3976        // Complete objects take the typed conversion, which computes fields
3977        // derived from the whole spec.
3978        assert!(converted["status"]["requestedRolloutHash"].is_string());
3979    }
3980
3981    #[mz_ore::test]
3982    fn convert_rejects_non_objects() {
3983        assert!(super::convert_v1alpha1_to_v1(serde_json::json!("not an object")).is_err());
3984        assert!(super::convert_v1_to_v1alpha1(serde_json::json!(42)).is_err());
3985        assert!(
3986            super::convert_v1alpha1_to_v1(serde_json::json!({"spec": "not an object"})).is_err()
3987        );
3988    }
3989
3990    #[mz_ore::test]
3991    fn convert_preserves_null_vs_absent() {
3992        let subset = serde_json::json!({
3993            "apiVersion": "materialize.cloud/v1alpha1",
3994            "kind": "Materialize",
3995            "metadata": {"name": "mz"},
3996            "spec": {
3997                "environmentdExtraArgs": null,
3998                "backendSecretName": "mz-backend",
3999            },
4000        });
4001        let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
4002        let spec = converted["spec"].as_object().unwrap();
4003        assert!(spec.contains_key("environmentdExtraArgs"));
4004        assert!(spec["environmentdExtraArgs"].is_null());
4005        assert!(!spec.contains_key("consoleReplicas"));
4006    }
4007
4008    // A subset containing every required field deserializes as a complete
4009    // object and takes the derived-field splice, but the conversion must
4010    // still not add defaults or nulls for fields the subset did not carry.
4011    // Field managers must not gain ownership of fields they never set.
4012    #[mz_ore::test]
4013    #[cfg_attr(miri, ignore)] // can't call foreign function `sha256_compress` on OS `linux`
4014    fn convert_faithful_output_for_required_field_subsets() {
4015        let subset = serde_json::json!({
4016            "apiVersion": "materialize.cloud/v1alpha1",
4017            "kind": "Materialize",
4018            "metadata": {"name": "mz"},
4019            "spec": {
4020                "environmentdImageRef": "materialize/environmentd:v26.0.0",
4021                "backendSecretName": "mz-backend",
4022            },
4023        });
4024        let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
4025        let spec = converted["spec"].as_object().unwrap();
4026        let mut keys: Vec<_> = spec.keys().cloned().collect();
4027        keys.sort();
4028        assert_eq!(keys, ["backendSecretName", "environmentdImageRef"]);
4029    }
4030
4031    #[mz_ore::test]
4032    fn convert_passes_unknown_fields_through() {
4033        let subset = serde_json::json!({
4034            "apiVersion": "materialize.cloud/v1alpha1",
4035            "kind": "Materialize",
4036            "metadata": {"name": "mz"},
4037            "spec": {"someFutureField": {"a": 1}},
4038            "someTopLevelField": true,
4039        });
4040        let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
4041        assert_eq!(converted["spec"]["someFutureField"]["a"], 1);
4042        assert_eq!(converted["someTopLevelField"], true);
4043    }
4044
4045    #[mz_ore::test]
4046    #[cfg_attr(miri, ignore)] // can't call foreign function `sha256_compress` on OS `linux`
4047    fn convert_full_v1_to_v1alpha1_derives_request_rollout() {
4048        let mz = super::v1::Materialize {
4049            metadata: ObjectMeta {
4050                name: Some("mz".to_owned()),
4051                namespace: Some("materialize".to_owned()),
4052                ..Default::default()
4053            },
4054            spec: super::v1::MaterializeSpec {
4055                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
4056                backend_secret_name: "mz-backend".to_owned(),
4057                ..Default::default()
4058            },
4059            status: Some(super::v1::MaterializeStatus::default()),
4060        };
4061        let expected = Materialize::from(mz.clone()).spec.request_rollout;
4062        let converted = super::convert_v1_to_v1alpha1(serde_json::to_value(&mz).unwrap()).unwrap();
4063        assert_eq!(converted["apiVersion"], "materialize.cloud/v1alpha1");
4064        assert_eq!(
4065            converted["spec"]["requestRollout"],
4066            expected.hyphenated().to_string()
4067        );
4068        // The status fields required by the v1alpha1 schema but absent from
4069        // v1 must be spliced in, else the converted object fails validation
4070        // at the storage version.
4071        let status = converted["status"].as_object().unwrap();
4072        assert!(status["resourcesHash"].is_string());
4073        assert!(status["lastCompletedRolloutRequest"].is_string());
4074    }
4075
4076    // The `From<Materialize> for PartialMaterialize` impls are the
4077    // compile-time guard tying the partial mirrors to the typed structs.
4078    // Their output must be faithful: unset optional fields stay absent
4079    // rather than becoming nulls.
4080    #[mz_ore::test]
4081    fn partial_mirror_from_typed_omits_unset_fields() {
4082        let mz = Materialize {
4083            metadata: ObjectMeta::default(),
4084            spec: MaterializeSpec {
4085                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
4086                backend_secret_name: "mz-backend".to_owned(),
4087                ..Default::default()
4088            },
4089            status: None,
4090        };
4091        let value = serde_json::to_value(super::v1alpha1::PartialMaterialize::from(mz)).unwrap();
4092        let spec = value["spec"].as_object().unwrap();
4093        assert!(!spec.contains_key("balancerdReplicas"));
4094        for (key, field_value) in spec {
4095            assert!(!field_value.is_null(), "unexpected null for {key}");
4096        }
4097        assert!(!value.as_object().unwrap().contains_key("status"));
4098    }
4099}