1#![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";
41pub 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
59pub struct InitialStatusAnnotations {
60 pub active_generation: Option<u64>,
64 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 #[default]
107 WaitUntilReady,
108
109 ManuallyPromote,
137
138 ImmediatelyPromoteCausingDowntime,
149}
150
151pub const DEFAULT_ROLLOUT_REQUEST_TIMEOUT: &str = "24h";
156
157#[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 pub environmentd_image_ref: String,
207 pub environmentd_extra_args: Option<Vec<String>>,
209 pub environmentd_extra_env: Option<Vec<EnvVar>>,
211 #[kube(deprecated)]
220 pub environmentd_iam_role_arn: Option<String>,
221 pub environmentd_connection_role_arn: Option<String>,
224 pub environmentd_resource_requirements: Option<ResourceRequirements>,
226 pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
228 #[serde(skip_serializing_if = "Option::is_none")]
234 pub environmentd_readiness_probe: Option<Probe>,
235 #[serde(skip_serializing_if = "Option::is_none")]
241 pub environmentd_liveness_probe: Option<Probe>,
242 #[serde(skip_serializing_if = "Option::is_none")]
251 pub environmentd_startup_probe: Option<Probe>,
252 pub balancerd_resource_requirements: Option<ResourceRequirements>,
254 #[serde(skip_serializing_if = "Option::is_none")]
259 pub balancerd_configmap_name: Option<String>,
260 pub console_resource_requirements: Option<ResourceRequirements>,
262 pub balancerd_replicas: Option<i32>,
264 #[serde(skip_serializing_if = "Option::is_none")]
268 pub balancerd_externally_scaled: Option<bool>,
269 pub console_replicas: Option<i32>,
271
272 pub service_account_name: Option<String>,
275 pub service_account_annotations: Option<BTreeMap<String, String>>,
282 pub service_account_labels: Option<BTreeMap<String, String>>,
284 pub pod_annotations: Option<BTreeMap<String, String>>,
286 pub pod_labels: Option<BTreeMap<String, String>>,
288
289 #[serde(default)]
301 pub request_rollout: Uuid,
302 #[serde(default)]
307 pub force_promote: String,
308 #[serde(default)]
315 pub force_rollout: Uuid,
316 #[kube(deprecated)]
320 #[serde(default)]
321 pub in_place_rollout: bool,
322 #[serde(default)]
324 pub rollout_strategy: MaterializeRolloutStrategy,
325 #[serde(default)]
346 pub rollout_request_timeout: RolloutRequestTimeout,
347 pub backend_secret_name: String,
352 #[serde(default)]
354 pub authenticator_kind: AuthenticatorKind,
355 #[serde(default)]
357 pub enable_rbac: bool,
358
359 #[serde(default)]
366 pub environment_id: Uuid,
367
368 pub system_parameter_configmap_name: Option<String>,
383
384 pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
388 pub console_external_certificate_spec: Option<MaterializeCertSpec>,
393 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 .and_then(|requirements| requirements.get("memory").cloned())
551 .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 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 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 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 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 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 pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
759 let version = parse_image_ref(&self.spec.environmentd_image_ref);
760 match version {
761 Some(version) => version.cmp_precedence(minimum).is_ge(),
763 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 pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
782 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 return (active_version.minor == 147 && active_version.patch >= 20)
796 || active_version.minor >= 164;
797 } else {
798 return false;
799 }
800 }
801 if next_version.minor == 147 && active_version.minor == 130 {
803 return true;
804 }
805 return next_version.minor <= active_version.minor + 1;
807 } else if active_version.major >= 26 {
808 return next_version.major <= active_version.major + 1;
810 }
811
812 true
813 }
814
815 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 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 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 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 pub resource_id: String,
876 pub active_generation: u64,
878 pub last_completed_rollout_request: Uuid,
880 pub last_completed_rollout_environmentd_image_ref: Option<String>,
884 pub resources_hash: String,
889 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 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 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 #[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 #[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 #[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 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 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 pub environmentd_image_ref: String,
1591 pub environmentd_extra_args: Option<Vec<String>>,
1593 pub environmentd_extra_env: Option<Vec<EnvVar>>,
1595 pub environmentd_connection_role_arn: Option<String>,
1598 pub environmentd_resource_requirements: Option<ResourceRequirements>,
1600 pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
1602 #[serde(skip_serializing_if = "Option::is_none")]
1608 pub environmentd_readiness_probe: Option<Probe>,
1609 #[serde(skip_serializing_if = "Option::is_none")]
1615 pub environmentd_liveness_probe: Option<Probe>,
1616 #[serde(skip_serializing_if = "Option::is_none")]
1625 pub environmentd_startup_probe: Option<Probe>,
1626 pub balancerd_resource_requirements: Option<ResourceRequirements>,
1630 #[serde(skip_serializing_if = "Option::is_none")]
1635 pub balancerd_configmap_name: Option<String>,
1636 pub console_resource_requirements: Option<ResourceRequirements>,
1640 pub balancerd_replicas: Option<i32>,
1644 #[serde(skip_serializing_if = "Option::is_none")]
1650 pub balancerd_externally_scaled: Option<bool>,
1651 pub console_replicas: Option<i32>,
1655
1656 pub service_account_name: Option<String>,
1659 pub service_account_annotations: Option<BTreeMap<String, String>>,
1666 pub service_account_labels: Option<BTreeMap<String, String>>,
1668 pub pod_annotations: Option<BTreeMap<String, String>>,
1670 pub pod_labels: Option<BTreeMap<String, String>>,
1672
1673 pub force_promote: Option<String>,
1680 #[serde(default)]
1684 pub force_rollout: Uuid,
1685 #[serde(default)]
1687 pub rollout_strategy: MaterializeRolloutStrategy,
1688 #[serde(default)]
1709 pub rollout_request_timeout: RolloutRequestTimeout,
1710 pub backend_secret_name: String,
1714 #[serde(default)]
1716 pub authenticator_kind: AuthenticatorKind,
1717 #[serde(default)]
1719 pub enable_rbac: bool,
1720
1721 #[serde(default)]
1728 pub environment_id: Uuid,
1729
1730 pub system_parameter_configmap_name: Option<String>,
1745
1746 pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
1752 pub console_external_certificate_spec: Option<MaterializeCertSpec>,
1759 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 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 .and_then(|requirements| requirements.get("memory").cloned())
1976 .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 pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
2070 let version = parse_image_ref(&self.spec.environmentd_image_ref);
2071 match version {
2072 Some(version) => version.cmp_precedence(minimum).is_ge(),
2074 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 pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
2093 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 return (active_version.minor == 147 && active_version.patch >= 20)
2108 || active_version.minor >= 164;
2109 } else {
2110 return false;
2111 }
2112 }
2113 if next_version.minor == 147 && active_version.minor == 130 {
2115 return true;
2116 }
2117 return next_version.minor <= active_version.minor + 1;
2119 } else if active_version.major >= 26 {
2120 return next_version.major <= active_version.major + 1;
2122 }
2123
2124 true
2125 }
2126
2127 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 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 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 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 pub resource_id: String,
2188 pub active_generation: u64,
2190 pub last_completed_rollout_environmentd_image_ref: Option<String>,
2194 pub last_completed_rollout_hash: Option<String>,
2196 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 || status.last_completed_rollout_request.is_nil()
2320 })
2321 .unwrap_or(true);
2322 if currently_rolling_out {
2323 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 #[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 #[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 #[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 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 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
2877const NIL_UUID_STR: &str = "00000000-0000-0000-0000-000000000000";
2879
2880pub type PartialField = Option<Option<serde_json::Value>>;
2889
2890mod 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 None => serializer.serialize_none(),
2913 }
2914 }
2915}
2916
2917fn present<T: Serialize>(value: T) -> PartialField {
2920 Some(Some(
2921 serde_json::to_value(value).expect("CRD field serializes to JSON"),
2922 ))
2923}
2924
2925fn 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
2930fn 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
2950pub 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
2985pub 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 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 let status = mz(&[]).status();
3067 assert!(crate::crd::is_valid_resource_id(&status.resource_id));
3068 assert_eq!(status.active_generation, 0);
3069
3070 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 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 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 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)] fn force_rollout_annotation_forces_new_generation() {
3126 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 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 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 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 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 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 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 mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.3".to_owned();
3393 assert!(mz.within_upgrade_window());
3394
3395 mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.8-dev.0".to_owned();
3397 assert!(mz.within_upgrade_window());
3398
3399 mz.spec.environmentd_image_ref = "materialize/environmentd:v28.0.1".to_owned();
3401 assert!(!mz.within_upgrade_window());
3402
3403 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 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 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 (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 (Version::new(0, 147, 1), Version::new(26, 0, 0)),
3460 (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 let default = humantime::parse_duration(DEFAULT_ROLLOUT_REQUEST_TIMEOUT).unwrap();
3484 assert_eq!(default, Duration::from_secs(24 * 60 * 60));
3485
3486 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 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 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 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 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 assert_eq!(
3566 mz_with(vec![condition("UpToDate", "Unknown")]).rollout_in_progress_since(),
3567 Some(now)
3568 );
3569
3570 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 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 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 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 assert_eq!(
3629 mz_with(vec![condition("Unknown")]).up_to_date_transition_time("Unknown", now),
3630 stored
3631 );
3632
3633 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 let mz = mz_with(NEW, None);
3656 assert_eq!(mz.active_environmentd_image_ref(), NEW);
3657
3658 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 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 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 #[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 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 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)] 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 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 #[mz_ore::test]
3840 #[cfg_attr(miri, ignore)] 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)] 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 let status = converted["status"].as_object().unwrap();
3899 assert!(status["resourcesHash"].is_string());
3900 assert!(status["lastCompletedRolloutRequest"].is_string());
3901 }
3902
3903 #[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}