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
10use std::collections::BTreeMap;
11
12use k8s_openapi::{
13    api::core::v1::{EnvVar, ResourceRequirements},
14    apimachinery::pkg::{
15        api::resource::Quantity,
16        apis::meta::v1::{Condition, Time},
17    },
18    jiff::Timestamp,
19};
20use kube::{CustomResource, Resource, ResourceExt};
21use schemars::JsonSchema;
22use semver::Version;
23use serde::{Deserialize, Serialize};
24use uuid::Uuid;
25
26use crate::crd::{ManagedResource, MaterializeCertSpec, new_resource_id};
27use mz_server_core::listeners::AuthenticatorKind;
28
29pub const LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION: &str =
30    "materialize.cloud/last-known-active-generation";
31
32pub mod v1alpha1 {
33    use super::*;
34
35    #[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema)]
36    pub enum MaterializeRolloutStrategy {
37        /// Create a new generation of pods, leaving the old generation around until the
38        /// new ones are ready to take over.
39        /// This minimizes downtime, and is what almost everyone should use.
40        #[default]
41        WaitUntilReady,
42
43        /// Create a new generation of pods, leaving the old generation as the serving generation
44        /// until the user manually promotes the new generation.
45        ///
46        /// When using `ManuallyPromote`, the new generation can be promoted at any
47        /// time, even if it has dataflows that are not fully caught up, by setting
48        /// `forcePromote` to the same value as `requestRollout` in the Materialize spec.
49        ///
50        /// To minimize downtime, promotion should occur when the new generation
51        /// has caught up to the prior generation. To determine if the new
52        /// generation has caught up, consult the `UpToDate` condition in the
53        /// status of the Materialize Resource. If the condition's reason is
54        /// `ReadyToPromote` the new generation is ready to promote.
55        ///
56        /// {{<warning>}}
57        /// Do not leave new generations unpromoted indefinitely.
58        ///
59        /// The new generation keeps open read holds which prevent compaction. Once promoted or
60        /// cancelled, those read holds are released. If left unpromoted for an extended time, this
61        /// data can build up, and can cause extreme deletion load on the metadata backend database
62        /// when finally promoted or cancelled.
63        /// {{</warning>}}
64        ManuallyPromote,
65
66        /// {{<warning>}}
67        /// THIS WILL CAUSE YOUR MATERIALIZE INSTANCE TO BE UNAVAILABLE FOR SOME TIME!!!
68        ///
69        /// This strategy should ONLY be used by customers with physical hardware who do not have
70        /// enough hardware for the `WaitUntilReady` strategy. If you think you want this, please
71        /// consult with Materialize engineering to discuss your situation.
72        /// {{</warning>}}
73        ///
74        /// Tear down the old generation of pods and promote the new generation of pods immediately,
75        /// without waiting for the new generation of pods to be ready.
76        ImmediatelyPromoteCausingDowntime,
77    }
78
79    #[derive(
80        CustomResource,
81        Clone,
82        Debug,
83        Default,
84        PartialEq,
85        Deserialize,
86        Serialize,
87        JsonSchema
88    )]
89    #[serde(rename_all = "camelCase")]
90    #[kube(
91        namespaced,
92        group = "materialize.cloud",
93        version = "v1alpha1",
94        kind = "Materialize",
95        singular = "materialize",
96        plural = "materializes",
97        shortname = "mzs",
98        status = "MaterializeStatus",
99        printcolumn = r#"{"name": "ImageRefRunning", "type": "string", "description": "Reference to the Docker image that is currently in use.", "jsonPath": ".status.lastCompletedRolloutEnvironmentdImageRef", "priority": 1}"#,
100        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}"#,
101        printcolumn = r#"{"name": "UpToDate", "type": "string", "description": "Whether the spec has been applied", "jsonPath": ".status.conditions[?(@.type==\"UpToDate\")].status", "priority": 1}"#
102    )]
103    pub struct MaterializeSpec {
104        /// The environmentd image to run.
105        pub environmentd_image_ref: String,
106        /// Extra args to pass to the environmentd binary.
107        pub environmentd_extra_args: Option<Vec<String>>,
108        /// Extra environment variables to pass to the environmentd binary.
109        pub environmentd_extra_env: Option<Vec<EnvVar>>,
110        /// {{<warning>}}
111        /// Deprecated.
112        ///
113        /// Use `service_account_annotations` to set "eks.amazonaws.com/role-arn" instead.
114        /// {{</warning>}}
115        ///
116        /// If running in AWS, override the IAM role to use to give
117        /// environmentd access to the persist S3 bucket.
118        #[kube(deprecated)]
119        pub environmentd_iam_role_arn: Option<String>,
120        /// If running in AWS, override the IAM role to use to support
121        /// the CREATE CONNECTION feature.
122        pub environmentd_connection_role_arn: Option<String>,
123        /// Resource requirements for the environmentd pod.
124        pub environmentd_resource_requirements: Option<ResourceRequirements>,
125        /// Amount of disk to allocate, if a storage class is provided.
126        pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
127        /// Resource requirements for the balancerd pod.
128        pub balancerd_resource_requirements: Option<ResourceRequirements>,
129        /// Resource requirements for the console pod.
130        pub console_resource_requirements: Option<ResourceRequirements>,
131        /// Number of balancerd pods to create.
132        pub balancerd_replicas: Option<i32>,
133        /// Number of console pods to create.
134        pub console_replicas: Option<i32>,
135
136        /// Name of the kubernetes service account to use.
137        /// If not set, we will create one with the same name as this Materialize object.
138        pub service_account_name: Option<String>,
139        /// Annotations to apply to the service account.
140        ///
141        /// Annotations on service accounts are commonly used by cloud providers for IAM.
142        /// AWS uses "eks.amazonaws.com/role-arn".
143        /// Azure uses "azure.workload.identity/client-id", but
144        /// additionally requires "azure.workload.identity/use": "true" on the pods.
145        pub service_account_annotations: Option<BTreeMap<String, String>>,
146        /// Labels to apply to the service account.
147        pub service_account_labels: Option<BTreeMap<String, String>>,
148        /// Annotations to apply to the pods.
149        pub pod_annotations: Option<BTreeMap<String, String>>,
150        /// Labels to apply to the pods.
151        pub pod_labels: Option<BTreeMap<String, String>>,
152
153        /// When changes are made to the environmentd resources (either via
154        /// modifying fields in the spec here or by deploying a new
155        /// orchestratord version which changes how resources are generated),
156        /// existing environmentd processes won't be automatically restarted.
157        /// In order to trigger a restart, the request_rollout field should be
158        /// set to a new (random) value. Once the rollout completes, the value
159        /// of `status.lastCompletedRolloutRequest` will be set to this value
160        /// to indicate completion.
161        ///
162        /// Defaults to a random value in order to ensure that the first
163        /// generation rollout is automatically triggered.
164        #[serde(default)]
165        pub request_rollout: Uuid,
166        /// If `forcePromote` is set to the same value as `requestRollout`, the
167        /// current rollout will skip waiting for clusters in the new
168        /// generation to rehydrate before promoting the new environmentd to
169        /// leader.
170        #[serde(default)]
171        pub force_promote: Uuid,
172        /// This value will be written to an annotation in the generated
173        /// environmentd statefulset, in order to force the controller to
174        /// detect the generated resources as changed even if no other changes
175        /// happened. This can be used to force a rollout to a new generation
176        /// even without making any meaningful changes, by setting it to the
177        /// same value as `requestRollout`.
178        #[serde(default)]
179        pub force_rollout: Uuid,
180        /// {{<warning>}}
181        /// Deprecated and ignored. Use `rolloutStrategy` instead.
182        /// {{</warning>}}
183        #[kube(deprecated)]
184        #[serde(default)]
185        pub in_place_rollout: bool,
186        /// Rollout strategy to use when upgrading this Materialize instance.
187        #[serde(default)]
188        pub rollout_strategy: MaterializeRolloutStrategy,
189        /// The name of a secret containing `metadata_backend_url` and `persist_backend_url`.
190        /// It may also contain `external_login_password_mz_system`, which will be used as
191        /// the password for the `mz_system` user if `authenticatorKind` is `Password`,
192        /// `Sasl`, or `Oidc`.
193        pub backend_secret_name: String,
194        /// How to authenticate with Materialize.
195        #[serde(default)]
196        pub authenticator_kind: AuthenticatorKind,
197        /// Whether to enable role based access control. Defaults to false.
198        #[serde(default)]
199        pub enable_rbac: bool,
200
201        /// The value used by environmentd (via the --environment-id flag) to
202        /// uniquely identify this instance. Must be globally unique, and
203        /// is required if a license key is not provided.
204        /// NOTE: This value MUST NOT be changed in an existing instance,
205        /// since it affects things like the way data is stored in the persist
206        /// backend.
207        #[serde(default)]
208        pub environment_id: Uuid,
209
210        /// The name of a ConfigMap containing system parameters in JSON format.
211        /// The ConfigMap must contain a `system-params.json` key whose value
212        /// is a valid JSON object containing valid system parameters.
213        ///
214        /// Run `SHOW ALL` in SQL to see a subset of configurable system parameters.
215        ///
216        /// Example ConfigMap:
217        /// ```yaml
218        /// data:
219        ///   system-params.json: |
220        ///     {
221        ///       "max_connections": 1000
222        ///     }
223        /// ```
224        pub system_parameter_configmap_name: Option<String>,
225
226        /// The configuration for generating an x509 certificate using cert-manager for balancerd
227        /// to present to incoming connections.
228        /// The `dnsNames` and `issuerRef` fields are required.
229        pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
230        /// The configuration for generating an x509 certificate using cert-manager for the console
231        /// to present to incoming connections.
232        /// The `dnsNames` and `issuerRef` fields are required.
233        /// Not yet implemented.
234        pub console_external_certificate_spec: Option<MaterializeCertSpec>,
235        /// The cert-manager Issuer or ClusterIssuer to use for database internal communication.
236        /// The `issuerRef` field is required.
237        /// This currently is only used for environmentd, but will eventually support clusterd.
238        /// Not yet implemented.
239        pub internal_certificate_spec: Option<MaterializeCertSpec>,
240    }
241
242    impl Materialize {
243        pub fn backend_secret_name(&self) -> String {
244            self.spec.backend_secret_name.clone()
245        }
246
247        pub fn namespace(&self) -> String {
248            self.meta().namespace.clone().unwrap()
249        }
250
251        pub fn create_service_account(&self) -> bool {
252            self.spec.service_account_name.is_none()
253        }
254
255        pub fn service_account_name(&self) -> String {
256            self.spec
257                .service_account_name
258                .clone()
259                .unwrap_or_else(|| self.name_unchecked())
260        }
261
262        pub fn role_name(&self) -> String {
263            self.name_unchecked()
264        }
265
266        pub fn role_binding_name(&self) -> String {
267            self.name_unchecked()
268        }
269
270        pub fn environmentd_statefulset_name(&self, generation: u64) -> String {
271            self.name_prefixed(&format!("environmentd-{generation}"))
272        }
273
274        pub fn environmentd_app_name(&self) -> String {
275            "environmentd".to_owned()
276        }
277
278        pub fn environmentd_service_name(&self) -> String {
279            self.name_prefixed("environmentd")
280        }
281
282        pub fn environmentd_service_internal_fqdn(&self) -> String {
283            format!(
284                "{}.{}.svc.cluster.local",
285                self.environmentd_service_name(),
286                self.meta().namespace.as_ref().unwrap()
287            )
288        }
289
290        pub fn environmentd_generation_service_name(&self, generation: u64) -> String {
291            self.name_prefixed(&format!("environmentd-{generation}"))
292        }
293
294        pub fn balancerd_app_name(&self) -> String {
295            "balancerd".to_owned()
296        }
297
298        pub fn environmentd_certificate_name(&self) -> String {
299            self.name_prefixed("environmentd-external")
300        }
301
302        pub fn environmentd_certificate_secret_name(&self) -> String {
303            self.name_prefixed("environmentd-tls")
304        }
305
306        pub fn balancerd_deployment_name(&self) -> String {
307            self.name_prefixed("balancerd")
308        }
309
310        pub fn balancerd_service_name(&self) -> String {
311            self.name_prefixed("balancerd")
312        }
313
314        pub fn console_app_name(&self) -> String {
315            "console".to_owned()
316        }
317
318        pub fn balancerd_external_certificate_name(&self) -> String {
319            self.name_prefixed("balancerd-external")
320        }
321
322        pub fn balancerd_external_certificate_secret_name(&self) -> String {
323            self.name_prefixed("balancerd-external-tls")
324        }
325
326        pub fn balancerd_replicas(&self) -> i32 {
327            self.spec.balancerd_replicas.unwrap_or(2)
328        }
329
330        pub fn console_replicas(&self) -> i32 {
331            self.spec.console_replicas.unwrap_or(2)
332        }
333
334        pub fn console_configmap_name(&self) -> String {
335            self.name_prefixed("console")
336        }
337
338        pub fn console_deployment_name(&self) -> String {
339            self.name_prefixed("console")
340        }
341
342        pub fn console_service_name(&self) -> String {
343            self.name_prefixed("console")
344        }
345
346        pub fn console_external_certificate_name(&self) -> String {
347            self.name_prefixed("console-external")
348        }
349
350        pub fn console_external_certificate_secret_name(&self) -> String {
351            self.name_prefixed("console-external-tls")
352        }
353
354        pub fn persist_pubsub_service_name(&self, generation: u64) -> String {
355            self.name_prefixed(&format!("persist-pubsub-{generation}"))
356        }
357
358        pub fn listeners_configmap_name(&self, generation: u64) -> String {
359            self.name_prefixed(&format!("listeners-{generation}"))
360        }
361
362        pub fn name_prefixed(&self, suffix: &str) -> String {
363            format!("mz{}-{}", self.resource_id(), suffix)
364        }
365
366        pub fn resource_id(&self) -> &str {
367            &self.status.as_ref().unwrap().resource_id
368        }
369
370        pub fn system_parameter_configmap_name(&self) -> Option<String> {
371            self.spec.system_parameter_configmap_name.clone()
372        }
373
374        pub fn environmentd_scratch_volume_storage_requirement(&self) -> Quantity {
375            self.spec
376                .environmentd_scratch_volume_storage_requirement
377                .clone()
378                .unwrap_or_else(|| {
379                    self.spec
380                        .environmentd_resource_requirements
381                        .as_ref()
382                        .and_then(|requirements| {
383                            requirements
384                                .requests
385                                .as_ref()
386                                .or(requirements.limits.as_ref())
387                        })
388                        // TODO: in cloud, we've been defaulting to twice the
389                        // memory limit, but k8s-openapi doesn't seem to
390                        // provide any way to parse Quantity values, so there
391                        // isn't an easy way to do arithmetic on it
392                        .and_then(|requirements| requirements.get("memory").cloned())
393                        // TODO: is there a better default to use here?
394                        .unwrap_or_else(|| Quantity("4096Mi".to_string()))
395                })
396        }
397
398        pub fn environment_id(&self, cloud_provider: &str, region: &str) -> String {
399            format!(
400                "{}-{}-{}-0",
401                cloud_provider, region, self.spec.environment_id,
402            )
403        }
404
405        pub fn requested_reconciliation_id(&self) -> Uuid {
406            self.spec.request_rollout
407        }
408
409        pub fn rollout_requested(&self) -> bool {
410            self.requested_reconciliation_id()
411                != self
412                    .status
413                    .as_ref()
414                    .map_or_else(Uuid::nil, |status| status.last_completed_rollout_request)
415        }
416
417        pub fn set_force_promote(&mut self) {
418            self.spec.force_promote = self.spec.request_rollout;
419        }
420
421        pub fn should_force_promote(&self) -> bool {
422            self.spec.force_promote == self.spec.request_rollout
423                || self.spec.rollout_strategy
424                    == MaterializeRolloutStrategy::ImmediatelyPromoteCausingDowntime
425        }
426
427        pub fn conditions_need_update(&self) -> bool {
428            let Some(status) = self.status.as_ref() else {
429                return true;
430            };
431            if status.conditions.is_empty() {
432                return true;
433            }
434            for condition in &status.conditions {
435                if condition.observed_generation != self.meta().generation {
436                    return true;
437                }
438            }
439            false
440        }
441
442        pub fn is_ready_to_promote(&self, resources_hash: &str) -> bool {
443            let Some(status) = self.status.as_ref() else {
444                return false;
445            };
446            if status.conditions.is_empty() {
447                return false;
448            }
449            status
450                .conditions
451                .iter()
452                .any(|condition| condition.reason == "ReadyToPromote")
453                && &status.resources_hash == resources_hash
454        }
455
456        pub fn is_promoting(&self) -> bool {
457            let Some(status) = self.status.as_ref() else {
458                return false;
459            };
460            if status.conditions.is_empty() {
461                return false;
462            }
463            status
464                .conditions
465                .iter()
466                .any(|condition| condition.reason == "Promoting")
467        }
468
469        pub fn update_in_progress(&self) -> bool {
470            let Some(status) = self.status.as_ref() else {
471                return false;
472            };
473            if status.conditions.is_empty() {
474                return false;
475            }
476            for condition in &status.conditions {
477                if condition.type_ == "UpToDate" && condition.status == "Unknown" {
478                    return true;
479                }
480            }
481            false
482        }
483
484        /// Checks that the given version is greater than or equal
485        /// to the existing version, if the existing version
486        /// can be parsed.
487        pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
488            let version = parse_image_ref(&self.spec.environmentd_image_ref);
489            match version {
490                // Use cmp_precedence() to ignore build metadata per SemVer 2.0.0 spec
491                Some(version) => version.cmp_precedence(minimum).is_ge(),
492                // In the rare case that we see an image reference
493                // that we can't parse, we assume that it satisfies all
494                // version checks. Usually these are custom images that have
495                // been by a developer on a branch forked from a recent copy
496                // of main, and so this works out reasonably well in practice.
497                None => {
498                    tracing::warn!(
499                        image_ref = %self.spec.environmentd_image_ref,
500                        "failed to parse image ref",
501                    );
502                    true
503                }
504            }
505        }
506
507        /// This check isn't strictly required since environmentd will still be able to determine
508        /// if the upgrade is allowed or not. However, doing this check allows us to provide
509        /// the error as soon as possible and in a more user friendly way.
510        pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
511            // Don't allow rolling back
512            // Note: semver comparison handles RC versions correctly:
513            // v26.0.0-rc.1 < v26.0.0-rc.2 < v26.0.0
514            // Use cmp_precedence() to ignore build metadata
515            if next_version.cmp_precedence(active_version) == std::cmp::Ordering::Less {
516                return false;
517            }
518
519            if active_version.major == 0 {
520                if next_version.major != active_version.major {
521                    if next_version.major == 26 {
522                        // We require customers to upgrade from 0.147.20 (Self Managed 25.2) or v0.164.X (Cloud)
523                        // before upgrading to 26.0.0
524
525                        return (active_version.minor == 147 && active_version.patch >= 20)
526                            || active_version.minor >= 164;
527                    } else {
528                        return false;
529                    }
530                }
531                // Self managed 25.1 to 25.2
532                if next_version.minor == 147 && active_version.minor == 130 {
533                    return true;
534                }
535                // only allow upgrading a single minor version at a time
536                return next_version.minor <= active_version.minor + 1;
537            } else if active_version.major >= 26 {
538                // For versions 26.X.X and onwards, we deny upgrades past 1 major version of the active version
539                return next_version.major <= active_version.major + 1;
540            }
541
542            true
543        }
544
545        /// Checks if the current environmentd image ref is within the upgrade window of the last
546        /// successful rollout.
547        pub fn within_upgrade_window(&self) -> bool {
548            let active_environmentd_version = self
549                .status
550                .as_ref()
551                .and_then(|status| {
552                    status
553                        .last_completed_rollout_environmentd_image_ref
554                        .as_ref()
555                })
556                .and_then(|image_ref| parse_image_ref(image_ref));
557
558            if let (Some(next_environmentd_version), Some(active_environmentd_version)) = (
559                parse_image_ref(&self.spec.environmentd_image_ref),
560                active_environmentd_version,
561            ) {
562                Self::is_valid_upgrade_version(
563                    &active_environmentd_version,
564                    &next_environmentd_version,
565                )
566            } else {
567                // If we fail to parse either version,
568                // we still allow the upgrade since environmentd will still error if the upgrade is not allowed.
569                true
570            }
571        }
572
573        pub fn status(&self) -> MaterializeStatus {
574            self.status.clone().unwrap_or_else(|| {
575                let mut status = MaterializeStatus::default();
576
577                status.resource_id = new_resource_id();
578
579                // If we're creating the initial status on an un-soft-deleted
580                // Environment we need to ensure that the last active generation
581                // is restored, otherwise the env will crash loop indefinitely
582                // as its catalog would have durably recorded a greater generation
583                if let Some(last_active_generation) = self
584                    .annotations()
585                    .get(LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION)
586                {
587                    status.active_generation = last_active_generation
588                        .parse()
589                        .expect("valid int generation");
590                }
591
592                // Initialize the last completed rollout environmentd image ref to
593                // the current image ref if not already set.
594                status.last_completed_rollout_environmentd_image_ref =
595                    Some(self.spec.environmentd_image_ref.clone());
596
597                status
598            })
599        }
600    }
601
602    #[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema, PartialEq)]
603    #[serde(rename_all = "camelCase")]
604    pub struct MaterializeStatus {
605        /// Resource identifier used as a name prefix to avoid pod name collisions.
606        pub resource_id: String,
607        /// The generation of Materialize pods actively capable of servicing requests.
608        pub active_generation: u64,
609        /// The UUID of the last successfully completed rollout.
610        pub last_completed_rollout_request: Uuid,
611        /// The image ref of the environmentd image that was last successfully rolled out.
612        /// Used to deny upgrades past 1 major version from the last successful rollout.
613        /// When None, we upgrade anyways.
614        pub last_completed_rollout_environmentd_image_ref: Option<String>,
615        /// A hash calculated from the spec of resources to be created based on this Materialize
616        /// spec. This is used for detecting when the existing resources are up to date.
617        /// If you want to trigger a rollout without making other changes that would cause this
618        /// hash to change, you must set forceRollout to the same UUID as requestRollout.
619        pub resources_hash: String,
620        pub conditions: Vec<Condition>,
621    }
622
623    impl MaterializeStatus {
624        pub fn needs_update(&self, other: &Self) -> bool {
625            let now = Timestamp::now();
626            let mut a = self.clone();
627            for condition in &mut a.conditions {
628                condition.last_transition_time = Time(now);
629            }
630            let mut b = other.clone();
631            for condition in &mut b.conditions {
632                condition.last_transition_time = Time(now);
633            }
634            a != b
635        }
636    }
637
638    impl ManagedResource for Materialize {
639        fn default_labels(&self) -> BTreeMap<String, String> {
640            BTreeMap::from_iter([
641                (
642                    "materialize.cloud/organization-name".to_owned(),
643                    self.name_unchecked(),
644                ),
645                (
646                    "materialize.cloud/organization-namespace".to_owned(),
647                    self.namespace(),
648                ),
649                (
650                    "materialize.cloud/mz-resource-id".to_owned(),
651                    self.resource_id().to_owned(),
652                ),
653            ])
654        }
655    }
656}
657
658fn parse_image_ref(image_ref: &str) -> Option<Version> {
659    image_ref
660        .rsplit_once(':')
661        .and_then(|(_repo, tag)| tag.strip_prefix('v'))
662        .and_then(|tag| {
663            // To work around Docker tag restrictions, build metadata in
664            // a Docker tag is delimited by `--` rather than the SemVer
665            // `+` delimiter. So we need to swap the delimiter back to
666            // `+` before parsing it as SemVer.
667            let tag = tag.replace("--", "+");
668            Version::parse(&tag).ok()
669        })
670}
671
672#[cfg(test)]
673mod tests {
674    use kube::core::ObjectMeta;
675    use semver::Version;
676
677    use super::v1alpha1::{Materialize, MaterializeSpec};
678
679    #[mz_ore::test]
680    fn meets_minimum_version() {
681        let mut mz = Materialize {
682            spec: MaterializeSpec {
683                environmentd_image_ref:
684                    "materialize/environmentd:devel-47116c24b8d0df33d3f60a9ee476aa8d7bce5953"
685                        .to_owned(),
686                ..Default::default()
687            },
688            metadata: ObjectMeta {
689                ..Default::default()
690            },
691            status: None,
692        };
693
694        // true cases
695        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
696        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
697        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
698        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.35.0".to_owned();
699        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
700        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.3".to_owned();
701        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
702        mz.spec.environmentd_image_ref = "materialize/environmentd@41af286dc0b172ed2f1ca934fd2278de4a1192302ffa07087cea2682e7d372e3".to_owned();
703        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
704        mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.34.3".to_owned();
705        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
706        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.asdf.0".to_owned();
707        assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
708        mz.spec.environmentd_image_ref =
709            "materialize/environmentd:v0.146.0-dev.0--pr.g5a05a9e4ba873be8adaa528644aaae6e4c7cd29b"
710                .to_owned();
711        assert!(mz.meets_minimum_version(&Version::parse("0.146.0-dev.0").unwrap()));
712
713        // false cases
714        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0-dev".to_owned();
715        assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
716        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.33.0".to_owned();
717        assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
718        mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
719        assert!(!mz.meets_minimum_version(&Version::parse("1.0.0").unwrap()));
720        mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.33.3".to_owned();
721        assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
722    }
723
724    #[mz_ore::test]
725    fn within_upgrade_window() {
726        use super::v1alpha1::MaterializeStatus;
727
728        let mut mz = Materialize {
729            spec: MaterializeSpec {
730                environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
731                ..Default::default()
732            },
733            metadata: ObjectMeta {
734                ..Default::default()
735            },
736            status: Some(MaterializeStatus {
737                last_completed_rollout_environmentd_image_ref: Some(
738                    "materialize/environmentd:v26.0.0".to_owned(),
739                ),
740                ..Default::default()
741            }),
742        };
743
744        // Pass: upgrading from 26.0.0 to 27.7.3 (within 1 major version)
745        mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.3".to_owned();
746        assert!(mz.within_upgrade_window());
747
748        // Pass: upgrading from 26.0.0 to 27.7.8-dev.0 (within 1 major version, pre-release)
749        mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.8-dev.0".to_owned();
750        assert!(mz.within_upgrade_window());
751
752        // Fail: upgrading from 26.0.0 to 28.0.1 (more than 1 major version)
753        mz.spec.environmentd_image_ref = "materialize/environmentd:v28.0.1".to_owned();
754        assert!(!mz.within_upgrade_window());
755
756        // Pass: upgrading from 26.0.0 to 28.0.1.not_a_valid_version (invalid version, defaults to true)
757        mz.spec.environmentd_image_ref =
758            "materialize/environmentd:v28.0.1.not_a_valid_version".to_owned();
759        assert!(mz.within_upgrade_window());
760
761        // Pass: upgrading from 0.164.0 to 26.1.0 (self managed 25.2 to 26.0)
762        mz.status
763            .as_mut()
764            .unwrap()
765            .last_completed_rollout_environmentd_image_ref =
766            Some("materialize/environmentd:v0.147.20".to_owned());
767        mz.spec.environmentd_image_ref = "materialize/environmentd:v26.1.0".to_owned();
768        assert!(mz.within_upgrade_window());
769
770        // Pass: upgrading from 26.11.0-dev.0+b to 26.11.0-dev.0+a (same major.minor.patch.prerelease, different build metadata)
771        mz.status
772            .as_mut()
773            .unwrap()
774            .last_completed_rollout_environmentd_image_ref =
775            Some("materialize/environmentd:v26.11.0-dev.0+b".to_owned());
776        mz.spec.environmentd_image_ref = "materialize/environmentd:v26.11.0-dev.0+a".to_owned();
777        assert!(mz.within_upgrade_window());
778    }
779
780    #[mz_ore::test]
781    fn is_valid_upgrade_version() {
782        let success_tests = [
783            (Version::new(0, 83, 0), Version::new(0, 83, 0)),
784            (Version::new(0, 83, 0), Version::new(0, 84, 0)),
785            (Version::new(0, 9, 0), Version::new(0, 10, 0)),
786            (Version::new(0, 99, 0), Version::new(0, 100, 0)),
787            (Version::new(0, 83, 0), Version::new(0, 83, 1)),
788            (Version::new(0, 83, 0), Version::new(0, 83, 2)),
789            (Version::new(0, 83, 2), Version::new(0, 83, 10)),
790            // 0.147.20 to 26.0.0 represents the Self Managed 25.2 to 26.0 upgrade
791            (Version::new(0, 147, 20), Version::new(26, 0, 0)),
792            (Version::new(0, 164, 0), Version::new(26, 0, 0)),
793            (Version::new(26, 0, 0), Version::new(26, 1, 0)),
794            (Version::new(26, 5, 3), Version::new(26, 10, 0)),
795            (Version::new(0, 130, 0), Version::new(0, 147, 0)),
796        ];
797        for (active_version, next_version) in success_tests {
798            assert!(
799                Materialize::is_valid_upgrade_version(&active_version, &next_version),
800                "v{active_version} can upgrade to v{next_version}"
801            );
802        }
803
804        let failure_tests = [
805            (Version::new(0, 83, 0), Version::new(0, 82, 0)),
806            (Version::new(0, 83, 3), Version::new(0, 83, 2)),
807            (Version::new(0, 83, 3), Version::new(1, 83, 3)),
808            (Version::new(0, 83, 0), Version::new(0, 85, 0)),
809            (Version::new(26, 0, 0), Version::new(28, 0, 0)),
810            (Version::new(0, 130, 0), Version::new(26, 1, 0)),
811            // Disallow anything before 0.147.20 to upgrade
812            (Version::new(0, 147, 1), Version::new(26, 0, 0)),
813            // Disallow anything between 0.148.0 and 0.164.0 to upgrade
814            (Version::new(0, 148, 0), Version::new(26, 0, 0)),
815        ];
816        for (active_version, next_version) in failure_tests {
817            assert!(
818                !Materialize::is_valid_upgrade_version(&active_version, &next_version),
819                "v{active_version} can't upgrade to v{next_version}"
820            );
821        }
822    }
823}