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