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
177#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)]
184#[serde(rename_all = "camelCase")]
185pub struct AdditionalTrustBundle {
186 #[serde(skip_serializing_if = "Option::is_none")]
188 pub config_map_key_ref: Option<TrustBundleKeyRef>,
189 #[serde(skip_serializing_if = "Option::is_none")]
191 pub secret_key_ref: Option<TrustBundleKeyRef>,
192}
193
194impl AdditionalTrustBundle {
195 pub fn source(&self) -> Result<TrustBundleSource<'_>, anyhow::Error> {
198 match (&self.config_map_key_ref, &self.secret_key_ref) {
199 (Some(key_ref), None) => Ok(TrustBundleSource::ConfigMap(key_ref)),
200 (None, Some(key_ref)) => Ok(TrustBundleSource::Secret(key_ref)),
201 (Some(_), Some(_)) => {
202 anyhow::bail!("set only one of configMapKeyRef and secretKeyRef, not both")
203 }
204 (None, None) => anyhow::bail!("set one of configMapKeyRef or secretKeyRef"),
205 }
206 }
207}
208
209#[derive(Clone, Copy, Debug, PartialEq)]
211pub enum TrustBundleSource<'a> {
212 ConfigMap(&'a TrustBundleKeyRef),
213 Secret(&'a TrustBundleKeyRef),
214}
215
216#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)]
218#[serde(rename_all = "camelCase")]
219pub struct TrustBundleKeyRef {
220 pub name: String,
222 pub key: String,
224}
225
226pub mod v1alpha1 {
227 use super::*;
228
229 #[derive(
230 CustomResource,
231 Clone,
232 Debug,
233 Default,
234 PartialEq,
235 Deserialize,
236 Serialize,
237 JsonSchema
238 )]
239 #[serde(rename_all = "camelCase")]
240 #[kube(
241 namespaced,
242 group = "materialize.cloud",
243 version = "v1alpha1",
244 kind = "Materialize",
245 singular = "materialize",
246 plural = "materializes",
247 shortname = "mzs",
248 status = "MaterializeStatus",
249 printcolumn = r#"{"name": "ImageRefRunning", "type": "string", "description": "Reference to the Docker image that is currently in use.", "jsonPath": ".status.lastCompletedRolloutEnvironmentdImageRef", "priority": 1}"#,
250 printcolumn = r#"{"name": "ImageRefToDeploy", "type": "string", "description": "Reference to the Docker image which will be deployed on the next rollout.", "jsonPath": ".spec.environmentdImageRef", "priority": 1}"#,
251 printcolumn = r#"{"name": "UpToDate", "type": "string", "description": "Whether the spec has been applied", "jsonPath": ".status.conditions[?(@.type==\"UpToDate\")].status", "priority": 1}"#
252 )]
253 pub struct MaterializeSpec {
254 pub environmentd_image_ref: String,
256 pub environmentd_extra_args: Option<Vec<String>>,
258 pub environmentd_extra_env: Option<Vec<EnvVar>>,
260 #[kube(deprecated)]
269 pub environmentd_iam_role_arn: Option<String>,
270 pub environmentd_connection_role_arn: Option<String>,
273 pub environmentd_resource_requirements: Option<ResourceRequirements>,
275 pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
277 #[serde(skip_serializing_if = "Option::is_none")]
283 pub environmentd_readiness_probe: Option<Probe>,
284 #[serde(skip_serializing_if = "Option::is_none")]
290 pub environmentd_liveness_probe: Option<Probe>,
291 #[serde(skip_serializing_if = "Option::is_none")]
300 pub environmentd_startup_probe: Option<Probe>,
301 pub balancerd_resource_requirements: Option<ResourceRequirements>,
303 #[serde(skip_serializing_if = "Option::is_none")]
308 pub balancerd_configmap_name: Option<String>,
309 pub console_resource_requirements: Option<ResourceRequirements>,
311 pub balancerd_replicas: Option<i32>,
313 #[serde(skip_serializing_if = "Option::is_none")]
317 pub balancerd_externally_scaled: Option<bool>,
318 pub console_replicas: Option<i32>,
320
321 pub service_account_name: Option<String>,
324 pub service_account_annotations: Option<BTreeMap<String, String>>,
331 pub service_account_labels: Option<BTreeMap<String, String>>,
333 pub pod_annotations: Option<BTreeMap<String, String>>,
335 pub pod_labels: Option<BTreeMap<String, String>>,
337
338 #[serde(default)]
350 pub request_rollout: Uuid,
351 #[serde(default)]
356 pub force_promote: String,
357 #[serde(default)]
364 pub force_rollout: Uuid,
365 #[kube(deprecated)]
369 #[serde(default)]
370 pub in_place_rollout: bool,
371 #[serde(default)]
373 pub rollout_strategy: MaterializeRolloutStrategy,
374 #[serde(default)]
395 pub rollout_request_timeout: RolloutRequestTimeout,
396 pub backend_secret_name: String,
401 #[serde(default)]
403 pub authenticator_kind: AuthenticatorKind,
404 #[serde(default)]
406 pub enable_rbac: bool,
407
408 #[serde(default)]
415 pub environment_id: Uuid,
416
417 pub system_parameter_configmap_name: Option<String>,
432 #[serde(skip_serializing_if = "Option::is_none")]
441 pub additional_trust_bundle: Option<AdditionalTrustBundle>,
442
443 pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
447 pub console_external_certificate_spec: Option<MaterializeCertSpec>,
452 pub internal_certificate_spec: Option<MaterializeCertSpec>,
457 }
458
459 impl Materialize {
460 pub fn backend_secret_name(&self) -> String {
461 self.spec.backend_secret_name.clone()
462 }
463
464 pub fn namespace(&self) -> String {
465 self.meta().namespace.clone().unwrap()
466 }
467
468 pub fn create_service_account(&self) -> bool {
469 self.spec.service_account_name.is_none()
470 }
471
472 pub fn service_account_name(&self) -> String {
473 self.spec
474 .service_account_name
475 .clone()
476 .unwrap_or_else(|| self.name_unchecked())
477 }
478
479 pub fn role_name(&self) -> String {
480 self.name_unchecked()
481 }
482
483 pub fn role_binding_name(&self) -> String {
484 self.name_unchecked()
485 }
486
487 pub fn environmentd_statefulset_name(&self, generation: u64) -> String {
488 self.name_prefixed(&format!("environmentd-{generation}"))
489 }
490
491 pub fn environmentd_app_name(&self) -> String {
492 "environmentd".to_owned()
493 }
494
495 pub fn environmentd_service_name(&self) -> String {
496 self.name_prefixed("environmentd")
497 }
498
499 pub fn environmentd_service_internal_fqdn(&self) -> String {
500 format!(
501 "{}.{}.svc.cluster.local",
502 self.environmentd_service_name(),
503 self.meta().namespace.as_ref().unwrap()
504 )
505 }
506
507 pub fn environmentd_generation_service_name(&self, generation: u64) -> String {
508 self.name_prefixed(&format!("environmentd-{generation}"))
509 }
510
511 pub fn balancerd_app_name(&self) -> String {
512 "balancerd".to_owned()
513 }
514
515 pub fn environmentd_certificate_name(&self) -> String {
516 self.name_prefixed("environmentd-external")
517 }
518
519 pub fn environmentd_certificate_secret_name(&self) -> String {
520 self.name_prefixed("environmentd-tls")
521 }
522
523 pub fn balancerd_deployment_name(&self) -> String {
524 self.name_prefixed("balancerd")
525 }
526
527 pub fn balancerd_service_name(&self) -> String {
528 self.name_prefixed("balancerd")
529 }
530
531 pub fn console_app_name(&self) -> String {
532 "console".to_owned()
533 }
534
535 pub fn balancerd_external_certificate_name(&self) -> String {
536 self.name_prefixed("balancerd-external")
537 }
538
539 pub fn balancerd_external_certificate_secret_name(&self) -> String {
540 self.name_prefixed("balancerd-external-tls")
541 }
542
543 pub fn balancerd_replicas(&self) -> i32 {
544 self.spec.balancerd_replicas.unwrap_or(2)
545 }
546
547 pub fn console_replicas(&self) -> i32 {
548 self.spec.console_replicas.unwrap_or(2)
549 }
550
551 pub fn console_configmap_name(&self) -> String {
552 self.name_prefixed("console")
553 }
554
555 pub fn console_deployment_name(&self) -> String {
556 self.name_prefixed("console")
557 }
558
559 pub fn console_service_name(&self) -> String {
560 self.name_prefixed("console")
561 }
562
563 pub fn console_external_certificate_name(&self) -> String {
564 self.name_prefixed("console-external")
565 }
566
567 pub fn console_external_certificate_secret_name(&self) -> String {
568 self.name_prefixed("console-external-tls")
569 }
570
571 pub fn persist_pubsub_service_name(&self, generation: u64) -> String {
572 self.name_prefixed(&format!("persist-pubsub-{generation}"))
573 }
574
575 pub fn listeners_configmap_name(&self, generation: u64) -> String {
576 self.name_prefixed(&format!("listeners-{generation}"))
577 }
578
579 pub fn name_prefixed(&self, suffix: &str) -> String {
580 format!("mz{}-{}", self.resource_id(), suffix)
581 }
582
583 pub fn resource_id(&self) -> &str {
584 &self.status.as_ref().unwrap().resource_id
585 }
586
587 pub fn system_parameter_configmap_name(&self) -> Option<String> {
588 self.spec.system_parameter_configmap_name.clone()
589 }
590
591 pub fn environmentd_scratch_volume_storage_requirement(&self) -> Quantity {
592 self.spec
593 .environmentd_scratch_volume_storage_requirement
594 .clone()
595 .unwrap_or_else(|| {
596 self.spec
597 .environmentd_resource_requirements
598 .as_ref()
599 .and_then(|requirements| {
600 requirements
601 .requests
602 .as_ref()
603 .or(requirements.limits.as_ref())
604 })
605 .and_then(|requirements| requirements.get("memory").cloned())
610 .unwrap_or_else(|| Quantity("4096Mi".to_string()))
612 })
613 }
614
615 pub fn environment_id(&self, cloud_provider: &str, region: &str) -> String {
616 format!(
617 "{}-{}-{}-0",
618 cloud_provider, region, self.spec.environment_id,
619 )
620 }
621
622 pub fn requested_reconciliation_id(&self) -> Uuid {
623 self.spec.request_rollout
624 }
625
626 pub fn force_rollout_value(&self) -> String {
638 match self
639 .meta()
640 .annotations
641 .as_ref()
642 .and_then(|annotations| annotations.get(FORCE_ROLLOUT_ANNOTATION))
643 {
644 Some(annotation) => format!("{}/{}", self.spec.force_rollout, annotation),
645 None => self.spec.force_rollout.to_string(),
646 }
647 }
648
649 pub fn rollout_requested(&self) -> bool {
650 self.requested_reconciliation_id()
651 != self
652 .status
653 .as_ref()
654 .map_or_else(Uuid::nil, |status| status.last_completed_rollout_request)
655 }
656
657 pub fn rollout_request_timeout(&self) -> Duration {
662 let timeout = &self.spec.rollout_request_timeout.0;
663 humantime::parse_duration(timeout)
664 .or_else(|e| {
665 tracing::warn!(
666 rollout_request_timeout = %timeout,
667 "failed to parse rolloutRequestTimeout, using default: {e}",
668 );
669 humantime::parse_duration(DEFAULT_ROLLOUT_REQUEST_TIMEOUT)
670 })
671 .expect("DEFAULT_ROLLOUT_REQUEST_TIMEOUT must be a valid duration")
672 }
673
674 pub fn rollout_in_progress_since(&self) -> Option<Timestamp> {
691 self.status
692 .as_ref()?
693 .conditions
694 .iter()
695 .find_map(|condition| {
696 if condition.type_ == "UpToDate"
697 && condition.status == "Unknown"
698 && condition.reason != "Promoting"
699 {
700 Some(condition.last_transition_time.0)
701 } else {
702 None
703 }
704 })
705 }
706
707 pub fn up_to_date_transition_time(&self, new_status: &str, now: Timestamp) -> Timestamp {
719 self.status
720 .as_ref()
721 .and_then(|status| {
722 status
723 .conditions
724 .iter()
725 .find(|condition| condition.type_ == "UpToDate")
726 })
727 .filter(|condition| condition.status == new_status)
728 .map_or(now, |condition| condition.last_transition_time.0)
729 }
730
731 pub fn active_environmentd_image_ref(&self) -> &str {
739 self.status
740 .as_ref()
741 .and_then(|s| s.last_completed_rollout_environmentd_image_ref.as_deref())
742 .unwrap_or(&self.spec.environmentd_image_ref)
743 }
744
745 pub fn set_force_promote(&mut self) {
746 self.spec.force_promote = self.spec.request_rollout.hyphenated().to_string();
747 }
748
749 pub fn should_force_promote(&self) -> bool {
750 self.spec.force_promote == self.spec.request_rollout.hyphenated().to_string()
751 || self.spec.force_promote
752 == super::v1::Materialize::from(self.clone()).generate_rollout_hash()
753 || self.spec.rollout_strategy
754 == MaterializeRolloutStrategy::ImmediatelyPromoteCausingDowntime
755 }
756
757 pub fn conditions_need_update(&self) -> bool {
758 let Some(status) = self.status.as_ref() else {
759 return true;
760 };
761 if status.conditions.is_empty() {
762 return true;
763 }
764 for condition in &status.conditions {
765 if condition.observed_generation != self.meta().generation {
766 return true;
767 }
768 }
769 false
770 }
771
772 pub fn is_ready_to_promote(&self, resources_hash: &str) -> bool {
773 let Some(status) = self.status.as_ref() else {
774 return false;
775 };
776 if status.conditions.is_empty() {
777 return false;
778 }
779 status
780 .conditions
781 .iter()
782 .any(|condition| condition.reason == "ReadyToPromote")
783 && &status.resources_hash == resources_hash
784 }
785
786 pub fn is_promoting(&self) -> bool {
787 let Some(status) = self.status.as_ref() else {
788 return false;
789 };
790 if status.conditions.is_empty() {
791 return false;
792 }
793 status
794 .conditions
795 .iter()
796 .any(|condition| condition.reason == "Promoting")
797 }
798
799 pub fn update_in_progress(&self) -> bool {
800 let Some(status) = self.status.as_ref() else {
801 return false;
802 };
803 if status.conditions.is_empty() {
804 return false;
805 }
806 for condition in &status.conditions {
807 if condition.type_ == "UpToDate" && condition.status == "Unknown" {
808 return true;
809 }
810 }
811 false
812 }
813
814 pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
818 let version = parse_image_ref(&self.spec.environmentd_image_ref);
819 match version {
820 Some(version) => version.cmp_precedence(minimum).is_ge(),
822 None => {
828 tracing::warn!(
829 image_ref = %self.spec.environmentd_image_ref,
830 "failed to parse image ref",
831 );
832 true
833 }
834 }
835 }
836
837 pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
841 if next_version.cmp_precedence(active_version) == std::cmp::Ordering::Less {
846 return false;
847 }
848
849 if active_version.major == 0 {
850 if next_version.major != active_version.major {
851 if next_version.major == 26 {
852 return (active_version.minor == 147 && active_version.patch >= 20)
855 || active_version.minor >= 164;
856 } else {
857 return false;
858 }
859 }
860 if next_version.minor == 147 && active_version.minor == 130 {
862 return true;
863 }
864 return next_version.minor <= active_version.minor + 1;
866 } else if active_version.major >= 26 {
867 return next_version.major <= active_version.major + 1;
869 }
870
871 true
872 }
873
874 pub fn within_upgrade_window(&self) -> bool {
877 let active_environmentd_version = self
878 .status
879 .as_ref()
880 .and_then(|status| {
881 status
882 .last_completed_rollout_environmentd_image_ref
883 .as_ref()
884 })
885 .and_then(|image_ref| parse_image_ref(image_ref));
886
887 if let (Some(next_environmentd_version), Some(active_environmentd_version)) = (
888 parse_image_ref(&self.spec.environmentd_image_ref),
889 active_environmentd_version,
890 ) {
891 Self::is_valid_upgrade_version(
892 &active_environmentd_version,
893 &next_environmentd_version,
894 )
895 } else {
896 true
899 }
900 }
901
902 pub fn status(&self) -> MaterializeStatus {
903 self.status.clone().unwrap_or_else(|| {
904 let mut status = MaterializeStatus::default();
905
906 let initial =
909 InitialStatusAnnotations::parse(self.annotations()).unwrap_or_else(|e| {
910 warn!("ignoring initial status annotations: {e}");
911 InitialStatusAnnotations::default()
912 });
913
914 status.resource_id = initial.resource_id.unwrap_or_else(new_resource_id);
915
916 if let Some(active_generation) = initial.active_generation {
917 status.active_generation = active_generation;
918 }
919
920 status.last_completed_rollout_environmentd_image_ref =
923 Some(self.spec.environmentd_image_ref.clone());
924
925 status
926 })
927 }
928 }
929
930 #[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema, PartialEq)]
931 #[serde(rename_all = "camelCase")]
932 pub struct MaterializeStatus {
933 pub resource_id: String,
935 pub active_generation: u64,
937 pub last_completed_rollout_request: Uuid,
939 pub last_completed_rollout_environmentd_image_ref: Option<String>,
943 pub resources_hash: String,
948 pub last_completed_rollout_hash: Option<String>,
951 pub conditions: Vec<Condition>,
952 }
953
954 impl MaterializeStatus {
955 pub fn needs_update(&self, other: &Self) -> bool {
956 let now = Timestamp::now();
957 let mut a = self.clone();
958 for condition in &mut a.conditions {
959 condition.last_transition_time = Time(now);
960 }
961 let mut b = other.clone();
962 for condition in &mut b.conditions {
963 condition.last_transition_time = Time(now);
964 }
965 a != b
966 }
967 }
968
969 impl ManagedResource for Materialize {
970 fn default_labels(&self) -> BTreeMap<String, String> {
971 BTreeMap::from_iter([
972 (
973 "materialize.cloud/organization-name".to_owned(),
974 self.name_unchecked(),
975 ),
976 (
977 "materialize.cloud/organization-namespace".to_owned(),
978 self.namespace(),
979 ),
980 (
981 "materialize.cloud/mz-resource-id".to_owned(),
982 self.resource_id().to_owned(),
983 ),
984 ])
985 }
986
987 fn app_name(&self) -> Option<&str> {
988 Some("environmentd")
989 }
990 }
991
992 impl From<v1::Materialize> for Materialize {
993 fn from(value: v1::Materialize) -> Self {
994 let rollout_hash = value.generate_rollout_hash();
995 let request_rollout = Uuid::new_v5(&Uuid::NAMESPACE_OID, rollout_hash.as_bytes());
999 Materialize {
1000 metadata: value.metadata,
1001 spec: MaterializeSpec {
1002 environmentd_image_ref: value.spec.environmentd_image_ref,
1003 environmentd_extra_args: value.spec.environmentd_extra_args,
1004 environmentd_extra_env: value.spec.environmentd_extra_env,
1005 environmentd_iam_role_arn: None,
1006 environmentd_connection_role_arn: value.spec.environmentd_connection_role_arn,
1007 environmentd_resource_requirements: value
1008 .spec
1009 .environmentd_resource_requirements,
1010 environmentd_scratch_volume_storage_requirement: value
1011 .spec
1012 .environmentd_scratch_volume_storage_requirement,
1013 environmentd_readiness_probe: value.spec.environmentd_readiness_probe,
1014 environmentd_liveness_probe: value.spec.environmentd_liveness_probe,
1015 environmentd_startup_probe: value.spec.environmentd_startup_probe,
1016 balancerd_resource_requirements: value.spec.balancerd_resource_requirements,
1017 balancerd_configmap_name: value.spec.balancerd_configmap_name,
1018 console_resource_requirements: value.spec.console_resource_requirements,
1019 balancerd_replicas: value.spec.balancerd_replicas,
1020 balancerd_externally_scaled: value.spec.balancerd_externally_scaled,
1021 console_replicas: value.spec.console_replicas,
1022 service_account_name: value.spec.service_account_name,
1023 service_account_annotations: value.spec.service_account_annotations,
1024 service_account_labels: value.spec.service_account_labels,
1025 pod_annotations: value.spec.pod_annotations,
1026 pod_labels: value.spec.pod_labels,
1027 force_promote: value.spec.force_promote.unwrap_or_default(),
1028 force_rollout: value.spec.force_rollout,
1029 rollout_strategy: value.spec.rollout_strategy,
1030 rollout_request_timeout: value.spec.rollout_request_timeout,
1031 backend_secret_name: value.spec.backend_secret_name,
1032 authenticator_kind: value.spec.authenticator_kind,
1033 enable_rbac: value.spec.enable_rbac,
1034 environment_id: value.spec.environment_id,
1035 system_parameter_configmap_name: value.spec.system_parameter_configmap_name,
1036 additional_trust_bundle: value.spec.additional_trust_bundle,
1037 balancerd_external_certificate_spec: value
1038 .spec
1039 .balancerd_external_certificate_spec,
1040 console_external_certificate_spec: value.spec.console_external_certificate_spec,
1041 internal_certificate_spec: value.spec.internal_certificate_spec,
1042 request_rollout,
1043 in_place_rollout: false,
1044 },
1045 status: value.status.map(|status| MaterializeStatus {
1046 resource_id: status.resource_id,
1047 active_generation: status.active_generation,
1048 last_completed_rollout_environmentd_image_ref: status
1049 .last_completed_rollout_environmentd_image_ref,
1050 conditions: status.conditions,
1051 last_completed_rollout_request: status
1055 .last_completed_rollout_hash
1056 .as_ref()
1057 .map(|hash| Uuid::new_v5(&Uuid::NAMESPACE_OID, hash.as_bytes()))
1058 .unwrap_or(Uuid::nil()),
1059 last_completed_rollout_hash: status.last_completed_rollout_hash,
1060 resources_hash: "".to_owned(),
1061 }),
1062 }
1063 }
1064 }
1065
1066 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
1075 #[serde(rename_all = "camelCase")]
1076 pub struct PartialMaterializeSpec {
1077 #[serde(
1078 default,
1079 with = "double_option",
1080 skip_serializing_if = "Option::is_none"
1081 )]
1082 pub environmentd_image_ref: PartialField,
1083 #[serde(
1084 default,
1085 with = "double_option",
1086 skip_serializing_if = "Option::is_none"
1087 )]
1088 pub environmentd_extra_args: PartialField,
1089 #[serde(
1090 default,
1091 with = "double_option",
1092 skip_serializing_if = "Option::is_none"
1093 )]
1094 pub environmentd_extra_env: PartialField,
1095 #[serde(
1096 default,
1097 with = "double_option",
1098 skip_serializing_if = "Option::is_none"
1099 )]
1100 pub environmentd_iam_role_arn: PartialField,
1101 #[serde(
1102 default,
1103 with = "double_option",
1104 skip_serializing_if = "Option::is_none"
1105 )]
1106 pub environmentd_connection_role_arn: PartialField,
1107 #[serde(
1108 default,
1109 with = "double_option",
1110 skip_serializing_if = "Option::is_none"
1111 )]
1112 pub environmentd_resource_requirements: PartialField,
1113 #[serde(
1114 default,
1115 with = "double_option",
1116 skip_serializing_if = "Option::is_none"
1117 )]
1118 pub environmentd_scratch_volume_storage_requirement: PartialField,
1119 #[serde(
1120 default,
1121 with = "double_option",
1122 skip_serializing_if = "Option::is_none"
1123 )]
1124 pub environmentd_readiness_probe: PartialField,
1125 #[serde(
1126 default,
1127 with = "double_option",
1128 skip_serializing_if = "Option::is_none"
1129 )]
1130 pub environmentd_liveness_probe: PartialField,
1131 #[serde(
1132 default,
1133 with = "double_option",
1134 skip_serializing_if = "Option::is_none"
1135 )]
1136 pub environmentd_startup_probe: PartialField,
1137 #[serde(
1138 default,
1139 with = "double_option",
1140 skip_serializing_if = "Option::is_none"
1141 )]
1142 pub balancerd_resource_requirements: PartialField,
1143 #[serde(
1144 default,
1145 with = "double_option",
1146 skip_serializing_if = "Option::is_none"
1147 )]
1148 pub balancerd_configmap_name: PartialField,
1149 #[serde(
1150 default,
1151 with = "double_option",
1152 skip_serializing_if = "Option::is_none"
1153 )]
1154 pub console_resource_requirements: PartialField,
1155 #[serde(
1156 default,
1157 with = "double_option",
1158 skip_serializing_if = "Option::is_none"
1159 )]
1160 pub balancerd_replicas: PartialField,
1161 #[serde(
1162 default,
1163 with = "double_option",
1164 skip_serializing_if = "Option::is_none"
1165 )]
1166 pub balancerd_externally_scaled: PartialField,
1167 #[serde(
1168 default,
1169 with = "double_option",
1170 skip_serializing_if = "Option::is_none"
1171 )]
1172 pub console_replicas: PartialField,
1173 #[serde(
1174 default,
1175 with = "double_option",
1176 skip_serializing_if = "Option::is_none"
1177 )]
1178 pub service_account_name: PartialField,
1179 #[serde(
1180 default,
1181 with = "double_option",
1182 skip_serializing_if = "Option::is_none"
1183 )]
1184 pub service_account_annotations: PartialField,
1185 #[serde(
1186 default,
1187 with = "double_option",
1188 skip_serializing_if = "Option::is_none"
1189 )]
1190 pub service_account_labels: PartialField,
1191 #[serde(
1192 default,
1193 with = "double_option",
1194 skip_serializing_if = "Option::is_none"
1195 )]
1196 pub pod_annotations: PartialField,
1197 #[serde(
1198 default,
1199 with = "double_option",
1200 skip_serializing_if = "Option::is_none"
1201 )]
1202 pub pod_labels: PartialField,
1203 #[serde(
1204 default,
1205 with = "double_option",
1206 skip_serializing_if = "Option::is_none"
1207 )]
1208 pub request_rollout: PartialField,
1209 #[serde(
1210 default,
1211 with = "double_option",
1212 skip_serializing_if = "Option::is_none"
1213 )]
1214 pub force_promote: PartialField,
1215 #[serde(
1216 default,
1217 with = "double_option",
1218 skip_serializing_if = "Option::is_none"
1219 )]
1220 pub force_rollout: PartialField,
1221 #[serde(
1222 default,
1223 with = "double_option",
1224 skip_serializing_if = "Option::is_none"
1225 )]
1226 pub in_place_rollout: PartialField,
1227 #[serde(
1228 default,
1229 with = "double_option",
1230 skip_serializing_if = "Option::is_none"
1231 )]
1232 pub rollout_strategy: PartialField,
1233 #[serde(
1234 default,
1235 with = "double_option",
1236 skip_serializing_if = "Option::is_none"
1237 )]
1238 pub rollout_request_timeout: PartialField,
1239 #[serde(
1240 default,
1241 with = "double_option",
1242 skip_serializing_if = "Option::is_none"
1243 )]
1244 pub backend_secret_name: PartialField,
1245 #[serde(
1246 default,
1247 with = "double_option",
1248 skip_serializing_if = "Option::is_none"
1249 )]
1250 pub authenticator_kind: PartialField,
1251 #[serde(
1252 default,
1253 with = "double_option",
1254 skip_serializing_if = "Option::is_none"
1255 )]
1256 pub enable_rbac: PartialField,
1257 #[serde(
1258 default,
1259 with = "double_option",
1260 skip_serializing_if = "Option::is_none"
1261 )]
1262 pub environment_id: PartialField,
1263 #[serde(
1264 default,
1265 with = "double_option",
1266 skip_serializing_if = "Option::is_none"
1267 )]
1268 pub system_parameter_configmap_name: PartialField,
1269 #[serde(
1270 default,
1271 with = "double_option",
1272 skip_serializing_if = "Option::is_none"
1273 )]
1274 pub additional_trust_bundle: PartialField,
1275 #[serde(
1276 default,
1277 with = "double_option",
1278 skip_serializing_if = "Option::is_none"
1279 )]
1280 pub balancerd_external_certificate_spec: PartialField,
1281 #[serde(
1282 default,
1283 with = "double_option",
1284 skip_serializing_if = "Option::is_none"
1285 )]
1286 pub console_external_certificate_spec: PartialField,
1287 #[serde(
1288 default,
1289 with = "double_option",
1290 skip_serializing_if = "Option::is_none"
1291 )]
1292 pub internal_certificate_spec: PartialField,
1293 #[serde(flatten)]
1294 pub extra: serde_json::Map<String, serde_json::Value>,
1295 }
1296
1297 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
1299 #[serde(rename_all = "camelCase")]
1300 pub struct PartialMaterializeStatus {
1301 #[serde(
1302 default,
1303 with = "double_option",
1304 skip_serializing_if = "Option::is_none"
1305 )]
1306 pub resource_id: PartialField,
1307 #[serde(
1308 default,
1309 with = "double_option",
1310 skip_serializing_if = "Option::is_none"
1311 )]
1312 pub active_generation: PartialField,
1313 #[serde(
1314 default,
1315 with = "double_option",
1316 skip_serializing_if = "Option::is_none"
1317 )]
1318 pub last_completed_rollout_request: PartialField,
1319 #[serde(
1320 default,
1321 with = "double_option",
1322 skip_serializing_if = "Option::is_none"
1323 )]
1324 pub last_completed_rollout_environmentd_image_ref: PartialField,
1325 #[serde(
1326 default,
1327 with = "double_option",
1328 skip_serializing_if = "Option::is_none"
1329 )]
1330 pub resources_hash: PartialField,
1331 #[serde(
1332 default,
1333 with = "double_option",
1334 skip_serializing_if = "Option::is_none"
1335 )]
1336 pub last_completed_rollout_hash: PartialField,
1337 #[serde(
1338 default,
1339 with = "double_option",
1340 skip_serializing_if = "Option::is_none"
1341 )]
1342 pub conditions: PartialField,
1343 #[serde(flatten)]
1344 pub extra: serde_json::Map<String, serde_json::Value>,
1345 }
1346
1347 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
1349 #[serde(rename_all = "camelCase")]
1350 pub struct PartialMaterialize {
1351 #[serde(skip_serializing_if = "Option::is_none")]
1352 pub api_version: Option<String>,
1353 #[serde(skip_serializing_if = "Option::is_none")]
1354 pub kind: Option<serde_json::Value>,
1355 #[serde(skip_serializing_if = "Option::is_none")]
1356 pub metadata: Option<serde_json::Value>,
1357 #[serde(skip_serializing_if = "Option::is_none")]
1358 pub spec: Option<PartialMaterializeSpec>,
1359 #[serde(skip_serializing_if = "Option::is_none")]
1360 pub status: Option<PartialMaterializeStatus>,
1361 #[serde(flatten)]
1362 pub extra: serde_json::Map<String, serde_json::Value>,
1363 }
1364
1365 impl From<MaterializeSpec> for PartialMaterializeSpec {
1366 fn from(spec: MaterializeSpec) -> Self {
1367 let MaterializeSpec {
1368 environmentd_image_ref,
1369 environmentd_extra_args,
1370 environmentd_extra_env,
1371 environmentd_iam_role_arn,
1372 environmentd_connection_role_arn,
1373 environmentd_resource_requirements,
1374 environmentd_scratch_volume_storage_requirement,
1375 environmentd_readiness_probe,
1376 environmentd_liveness_probe,
1377 environmentd_startup_probe,
1378 balancerd_resource_requirements,
1379 balancerd_configmap_name,
1380 console_resource_requirements,
1381 balancerd_replicas,
1382 balancerd_externally_scaled,
1383 console_replicas,
1384 service_account_name,
1385 service_account_annotations,
1386 service_account_labels,
1387 pod_annotations,
1388 pod_labels,
1389 request_rollout,
1390 force_promote,
1391 force_rollout,
1392 in_place_rollout,
1393 rollout_strategy,
1394 rollout_request_timeout,
1395 backend_secret_name,
1396 authenticator_kind,
1397 enable_rbac,
1398 environment_id,
1399 system_parameter_configmap_name,
1400 additional_trust_bundle,
1401 balancerd_external_certificate_spec,
1402 console_external_certificate_spec,
1403 internal_certificate_spec,
1404 } = spec;
1405 Self {
1406 environmentd_image_ref: present(environmentd_image_ref),
1407 environmentd_extra_args: present_opt(environmentd_extra_args),
1408 environmentd_extra_env: present_opt(environmentd_extra_env),
1409 environmentd_iam_role_arn: present_opt(environmentd_iam_role_arn),
1410 environmentd_connection_role_arn: present_opt(environmentd_connection_role_arn),
1411 environmentd_resource_requirements: present_opt(environmentd_resource_requirements),
1412 environmentd_scratch_volume_storage_requirement: present_opt(
1413 environmentd_scratch_volume_storage_requirement,
1414 ),
1415 environmentd_readiness_probe: present_opt(environmentd_readiness_probe),
1416 environmentd_liveness_probe: present_opt(environmentd_liveness_probe),
1417 environmentd_startup_probe: present_opt(environmentd_startup_probe),
1418 balancerd_resource_requirements: present_opt(balancerd_resource_requirements),
1419 balancerd_configmap_name: present_opt(balancerd_configmap_name),
1420 console_resource_requirements: present_opt(console_resource_requirements),
1421 balancerd_replicas: present_opt(balancerd_replicas),
1422 balancerd_externally_scaled: present_opt(balancerd_externally_scaled),
1423 console_replicas: present_opt(console_replicas),
1424 service_account_name: present_opt(service_account_name),
1425 service_account_annotations: present_opt(service_account_annotations),
1426 service_account_labels: present_opt(service_account_labels),
1427 pod_annotations: present_opt(pod_annotations),
1428 pod_labels: present_opt(pod_labels),
1429 request_rollout: present(request_rollout),
1430 force_promote: present(force_promote),
1431 force_rollout: present(force_rollout),
1432 in_place_rollout: present(in_place_rollout),
1433 rollout_strategy: present(rollout_strategy),
1434 rollout_request_timeout: present(rollout_request_timeout),
1435 backend_secret_name: present(backend_secret_name),
1436 authenticator_kind: present(authenticator_kind),
1437 enable_rbac: present(enable_rbac),
1438 environment_id: present(environment_id),
1439 system_parameter_configmap_name: present_opt(system_parameter_configmap_name),
1440 additional_trust_bundle: present_opt(additional_trust_bundle),
1441 balancerd_external_certificate_spec: present_opt(
1442 balancerd_external_certificate_spec,
1443 ),
1444 console_external_certificate_spec: present_opt(console_external_certificate_spec),
1445 internal_certificate_spec: present_opt(internal_certificate_spec),
1446 extra: serde_json::Map::new(),
1447 }
1448 }
1449 }
1450
1451 impl From<MaterializeStatus> for PartialMaterializeStatus {
1452 fn from(status: MaterializeStatus) -> Self {
1453 let MaterializeStatus {
1454 resource_id,
1455 active_generation,
1456 last_completed_rollout_request,
1457 last_completed_rollout_environmentd_image_ref,
1458 resources_hash,
1459 last_completed_rollout_hash,
1460 conditions,
1461 } = status;
1462 Self {
1463 resource_id: present(resource_id),
1464 active_generation: present(active_generation),
1465 last_completed_rollout_request: present(last_completed_rollout_request),
1466 last_completed_rollout_environmentd_image_ref: present_opt(
1467 last_completed_rollout_environmentd_image_ref,
1468 ),
1469 resources_hash: present(resources_hash),
1470 last_completed_rollout_hash: present_opt(last_completed_rollout_hash),
1471 conditions: present(conditions),
1472 extra: serde_json::Map::new(),
1473 }
1474 }
1475 }
1476
1477 impl From<Materialize> for PartialMaterialize {
1478 fn from(mz: Materialize) -> Self {
1479 let Materialize {
1480 metadata,
1481 spec,
1482 status,
1483 } = mz;
1484 Self {
1485 api_version: Some("materialize.cloud/v1alpha1".to_owned()),
1486 kind: Some("Materialize".into()),
1487 metadata: Some(
1488 serde_json::to_value(metadata).expect("ObjectMeta serializes to JSON"),
1489 ),
1490 spec: Some(spec.into()),
1491 status: status.map(Into::into),
1492 extra: serde_json::Map::new(),
1493 }
1494 }
1495 }
1496
1497 impl From<super::v1::PartialMaterializeSpec> for PartialMaterializeSpec {
1498 fn from(spec: super::v1::PartialMaterializeSpec) -> Self {
1499 let super::v1::PartialMaterializeSpec {
1500 environmentd_image_ref,
1501 environmentd_extra_args,
1502 environmentd_extra_env,
1503 environmentd_connection_role_arn,
1504 environmentd_resource_requirements,
1505 environmentd_scratch_volume_storage_requirement,
1506 environmentd_readiness_probe,
1507 environmentd_liveness_probe,
1508 environmentd_startup_probe,
1509 balancerd_resource_requirements,
1510 balancerd_configmap_name,
1511 console_resource_requirements,
1512 balancerd_replicas,
1513 balancerd_externally_scaled,
1514 console_replicas,
1515 service_account_name,
1516 service_account_annotations,
1517 service_account_labels,
1518 pod_annotations,
1519 pod_labels,
1520 force_promote,
1521 force_rollout,
1522 rollout_strategy,
1523 rollout_request_timeout,
1524 backend_secret_name,
1525 authenticator_kind,
1526 enable_rbac,
1527 environment_id,
1528 system_parameter_configmap_name,
1529 additional_trust_bundle,
1530 balancerd_external_certificate_spec,
1531 console_external_certificate_spec,
1532 internal_certificate_spec,
1533 extra,
1534 } = spec;
1535 Self {
1536 environmentd_image_ref,
1537 environmentd_extra_args,
1538 environmentd_extra_env,
1539 environmentd_iam_role_arn: None,
1540 environmentd_connection_role_arn,
1541 environmentd_resource_requirements,
1542 environmentd_scratch_volume_storage_requirement,
1543 environmentd_readiness_probe,
1544 environmentd_liveness_probe,
1545 environmentd_startup_probe,
1546 balancerd_resource_requirements,
1547 balancerd_configmap_name,
1548 console_resource_requirements,
1549 balancerd_replicas,
1550 balancerd_externally_scaled,
1551 console_replicas,
1552 service_account_name,
1553 service_account_annotations,
1554 service_account_labels,
1555 pod_annotations,
1556 pod_labels,
1557 request_rollout: None,
1562 force_promote,
1563 force_rollout,
1564 in_place_rollout: None,
1565 rollout_strategy,
1566 rollout_request_timeout,
1567 backend_secret_name,
1568 authenticator_kind,
1569 enable_rbac,
1570 environment_id,
1571 system_parameter_configmap_name,
1572 additional_trust_bundle,
1573 balancerd_external_certificate_spec,
1574 console_external_certificate_spec,
1575 internal_certificate_spec,
1576 extra,
1577 }
1578 }
1579 }
1580
1581 impl From<super::v1::PartialMaterializeStatus> for PartialMaterializeStatus {
1582 fn from(status: super::v1::PartialMaterializeStatus) -> Self {
1583 let super::v1::PartialMaterializeStatus {
1584 resource_id,
1585 active_generation,
1586 last_completed_rollout_environmentd_image_ref,
1587 last_completed_rollout_hash,
1588 requested_rollout_hash: _,
1589 conditions,
1590 extra,
1591 } = status;
1592 Self {
1593 resource_id,
1594 active_generation,
1595 last_completed_rollout_request: None,
1600 resources_hash: None,
1601 last_completed_rollout_environmentd_image_ref,
1602 last_completed_rollout_hash,
1603 conditions,
1604 extra,
1605 }
1606 }
1607 }
1608
1609 impl From<super::v1::PartialMaterialize> for PartialMaterialize {
1610 fn from(mz: super::v1::PartialMaterialize) -> Self {
1611 let super::v1::PartialMaterialize {
1612 api_version: _,
1613 kind,
1614 metadata,
1615 spec,
1616 status,
1617 extra,
1618 } = mz;
1619 Self {
1620 api_version: Some("materialize.cloud/v1alpha1".to_owned()),
1621 kind,
1622 metadata,
1623 spec: spec.map(Into::into),
1624 status: status.map(Into::into),
1625 extra,
1626 }
1627 }
1628 }
1629}
1630
1631pub mod v1 {
1632 use super::*;
1633
1634 #[derive(
1635 CustomResource,
1636 Clone,
1637 Debug,
1638 Default,
1639 PartialEq,
1640 Deserialize,
1641 Serialize,
1642 JsonSchema
1643 )]
1644 #[serde(rename_all = "camelCase")]
1645 #[kube(
1646 namespaced,
1647 group = "materialize.cloud",
1648 version = "v1",
1649 kind = "Materialize",
1650 singular = "materialize",
1651 plural = "materializes",
1652 shortname = "mzs",
1653 status = "MaterializeStatus",
1654 printcolumn = r#"{"name": "ImageRefRunning", "type": "string", "description": "Reference to the Docker image that is currently in use.", "jsonPath": ".status.lastCompletedRolloutEnvironmentdImageRef", "priority": 1}"#,
1655 printcolumn = r#"{"name": "ImageRefToDeploy", "type": "string", "description": "Reference to the Docker image which will be deployed on the next rollout.", "jsonPath": ".spec.environmentdImageRef", "priority": 1}"#,
1656 printcolumn = r#"{"name": "UpToDate", "type": "string", "description": "Whether the spec has been applied", "jsonPath": ".status.conditions[?(@.type==\"UpToDate\")].status", "priority": 1}"#
1657 )]
1658 pub struct MaterializeSpec {
1659 pub environmentd_image_ref: String,
1661 pub environmentd_extra_args: Option<Vec<String>>,
1663 pub environmentd_extra_env: Option<Vec<EnvVar>>,
1665 pub environmentd_connection_role_arn: Option<String>,
1668 pub environmentd_resource_requirements: Option<ResourceRequirements>,
1670 pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
1672 #[serde(skip_serializing_if = "Option::is_none")]
1678 pub environmentd_readiness_probe: Option<Probe>,
1679 #[serde(skip_serializing_if = "Option::is_none")]
1685 pub environmentd_liveness_probe: Option<Probe>,
1686 #[serde(skip_serializing_if = "Option::is_none")]
1695 pub environmentd_startup_probe: Option<Probe>,
1696 pub balancerd_resource_requirements: Option<ResourceRequirements>,
1700 #[serde(skip_serializing_if = "Option::is_none")]
1705 pub balancerd_configmap_name: Option<String>,
1706 pub console_resource_requirements: Option<ResourceRequirements>,
1710 pub balancerd_replicas: Option<i32>,
1714 #[serde(skip_serializing_if = "Option::is_none")]
1720 pub balancerd_externally_scaled: Option<bool>,
1721 pub console_replicas: Option<i32>,
1725
1726 pub service_account_name: Option<String>,
1729 pub service_account_annotations: Option<BTreeMap<String, String>>,
1736 pub service_account_labels: Option<BTreeMap<String, String>>,
1738 pub pod_annotations: Option<BTreeMap<String, String>>,
1740 pub pod_labels: Option<BTreeMap<String, String>>,
1742
1743 pub force_promote: Option<String>,
1750 #[serde(default)]
1754 pub force_rollout: Uuid,
1755 #[serde(default)]
1757 pub rollout_strategy: MaterializeRolloutStrategy,
1758 #[serde(default)]
1779 pub rollout_request_timeout: RolloutRequestTimeout,
1780 pub backend_secret_name: String,
1784 #[serde(default)]
1786 pub authenticator_kind: AuthenticatorKind,
1787 #[serde(default)]
1789 pub enable_rbac: bool,
1790
1791 #[serde(default)]
1798 pub environment_id: Uuid,
1799
1800 pub system_parameter_configmap_name: Option<String>,
1815 #[serde(skip_serializing_if = "Option::is_none")]
1824 pub additional_trust_bundle: Option<AdditionalTrustBundle>,
1825
1826 pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
1832 pub console_external_certificate_spec: Option<MaterializeCertSpec>,
1839 pub internal_certificate_spec: Option<MaterializeCertSpec>,
1844 }
1845
1846 impl Materialize {
1847 pub fn generate_rollout_hash(&self) -> String {
1848 let mut hasher = Sha256::new();
1849 let spec = MaterializeSpec {
1852 environmentd_image_ref: self.spec.environmentd_image_ref.clone(),
1853 environmentd_extra_args: self.spec.environmentd_extra_args.clone(),
1854 environmentd_extra_env: self.spec.environmentd_extra_env.clone(),
1855 environmentd_connection_role_arn: self
1856 .spec
1857 .environmentd_connection_role_arn
1858 .clone(),
1859 environmentd_resource_requirements: self
1860 .spec
1861 .environmentd_resource_requirements
1862 .clone(),
1863 environmentd_scratch_volume_storage_requirement: self
1864 .spec
1865 .environmentd_scratch_volume_storage_requirement
1866 .clone(),
1867 environmentd_readiness_probe: self.spec.environmentd_readiness_probe.clone(),
1868 environmentd_liveness_probe: self.spec.environmentd_liveness_probe.clone(),
1869 environmentd_startup_probe: self.spec.environmentd_startup_probe.clone(),
1870 balancerd_resource_requirements: None,
1871 balancerd_configmap_name: None,
1872 console_resource_requirements: None,
1873 balancerd_replicas: None,
1874 balancerd_externally_scaled: None,
1875 console_replicas: None,
1876 service_account_name: self.spec.service_account_name.clone(),
1877 service_account_annotations: self.spec.service_account_annotations.clone(),
1878 service_account_labels: self.spec.service_account_labels.clone(),
1879 pod_annotations: self.spec.pod_annotations.clone(),
1880 pod_labels: self.spec.pod_labels.clone(),
1881 force_promote: None,
1882 force_rollout: self.spec.force_rollout,
1883 rollout_strategy: self.spec.rollout_strategy.clone(),
1884 rollout_request_timeout: self.spec.rollout_request_timeout.clone(),
1885 backend_secret_name: self.spec.backend_secret_name.clone(),
1886 authenticator_kind: self.spec.authenticator_kind,
1887 enable_rbac: self.spec.enable_rbac,
1888 environment_id: self.spec.environment_id,
1889 system_parameter_configmap_name: self.spec.system_parameter_configmap_name.clone(),
1890 additional_trust_bundle: self.spec.additional_trust_bundle.clone(),
1891 balancerd_external_certificate_spec: None,
1892 console_external_certificate_spec: None,
1893 internal_certificate_spec: self.spec.internal_certificate_spec.clone(),
1894 };
1895 hasher.update(&serde_json::to_vec(&spec).unwrap());
1896 if let Some(annotation) = self
1897 .metadata
1898 .annotations
1899 .as_ref()
1900 .and_then(|annotations| annotations.get(FORCE_ROLLOUT_ANNOTATION))
1901 {
1902 hasher.update(annotation);
1903 }
1904 hex::encode(hasher.finalize())
1905 }
1906
1907 pub fn backend_secret_name(&self) -> String {
1908 self.spec.backend_secret_name.clone()
1909 }
1910
1911 pub fn namespace(&self) -> String {
1912 self.meta().namespace.clone().unwrap()
1913 }
1914
1915 pub fn create_service_account(&self) -> bool {
1916 self.spec.service_account_name.is_none()
1917 }
1918
1919 pub fn service_account_name(&self) -> String {
1920 self.spec
1921 .service_account_name
1922 .clone()
1923 .unwrap_or_else(|| self.name_unchecked())
1924 }
1925
1926 pub fn role_name(&self) -> String {
1927 self.name_unchecked()
1928 }
1929
1930 pub fn role_binding_name(&self) -> String {
1931 self.name_unchecked()
1932 }
1933
1934 pub fn environmentd_statefulset_name(&self, generation: u64) -> String {
1935 self.name_prefixed(&format!("environmentd-{generation}"))
1936 }
1937
1938 pub fn environmentd_app_name(&self) -> String {
1939 "environmentd".to_owned()
1940 }
1941
1942 pub fn environmentd_service_name(&self) -> String {
1943 self.name_prefixed("environmentd")
1944 }
1945
1946 pub fn environmentd_service_internal_fqdn(&self) -> String {
1947 format!(
1948 "{}.{}.svc.cluster.local",
1949 self.environmentd_service_name(),
1950 self.meta().namespace.as_ref().unwrap()
1951 )
1952 }
1953
1954 pub fn environmentd_generation_service_name(&self, generation: u64) -> String {
1955 self.name_prefixed(&format!("environmentd-{generation}"))
1956 }
1957
1958 pub fn balancerd_app_name(&self) -> String {
1959 "balancerd".to_owned()
1960 }
1961
1962 pub fn environmentd_certificate_name(&self) -> String {
1963 self.name_prefixed("environmentd-external")
1964 }
1965
1966 pub fn environmentd_certificate_secret_name(&self) -> String {
1967 self.name_prefixed("environmentd-tls")
1968 }
1969
1970 pub fn balancerd_deployment_name(&self) -> String {
1971 self.name_prefixed("balancerd")
1972 }
1973
1974 pub fn balancerd_service_name(&self) -> String {
1975 self.name_prefixed("balancerd")
1976 }
1977
1978 pub fn console_app_name(&self) -> String {
1979 "console".to_owned()
1980 }
1981
1982 pub fn balancerd_external_certificate_name(&self) -> String {
1983 self.name_prefixed("balancerd-external")
1984 }
1985
1986 pub fn balancerd_external_certificate_secret_name(&self) -> String {
1987 self.name_prefixed("balancerd-external-tls")
1988 }
1989
1990 pub fn balancerd_replicas(&self) -> i32 {
1991 self.spec.balancerd_replicas.unwrap_or(2)
1992 }
1993
1994 pub fn console_replicas(&self) -> i32 {
1995 self.spec.console_replicas.unwrap_or(2)
1996 }
1997
1998 pub fn console_configmap_name(&self) -> String {
1999 self.name_prefixed("console")
2000 }
2001
2002 pub fn console_deployment_name(&self) -> String {
2003 self.name_prefixed("console")
2004 }
2005
2006 pub fn console_service_name(&self) -> String {
2007 self.name_prefixed("console")
2008 }
2009
2010 pub fn console_external_certificate_name(&self) -> String {
2011 self.name_prefixed("console-external")
2012 }
2013
2014 pub fn console_external_certificate_secret_name(&self) -> String {
2015 self.name_prefixed("console-external-tls")
2016 }
2017
2018 pub fn persist_pubsub_service_name(&self, generation: u64) -> String {
2019 self.name_prefixed(&format!("persist-pubsub-{generation}"))
2020 }
2021
2022 pub fn listeners_configmap_name(&self, generation: u64) -> String {
2023 self.name_prefixed(&format!("listeners-{generation}"))
2024 }
2025
2026 pub fn name_prefixed(&self, suffix: &str) -> String {
2027 format!("mz{}-{}", self.resource_id(), suffix)
2028 }
2029
2030 pub fn resource_id(&self) -> &str {
2031 &self.status.as_ref().unwrap().resource_id
2032 }
2033
2034 pub fn system_parameter_configmap_name(&self) -> Option<String> {
2035 self.spec.system_parameter_configmap_name.clone()
2036 }
2037
2038 pub fn environmentd_scratch_volume_storage_requirement(&self) -> Quantity {
2039 self.spec
2040 .environmentd_scratch_volume_storage_requirement
2041 .clone()
2042 .unwrap_or_else(|| {
2043 self.spec
2044 .environmentd_resource_requirements
2045 .as_ref()
2046 .and_then(|requirements| {
2047 requirements
2048 .requests
2049 .as_ref()
2050 .or(requirements.limits.as_ref())
2051 })
2052 .and_then(|requirements| requirements.get("memory").cloned())
2057 .unwrap_or_else(|| Quantity("4096Mi".to_string()))
2059 })
2060 }
2061
2062 pub fn environment_id(&self, cloud_provider: &str, region: &str) -> String {
2063 format!(
2064 "{}-{}-{}-0",
2065 cloud_provider, region, self.spec.environment_id,
2066 )
2067 }
2068
2069 pub fn rollout_requested(&self) -> bool {
2070 self.status
2071 .as_ref()
2072 .map(|status| status.last_completed_rollout_hash != status.requested_rollout_hash)
2073 .unwrap_or(false)
2074 }
2075
2076 pub fn set_force_promote(&mut self) {
2077 self.spec.force_promote = Some(self.generate_rollout_hash());
2078 }
2079
2080 pub fn should_force_promote(&self) -> bool {
2081 self.spec.force_promote.as_ref()
2082 == self
2083 .status
2084 .as_ref()
2085 .and_then(|status| status.requested_rollout_hash.as_ref())
2086 || self.spec.rollout_strategy
2087 == MaterializeRolloutStrategy::ImmediatelyPromoteCausingDowntime
2088 }
2089
2090 pub fn conditions_need_update(&self) -> bool {
2091 let Some(status) = self.status.as_ref() else {
2092 return true;
2093 };
2094 if status.conditions.is_empty() {
2095 return true;
2096 }
2097 for condition in &status.conditions {
2098 if condition.observed_generation != self.meta().generation {
2099 return true;
2100 }
2101 }
2102 false
2103 }
2104
2105 pub fn is_ready_to_promote(&self, rollout_hash: &str) -> bool {
2106 let Some(status) = self.status.as_ref() else {
2107 return false;
2108 };
2109 if status.conditions.is_empty() {
2110 return false;
2111 }
2112 status
2113 .conditions
2114 .iter()
2115 .any(|condition| condition.reason == "ReadyToPromote")
2116 && status.requested_rollout_hash.as_deref() == Some(rollout_hash)
2117 }
2118
2119 pub fn is_promoting(&self) -> bool {
2120 let Some(status) = self.status.as_ref() else {
2121 return false;
2122 };
2123 if status.conditions.is_empty() {
2124 return false;
2125 }
2126 status
2127 .conditions
2128 .iter()
2129 .any(|condition| condition.reason == "Promoting")
2130 }
2131
2132 pub fn update_in_progress(&self) -> bool {
2133 let Some(status) = self.status.as_ref() else {
2134 return false;
2135 };
2136 if status.conditions.is_empty() {
2137 return false;
2138 }
2139 for condition in &status.conditions {
2140 if condition.type_ == "UpToDate" && condition.status == "Unknown" {
2141 return true;
2142 }
2143 }
2144 false
2145 }
2146
2147 pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
2151 let version = parse_image_ref(&self.spec.environmentd_image_ref);
2152 match version {
2153 Some(version) => version.cmp_precedence(minimum).is_ge(),
2155 None => {
2161 tracing::warn!(
2162 image_ref = %self.spec.environmentd_image_ref,
2163 "failed to parse image ref",
2164 );
2165 true
2166 }
2167 }
2168 }
2169
2170 pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
2174 if next_version.cmp_precedence(active_version) == std::cmp::Ordering::Less {
2179 return false;
2180 }
2181
2182 if active_version.major == 0 {
2183 if next_version.major != active_version.major {
2184 if next_version.major == 26 {
2185 return (active_version.minor == 147 && active_version.patch >= 20)
2189 || active_version.minor >= 164;
2190 } else {
2191 return false;
2192 }
2193 }
2194 if next_version.minor == 147 && active_version.minor == 130 {
2196 return true;
2197 }
2198 return next_version.minor <= active_version.minor + 1;
2200 } else if active_version.major >= 26 {
2201 return next_version.major <= active_version.major + 1;
2203 }
2204
2205 true
2206 }
2207
2208 pub fn within_upgrade_window(&self) -> bool {
2211 let active_environmentd_version = self
2212 .status
2213 .as_ref()
2214 .and_then(|status| {
2215 status
2216 .last_completed_rollout_environmentd_image_ref
2217 .as_ref()
2218 })
2219 .and_then(|image_ref| parse_image_ref(image_ref));
2220
2221 if let (Some(next_environmentd_version), Some(active_environmentd_version)) = (
2222 parse_image_ref(&self.spec.environmentd_image_ref),
2223 active_environmentd_version,
2224 ) {
2225 Self::is_valid_upgrade_version(
2226 &active_environmentd_version,
2227 &next_environmentd_version,
2228 )
2229 } else {
2230 true
2233 }
2234 }
2235
2236 pub fn status(&self) -> MaterializeStatus {
2237 self.status.clone().unwrap_or_else(|| {
2238 let mut status = MaterializeStatus::default();
2239
2240 let initial =
2243 InitialStatusAnnotations::parse(self.annotations()).unwrap_or_else(|e| {
2244 warn!("ignoring initial status annotations: {e}");
2245 InitialStatusAnnotations::default()
2246 });
2247
2248 status.resource_id = initial.resource_id.unwrap_or_else(new_resource_id);
2249
2250 if let Some(active_generation) = initial.active_generation {
2251 status.active_generation = active_generation;
2252 }
2253
2254 status.last_completed_rollout_environmentd_image_ref =
2257 Some(self.spec.environmentd_image_ref.clone());
2258
2259 status
2260 })
2261 }
2262 }
2263
2264 #[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema, PartialEq)]
2265 #[serde(rename_all = "camelCase")]
2266 pub struct MaterializeStatus {
2267 pub resource_id: String,
2269 pub active_generation: u64,
2271 pub last_completed_rollout_environmentd_image_ref: Option<String>,
2275 pub last_completed_rollout_hash: Option<String>,
2277 pub requested_rollout_hash: Option<String>,
2280 pub conditions: Vec<Condition>,
2281 }
2282
2283 impl MaterializeStatus {
2284 pub fn needs_update(&self, other: &Self) -> bool {
2285 let now = Timestamp::now();
2286 let mut a = self.clone();
2287 for condition in &mut a.conditions {
2288 condition.last_transition_time = Time(now);
2289 }
2290 let mut b = other.clone();
2291 for condition in &mut b.conditions {
2292 condition.last_transition_time = Time(now);
2293 }
2294 a != b
2295 }
2296 }
2297
2298 impl ManagedResource for Materialize {
2299 fn default_labels(&self) -> BTreeMap<String, String> {
2300 BTreeMap::from_iter([
2301 (
2302 "materialize.cloud/organization-name".to_owned(),
2303 self.name_unchecked(),
2304 ),
2305 (
2306 "materialize.cloud/organization-namespace".to_owned(),
2307 self.namespace(),
2308 ),
2309 (
2310 "materialize.cloud/mz-resource-id".to_owned(),
2311 self.resource_id().to_owned(),
2312 ),
2313 ])
2314 }
2315
2316 fn app_name(&self) -> Option<&str> {
2317 Some("environmentd")
2318 }
2319 }
2320
2321 impl From<v1alpha1::Materialize> for Materialize {
2322 fn from(value: v1alpha1::Materialize) -> Self {
2323 let is_promoting = value.is_promoting();
2324 let service_account_annotations = if let Some(environmentd_iam_role_arn) =
2325 value.spec.environmentd_iam_role_arn
2326 {
2327 let mut annotations = value.spec.service_account_annotations.unwrap_or_default();
2328 annotations
2329 .entry("eks.amazonaws.com/role-arn".to_owned())
2330 .or_insert(environmentd_iam_role_arn);
2331 Some(annotations)
2332 } else {
2333 value.spec.service_account_annotations
2334 };
2335 let mut mz = Materialize {
2336 metadata: value.metadata,
2337 spec: MaterializeSpec {
2338 environmentd_image_ref: value.spec.environmentd_image_ref,
2339 environmentd_extra_args: value.spec.environmentd_extra_args,
2340 environmentd_extra_env: value.spec.environmentd_extra_env,
2341 environmentd_connection_role_arn: value.spec.environmentd_connection_role_arn,
2342 environmentd_resource_requirements: value
2343 .spec
2344 .environmentd_resource_requirements,
2345 environmentd_scratch_volume_storage_requirement: value
2346 .spec
2347 .environmentd_scratch_volume_storage_requirement,
2348 environmentd_readiness_probe: value.spec.environmentd_readiness_probe,
2349 environmentd_liveness_probe: value.spec.environmentd_liveness_probe,
2350 environmentd_startup_probe: value.spec.environmentd_startup_probe,
2351 balancerd_resource_requirements: value.spec.balancerd_resource_requirements,
2352 balancerd_configmap_name: value.spec.balancerd_configmap_name,
2353 console_resource_requirements: value.spec.console_resource_requirements,
2354 balancerd_replicas: value.spec.balancerd_replicas,
2355 balancerd_externally_scaled: value.spec.balancerd_externally_scaled,
2356 console_replicas: value.spec.console_replicas,
2357 service_account_name: value.spec.service_account_name,
2358 service_account_annotations,
2359 service_account_labels: value.spec.service_account_labels,
2360 pod_annotations: value.spec.pod_annotations,
2361 pod_labels: value.spec.pod_labels,
2362 force_promote: if value.spec.force_promote.is_empty()
2363 || &value.spec.force_promote == "00000000-0000-0000-0000-000000000000"
2364 {
2365 None
2366 } else {
2367 Some(value.spec.force_promote.to_string())
2368 },
2369 force_rollout: value.spec.force_rollout,
2370 rollout_strategy: value.spec.rollout_strategy,
2371 rollout_request_timeout: value.spec.rollout_request_timeout,
2372 backend_secret_name: value.spec.backend_secret_name,
2373 authenticator_kind: value.spec.authenticator_kind,
2374 enable_rbac: value.spec.enable_rbac,
2375 environment_id: value.spec.environment_id,
2376 system_parameter_configmap_name: value.spec.system_parameter_configmap_name,
2377 additional_trust_bundle: value.spec.additional_trust_bundle,
2378 balancerd_external_certificate_spec: value
2379 .spec
2380 .balancerd_external_certificate_spec,
2381 console_external_certificate_spec: value.spec.console_external_certificate_spec,
2382 internal_certificate_spec: value.spec.internal_certificate_spec,
2383 },
2384 status: None,
2385 };
2386 let calculated_rollout_hash = mz.generate_rollout_hash();
2387 let last_completed_rollout_hash = match value
2388 .status
2389 .as_ref()
2390 .and_then(|status| status.last_completed_rollout_hash.to_owned())
2391 {
2392 Some(last_completed_rollout_hash) => Some(last_completed_rollout_hash),
2393 None => {
2394 let currently_rolling_out = value
2395 .status
2396 .as_ref()
2397 .map(|status| {
2398 status.last_completed_rollout_request != value.spec.request_rollout
2399 || status.last_completed_rollout_request.is_nil()
2402 })
2403 .unwrap_or(true);
2404 if currently_rolling_out {
2405 None
2407 } else {
2408 Some(calculated_rollout_hash.clone())
2409 }
2410 }
2411 };
2412 let requested_rollout_hash = if is_promoting {
2413 None
2414 } else {
2415 Some(calculated_rollout_hash)
2416 };
2417 mz.status = value.status.map(|status| MaterializeStatus {
2418 resource_id: status.resource_id,
2419 active_generation: status.active_generation,
2420 last_completed_rollout_environmentd_image_ref: status
2421 .last_completed_rollout_environmentd_image_ref,
2422 last_completed_rollout_hash,
2423 requested_rollout_hash,
2424 conditions: status.conditions,
2425 });
2426 mz
2427 }
2428 }
2429
2430 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
2439 #[serde(rename_all = "camelCase")]
2440 pub struct PartialMaterializeSpec {
2441 #[serde(
2442 default,
2443 with = "double_option",
2444 skip_serializing_if = "Option::is_none"
2445 )]
2446 pub environmentd_image_ref: PartialField,
2447 #[serde(
2448 default,
2449 with = "double_option",
2450 skip_serializing_if = "Option::is_none"
2451 )]
2452 pub environmentd_extra_args: PartialField,
2453 #[serde(
2454 default,
2455 with = "double_option",
2456 skip_serializing_if = "Option::is_none"
2457 )]
2458 pub environmentd_extra_env: PartialField,
2459 #[serde(
2460 default,
2461 with = "double_option",
2462 skip_serializing_if = "Option::is_none"
2463 )]
2464 pub environmentd_connection_role_arn: PartialField,
2465 #[serde(
2466 default,
2467 with = "double_option",
2468 skip_serializing_if = "Option::is_none"
2469 )]
2470 pub environmentd_resource_requirements: PartialField,
2471 #[serde(
2472 default,
2473 with = "double_option",
2474 skip_serializing_if = "Option::is_none"
2475 )]
2476 pub environmentd_scratch_volume_storage_requirement: PartialField,
2477 #[serde(
2478 default,
2479 with = "double_option",
2480 skip_serializing_if = "Option::is_none"
2481 )]
2482 pub environmentd_readiness_probe: PartialField,
2483 #[serde(
2484 default,
2485 with = "double_option",
2486 skip_serializing_if = "Option::is_none"
2487 )]
2488 pub environmentd_liveness_probe: PartialField,
2489 #[serde(
2490 default,
2491 with = "double_option",
2492 skip_serializing_if = "Option::is_none"
2493 )]
2494 pub environmentd_startup_probe: PartialField,
2495 #[serde(
2496 default,
2497 with = "double_option",
2498 skip_serializing_if = "Option::is_none"
2499 )]
2500 pub balancerd_resource_requirements: PartialField,
2501 #[serde(
2502 default,
2503 with = "double_option",
2504 skip_serializing_if = "Option::is_none"
2505 )]
2506 pub balancerd_configmap_name: PartialField,
2507 #[serde(
2508 default,
2509 with = "double_option",
2510 skip_serializing_if = "Option::is_none"
2511 )]
2512 pub console_resource_requirements: PartialField,
2513 #[serde(
2514 default,
2515 with = "double_option",
2516 skip_serializing_if = "Option::is_none"
2517 )]
2518 pub balancerd_replicas: PartialField,
2519 #[serde(
2520 default,
2521 with = "double_option",
2522 skip_serializing_if = "Option::is_none"
2523 )]
2524 pub balancerd_externally_scaled: PartialField,
2525 #[serde(
2526 default,
2527 with = "double_option",
2528 skip_serializing_if = "Option::is_none"
2529 )]
2530 pub console_replicas: PartialField,
2531 #[serde(
2532 default,
2533 with = "double_option",
2534 skip_serializing_if = "Option::is_none"
2535 )]
2536 pub service_account_name: PartialField,
2537 #[serde(
2538 default,
2539 with = "double_option",
2540 skip_serializing_if = "Option::is_none"
2541 )]
2542 pub service_account_annotations: PartialField,
2543 #[serde(
2544 default,
2545 with = "double_option",
2546 skip_serializing_if = "Option::is_none"
2547 )]
2548 pub service_account_labels: PartialField,
2549 #[serde(
2550 default,
2551 with = "double_option",
2552 skip_serializing_if = "Option::is_none"
2553 )]
2554 pub pod_annotations: PartialField,
2555 #[serde(
2556 default,
2557 with = "double_option",
2558 skip_serializing_if = "Option::is_none"
2559 )]
2560 pub pod_labels: PartialField,
2561 #[serde(
2562 default,
2563 with = "double_option",
2564 skip_serializing_if = "Option::is_none"
2565 )]
2566 pub force_promote: PartialField,
2567 #[serde(
2568 default,
2569 with = "double_option",
2570 skip_serializing_if = "Option::is_none"
2571 )]
2572 pub force_rollout: PartialField,
2573 #[serde(
2574 default,
2575 with = "double_option",
2576 skip_serializing_if = "Option::is_none"
2577 )]
2578 pub rollout_strategy: PartialField,
2579 #[serde(
2580 default,
2581 with = "double_option",
2582 skip_serializing_if = "Option::is_none"
2583 )]
2584 pub rollout_request_timeout: PartialField,
2585 #[serde(
2586 default,
2587 with = "double_option",
2588 skip_serializing_if = "Option::is_none"
2589 )]
2590 pub backend_secret_name: PartialField,
2591 #[serde(
2592 default,
2593 with = "double_option",
2594 skip_serializing_if = "Option::is_none"
2595 )]
2596 pub authenticator_kind: PartialField,
2597 #[serde(
2598 default,
2599 with = "double_option",
2600 skip_serializing_if = "Option::is_none"
2601 )]
2602 pub enable_rbac: PartialField,
2603 #[serde(
2604 default,
2605 with = "double_option",
2606 skip_serializing_if = "Option::is_none"
2607 )]
2608 pub environment_id: PartialField,
2609 #[serde(
2610 default,
2611 with = "double_option",
2612 skip_serializing_if = "Option::is_none"
2613 )]
2614 pub system_parameter_configmap_name: PartialField,
2615 #[serde(
2616 default,
2617 with = "double_option",
2618 skip_serializing_if = "Option::is_none"
2619 )]
2620 pub additional_trust_bundle: PartialField,
2621 #[serde(
2622 default,
2623 with = "double_option",
2624 skip_serializing_if = "Option::is_none"
2625 )]
2626 pub balancerd_external_certificate_spec: PartialField,
2627 #[serde(
2628 default,
2629 with = "double_option",
2630 skip_serializing_if = "Option::is_none"
2631 )]
2632 pub console_external_certificate_spec: PartialField,
2633 #[serde(
2634 default,
2635 with = "double_option",
2636 skip_serializing_if = "Option::is_none"
2637 )]
2638 pub internal_certificate_spec: PartialField,
2639 #[serde(flatten)]
2640 pub extra: serde_json::Map<String, serde_json::Value>,
2641 }
2642
2643 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
2645 #[serde(rename_all = "camelCase")]
2646 pub struct PartialMaterializeStatus {
2647 #[serde(
2648 default,
2649 with = "double_option",
2650 skip_serializing_if = "Option::is_none"
2651 )]
2652 pub resource_id: PartialField,
2653 #[serde(
2654 default,
2655 with = "double_option",
2656 skip_serializing_if = "Option::is_none"
2657 )]
2658 pub active_generation: PartialField,
2659 #[serde(
2660 default,
2661 with = "double_option",
2662 skip_serializing_if = "Option::is_none"
2663 )]
2664 pub last_completed_rollout_environmentd_image_ref: PartialField,
2665 #[serde(
2666 default,
2667 with = "double_option",
2668 skip_serializing_if = "Option::is_none"
2669 )]
2670 pub last_completed_rollout_hash: PartialField,
2671 #[serde(
2672 default,
2673 with = "double_option",
2674 skip_serializing_if = "Option::is_none"
2675 )]
2676 pub requested_rollout_hash: PartialField,
2677 #[serde(
2678 default,
2679 with = "double_option",
2680 skip_serializing_if = "Option::is_none"
2681 )]
2682 pub conditions: PartialField,
2683 #[serde(flatten)]
2684 pub extra: serde_json::Map<String, serde_json::Value>,
2685 }
2686
2687 #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
2689 #[serde(rename_all = "camelCase")]
2690 pub struct PartialMaterialize {
2691 #[serde(skip_serializing_if = "Option::is_none")]
2692 pub api_version: Option<String>,
2693 #[serde(skip_serializing_if = "Option::is_none")]
2694 pub kind: Option<serde_json::Value>,
2695 #[serde(skip_serializing_if = "Option::is_none")]
2696 pub metadata: Option<serde_json::Value>,
2697 #[serde(skip_serializing_if = "Option::is_none")]
2698 pub spec: Option<PartialMaterializeSpec>,
2699 #[serde(skip_serializing_if = "Option::is_none")]
2700 pub status: Option<PartialMaterializeStatus>,
2701 #[serde(flatten)]
2702 pub extra: serde_json::Map<String, serde_json::Value>,
2703 }
2704
2705 impl From<MaterializeSpec> for PartialMaterializeSpec {
2706 fn from(spec: MaterializeSpec) -> Self {
2707 let MaterializeSpec {
2708 environmentd_image_ref,
2709 environmentd_extra_args,
2710 environmentd_extra_env,
2711 environmentd_connection_role_arn,
2712 environmentd_resource_requirements,
2713 environmentd_scratch_volume_storage_requirement,
2714 environmentd_readiness_probe,
2715 environmentd_liveness_probe,
2716 environmentd_startup_probe,
2717 balancerd_resource_requirements,
2718 balancerd_configmap_name,
2719 console_resource_requirements,
2720 balancerd_replicas,
2721 balancerd_externally_scaled,
2722 console_replicas,
2723 service_account_name,
2724 service_account_annotations,
2725 service_account_labels,
2726 pod_annotations,
2727 pod_labels,
2728 force_promote,
2729 force_rollout,
2730 rollout_strategy,
2731 rollout_request_timeout,
2732 backend_secret_name,
2733 authenticator_kind,
2734 enable_rbac,
2735 environment_id,
2736 system_parameter_configmap_name,
2737 additional_trust_bundle,
2738 balancerd_external_certificate_spec,
2739 console_external_certificate_spec,
2740 internal_certificate_spec,
2741 } = spec;
2742 Self {
2743 environmentd_image_ref: present(environmentd_image_ref),
2744 environmentd_extra_args: present_opt(environmentd_extra_args),
2745 environmentd_extra_env: present_opt(environmentd_extra_env),
2746 environmentd_connection_role_arn: present_opt(environmentd_connection_role_arn),
2747 environmentd_resource_requirements: present_opt(environmentd_resource_requirements),
2748 environmentd_scratch_volume_storage_requirement: present_opt(
2749 environmentd_scratch_volume_storage_requirement,
2750 ),
2751 environmentd_readiness_probe: present_opt(environmentd_readiness_probe),
2752 environmentd_liveness_probe: present_opt(environmentd_liveness_probe),
2753 environmentd_startup_probe: present_opt(environmentd_startup_probe),
2754 balancerd_resource_requirements: present_opt(balancerd_resource_requirements),
2755 balancerd_configmap_name: present_opt(balancerd_configmap_name),
2756 console_resource_requirements: present_opt(console_resource_requirements),
2757 balancerd_replicas: present_opt(balancerd_replicas),
2758 balancerd_externally_scaled: present_opt(balancerd_externally_scaled),
2759 console_replicas: present_opt(console_replicas),
2760 service_account_name: present_opt(service_account_name),
2761 service_account_annotations: present_opt(service_account_annotations),
2762 service_account_labels: present_opt(service_account_labels),
2763 pod_annotations: present_opt(pod_annotations),
2764 pod_labels: present_opt(pod_labels),
2765 force_promote: present_opt(force_promote),
2766 force_rollout: present(force_rollout),
2767 rollout_strategy: present(rollout_strategy),
2768 rollout_request_timeout: present(rollout_request_timeout),
2769 backend_secret_name: present(backend_secret_name),
2770 authenticator_kind: present(authenticator_kind),
2771 enable_rbac: present(enable_rbac),
2772 environment_id: present(environment_id),
2773 system_parameter_configmap_name: present_opt(system_parameter_configmap_name),
2774 additional_trust_bundle: present_opt(additional_trust_bundle),
2775 balancerd_external_certificate_spec: present_opt(
2776 balancerd_external_certificate_spec,
2777 ),
2778 console_external_certificate_spec: present_opt(console_external_certificate_spec),
2779 internal_certificate_spec: present_opt(internal_certificate_spec),
2780 extra: serde_json::Map::new(),
2781 }
2782 }
2783 }
2784
2785 impl From<MaterializeStatus> for PartialMaterializeStatus {
2786 fn from(status: MaterializeStatus) -> Self {
2787 let MaterializeStatus {
2788 resource_id,
2789 active_generation,
2790 last_completed_rollout_environmentd_image_ref,
2791 last_completed_rollout_hash,
2792 requested_rollout_hash,
2793 conditions,
2794 } = status;
2795 Self {
2796 resource_id: present(resource_id),
2797 active_generation: present(active_generation),
2798 last_completed_rollout_environmentd_image_ref: present_opt(
2799 last_completed_rollout_environmentd_image_ref,
2800 ),
2801 last_completed_rollout_hash: present_opt(last_completed_rollout_hash),
2802 requested_rollout_hash: present_opt(requested_rollout_hash),
2803 conditions: present(conditions),
2804 extra: serde_json::Map::new(),
2805 }
2806 }
2807 }
2808
2809 impl From<Materialize> for PartialMaterialize {
2810 fn from(mz: Materialize) -> Self {
2811 let Materialize {
2812 metadata,
2813 spec,
2814 status,
2815 } = mz;
2816 Self {
2817 api_version: Some("materialize.cloud/v1".to_owned()),
2818 kind: Some("Materialize".into()),
2819 metadata: Some(
2820 serde_json::to_value(metadata).expect("ObjectMeta serializes to JSON"),
2821 ),
2822 spec: Some(spec.into()),
2823 status: status.map(Into::into),
2824 extra: serde_json::Map::new(),
2825 }
2826 }
2827 }
2828
2829 impl From<super::v1alpha1::PartialMaterializeSpec> for PartialMaterializeSpec {
2830 fn from(spec: super::v1alpha1::PartialMaterializeSpec) -> Self {
2831 let super::v1alpha1::PartialMaterializeSpec {
2832 environmentd_image_ref,
2833 environmentd_extra_args,
2834 environmentd_extra_env,
2835 environmentd_iam_role_arn,
2836 environmentd_connection_role_arn,
2837 environmentd_resource_requirements,
2838 environmentd_scratch_volume_storage_requirement,
2839 environmentd_readiness_probe,
2840 environmentd_liveness_probe,
2841 environmentd_startup_probe,
2842 balancerd_resource_requirements,
2843 balancerd_configmap_name,
2844 console_resource_requirements,
2845 balancerd_replicas,
2846 balancerd_externally_scaled,
2847 console_replicas,
2848 service_account_name,
2849 service_account_annotations,
2850 service_account_labels,
2851 pod_annotations,
2852 pod_labels,
2853 request_rollout: _,
2854 force_promote,
2855 force_rollout,
2856 in_place_rollout: _,
2857 rollout_strategy,
2858 rollout_request_timeout,
2859 backend_secret_name,
2860 authenticator_kind,
2861 enable_rbac,
2862 environment_id,
2863 system_parameter_configmap_name,
2864 additional_trust_bundle,
2865 balancerd_external_certificate_spec,
2866 console_external_certificate_spec,
2867 internal_certificate_spec,
2868 extra,
2869 } = spec;
2870 let service_account_annotations = merge_environmentd_iam_role_arn(
2871 service_account_annotations,
2872 environmentd_iam_role_arn,
2873 );
2874 let force_promote = match force_promote {
2877 Some(Some(value)) if value == "" || value == NIL_UUID_STR => None,
2878 other => other,
2879 };
2880 Self {
2881 environmentd_image_ref,
2882 environmentd_extra_args,
2883 environmentd_extra_env,
2884 environmentd_connection_role_arn,
2885 environmentd_resource_requirements,
2886 environmentd_scratch_volume_storage_requirement,
2887 environmentd_readiness_probe,
2888 environmentd_liveness_probe,
2889 environmentd_startup_probe,
2890 balancerd_resource_requirements,
2891 balancerd_configmap_name,
2892 console_resource_requirements,
2893 balancerd_replicas,
2894 balancerd_externally_scaled,
2895 console_replicas,
2896 service_account_name,
2897 service_account_annotations,
2898 service_account_labels,
2899 pod_annotations,
2900 pod_labels,
2901 force_promote,
2902 force_rollout,
2903 rollout_strategy,
2904 rollout_request_timeout,
2905 backend_secret_name,
2906 authenticator_kind,
2907 enable_rbac,
2908 environment_id,
2909 system_parameter_configmap_name,
2910 additional_trust_bundle,
2911 balancerd_external_certificate_spec,
2912 console_external_certificate_spec,
2913 internal_certificate_spec,
2914 extra,
2915 }
2916 }
2917 }
2918
2919 impl From<super::v1alpha1::PartialMaterializeStatus> for PartialMaterializeStatus {
2920 fn from(status: super::v1alpha1::PartialMaterializeStatus) -> Self {
2921 let super::v1alpha1::PartialMaterializeStatus {
2922 resource_id,
2923 active_generation,
2924 last_completed_rollout_request: _,
2925 last_completed_rollout_environmentd_image_ref,
2926 resources_hash: _,
2927 last_completed_rollout_hash,
2928 conditions,
2929 extra,
2930 } = status;
2931 Self {
2932 resource_id,
2933 active_generation,
2934 last_completed_rollout_environmentd_image_ref,
2935 last_completed_rollout_hash,
2936 requested_rollout_hash: None,
2941 conditions,
2942 extra,
2943 }
2944 }
2945 }
2946
2947 impl From<super::v1alpha1::PartialMaterialize> for PartialMaterialize {
2948 fn from(mz: super::v1alpha1::PartialMaterialize) -> Self {
2949 let super::v1alpha1::PartialMaterialize {
2950 api_version: _,
2951 kind,
2952 metadata,
2953 spec,
2954 status,
2955 extra,
2956 } = mz;
2957 Self {
2958 api_version: Some("materialize.cloud/v1".to_owned()),
2959 kind,
2960 metadata,
2961 spec: spec.map(Into::into),
2962 status: status.map(Into::into),
2963 extra,
2964 }
2965 }
2966 }
2967}
2968
2969const NIL_UUID_STR: &str = "00000000-0000-0000-0000-000000000000";
2971
2972pub type PartialField = Option<Option<serde_json::Value>>;
2981
2982mod double_option {
2986 use serde::{Deserialize, Deserializer, Serialize, Serializer};
2987
2988 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
2989 where
2990 T: Deserialize<'de>,
2991 D: Deserializer<'de>,
2992 {
2993 Option::<T>::deserialize(deserializer).map(Some)
2994 }
2995
2996 pub fn serialize<T, S>(value: &Option<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
2997 where
2998 T: Serialize,
2999 S: Serializer,
3000 {
3001 match value {
3002 Some(inner) => inner.serialize(serializer),
3003 None => serializer.serialize_none(),
3005 }
3006 }
3007}
3008
3009fn present<T: Serialize>(value: T) -> PartialField {
3012 Some(Some(
3013 serde_json::to_value(value).expect("CRD field serializes to JSON"),
3014 ))
3015}
3016
3017fn present_opt<T: Serialize>(value: Option<T>) -> PartialField {
3019 value.map(|value| Some(serde_json::to_value(value).expect("CRD field serializes to JSON")))
3020}
3021
3022fn merge_environmentd_iam_role_arn(
3027 annotations: PartialField,
3028 role_arn: PartialField,
3029) -> PartialField {
3030 let Some(Some(role_arn)) = role_arn else {
3031 return annotations;
3032 };
3033 let mut map = match annotations {
3034 Some(Some(serde_json::Value::Object(map))) => map,
3035 Some(Some(other)) => return Some(Some(other)),
3036 Some(None) | None => serde_json::Map::new(),
3037 };
3038 map.entry("eks.amazonaws.com/role-arn").or_insert(role_arn);
3039 Some(Some(serde_json::Value::Object(map)))
3040}
3041
3042pub fn convert_v1alpha1_to_v1(
3061 value: serde_json::Value,
3062) -> Result<serde_json::Value, anyhow::Error> {
3063 let complete = serde_json::from_value::<v1alpha1::Materialize>(value.clone()).ok();
3064 let partial: v1alpha1::PartialMaterialize = serde_json::from_value(value)?;
3065 let mut converted = v1::PartialMaterialize::from(partial);
3066 if let Some(complete) = complete {
3067 let typed = v1::Materialize::from(complete);
3068 if let (Some(status), Some(typed_status)) = (converted.status.as_mut(), typed.status) {
3069 status.requested_rollout_hash = present_opt(typed_status.requested_rollout_hash);
3070 status.last_completed_rollout_hash =
3071 present_opt(typed_status.last_completed_rollout_hash);
3072 }
3073 }
3074 Ok(serde_json::to_value(converted)?)
3075}
3076
3077pub fn convert_v1_to_v1alpha1(
3088 value: serde_json::Value,
3089) -> Result<serde_json::Value, anyhow::Error> {
3090 let complete = serde_json::from_value::<v1::Materialize>(value.clone()).ok();
3091 let partial: v1::PartialMaterialize = serde_json::from_value(value)?;
3092 let mut converted = v1alpha1::PartialMaterialize::from(partial);
3093 if let Some(complete) = complete {
3094 let typed = v1alpha1::Materialize::from(complete);
3095 if let Some(spec) = converted.spec.as_mut() {
3096 spec.request_rollout = present(typed.spec.request_rollout);
3097 }
3098 if let (Some(status), Some(typed_status)) = (converted.status.as_mut(), typed.status) {
3099 status.last_completed_rollout_request =
3100 present(typed_status.last_completed_rollout_request);
3101 status.resources_hash = present(typed_status.resources_hash);
3102 }
3103 }
3104 Ok(serde_json::to_value(converted)?)
3105}
3106
3107fn parse_image_ref(image_ref: &str) -> Option<Version> {
3108 image_ref
3109 .rsplit_once(':')
3110 .and_then(|(_repo, tag)| tag.strip_prefix('v'))
3111 .and_then(|tag| {
3112 let tag = tag.replace("--", "+");
3117 Version::parse(&tag).ok()
3118 })
3119}
3120
3121#[cfg(test)]
3122mod tests {
3123 use std::time::Duration;
3124
3125 use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, Time};
3126 use k8s_openapi::jiff::Timestamp;
3127 use kube::core::ObjectMeta;
3128 use semver::Version;
3129
3130 use super::v1alpha1::{Materialize, MaterializeSpec, MaterializeStatus};
3131 use super::{
3132 AdditionalTrustBundle, DEFAULT_ROLLOUT_REQUEST_TIMEOUT, FORCE_ROLLOUT_ANNOTATION,
3133 InitialStatusAnnotations, LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION,
3134 LAST_KNOWN_RESOURCE_ID_ANNOTATION, RolloutRequestTimeout, TrustBundleKeyRef,
3135 TrustBundleSource,
3136 };
3137
3138 #[mz_ore::test]
3139 fn initial_status_from_annotations() {
3140 let mz = |annotations: &[(&str, &str)]| Materialize {
3141 spec: MaterializeSpec {
3142 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3143 ..Default::default()
3144 },
3145 metadata: ObjectMeta {
3146 annotations: Some(
3147 annotations
3148 .iter()
3149 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
3150 .collect(),
3151 ),
3152 ..Default::default()
3153 },
3154 status: None,
3155 };
3156
3157 let status = mz(&[]).status();
3160 assert!(crate::crd::is_valid_resource_id(&status.resource_id));
3161 assert_eq!(status.active_generation, 0);
3162
3163 let restored = mz(&[
3165 (LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION, "3"),
3166 (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "abcde01234"),
3167 ]);
3168 InitialStatusAnnotations::parse(restored.metadata.annotations.as_ref().unwrap()).unwrap();
3169 let status = restored.status();
3170 assert_eq!(status.resource_id, "abcde01234");
3171 assert_eq!(status.active_generation, 3);
3172
3173 let status = super::v1::Materialize {
3175 spec: Default::default(),
3176 metadata: restored.metadata.clone(),
3177 status: None,
3178 }
3179 .status();
3180 assert_eq!(status.resource_id, "abcde01234");
3181 assert_eq!(status.active_generation, 3);
3182
3183 let mut existing = restored.clone();
3185 existing.status = Some(MaterializeStatus {
3186 resource_id: "zzzzz99999".to_owned(),
3187 active_generation: 7,
3188 ..Default::default()
3189 });
3190 let status = existing.status();
3191 assert_eq!(status.resource_id, "zzzzz99999");
3192 assert_eq!(status.active_generation, 7);
3193
3194 for (annotation, value) in [
3196 (LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION, "two"),
3197 (LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION, "-1"),
3198 (LAST_KNOWN_RESOURCE_ID_ANNOTATION, ""),
3199 (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "short"),
3200 (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "ABCDE01234"),
3201 (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "abcde-1234"),
3202 (LAST_KNOWN_RESOURCE_ID_ANNOTATION, "abcde012345"),
3203 ] {
3204 let invalid = mz(&[(annotation, value)]);
3205 let err =
3206 InitialStatusAnnotations::parse(invalid.metadata.annotations.as_ref().unwrap())
3207 .unwrap_err();
3208 assert!(err.to_string().contains(annotation), "{err}");
3209 let status = invalid.status();
3210 assert!(crate::crd::is_valid_resource_id(&status.resource_id));
3211 assert_ne!(status.resource_id, value);
3212 assert_eq!(status.active_generation, 0);
3213 }
3214 }
3215
3216 #[mz_ore::test]
3217 #[cfg_attr(miri, ignore)] fn force_rollout_annotation_forces_new_generation() {
3219 let mut mz = super::v1::Materialize {
3225 spec: super::v1::MaterializeSpec {
3226 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3227 ..Default::default()
3228 },
3229 metadata: ObjectMeta::default(),
3230 status: None,
3231 };
3232 let hash_without_annotation = mz.generate_rollout_hash();
3233 let force_without_annotation = Materialize::from(mz.clone()).force_rollout_value();
3234
3235 mz.metadata.annotations = Some(std::collections::BTreeMap::from_iter([(
3236 FORCE_ROLLOUT_ANNOTATION.to_owned(),
3237 "a4b56cbb-a13e-4f95-8a9d-425c9ba28576".to_owned(),
3238 )]));
3239 assert_ne!(mz.generate_rollout_hash(), hash_without_annotation);
3240 assert_ne!(
3241 Materialize::from(mz.clone()).force_rollout_value(),
3242 force_without_annotation
3243 );
3244
3245 let hash = mz.generate_rollout_hash();
3247 let force = Materialize::from(mz.clone()).force_rollout_value();
3248 mz.metadata.annotations.as_mut().unwrap().insert(
3249 FORCE_ROLLOUT_ANNOTATION.to_owned(),
3250 "3f61bf8d-0714-462c-8b3b-3d9a68d0bcba".to_owned(),
3251 );
3252 assert_ne!(mz.generate_rollout_hash(), hash);
3253 assert_ne!(Materialize::from(mz.clone()).force_rollout_value(), force);
3254 }
3255
3256 #[mz_ore::test]
3257 #[cfg_attr(miri, ignore)]
3258 fn balancerd_configmap_reference_preserves_rollout_hash_and_conversion() {
3259 let mut mz = super::v1::Materialize {
3260 spec: super::v1::MaterializeSpec {
3261 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3262 ..Default::default()
3263 },
3264 metadata: ObjectMeta::default(),
3265 status: None,
3266 };
3267 let hash = mz.generate_rollout_hash();
3268 assert!(
3270 serde_json::to_value(&mz.spec)
3271 .unwrap()
3272 .get("balancerdConfigmapName")
3273 .is_none()
3274 );
3275 mz.spec.balancerd_configmap_name = Some("balancerd-settings".to_owned());
3276 assert_eq!(mz.generate_rollout_hash(), hash);
3277 let alpha = Materialize::from(mz.clone());
3278 assert_eq!(
3279 alpha.spec.balancerd_configmap_name,
3280 mz.spec.balancerd_configmap_name
3281 );
3282 assert_eq!(
3283 super::v1::Materialize::from(alpha)
3284 .spec
3285 .balancerd_configmap_name,
3286 mz.spec.balancerd_configmap_name,
3287 );
3288 for value in [
3289 serde_json::json!("balancerd-settings"),
3290 serde_json::Value::Null,
3291 ] {
3292 let subset = serde_json::json!({
3293 "apiVersion": "materialize.cloud/v1alpha1",
3294 "kind": "Materialize",
3295 "metadata": {"name": "mz"},
3296 "spec": {"balancerdConfigmapName": value},
3297 });
3298 let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3299 assert_eq!(v1["spec"]["balancerdConfigmapName"], value);
3300 let roundtrip = super::convert_v1_to_v1alpha1(v1).unwrap();
3301 assert_eq!(roundtrip, subset);
3302 }
3303 }
3304
3305 #[mz_ore::test]
3306 #[cfg_attr(miri, ignore)]
3307 fn balancerd_externally_scaled_preserves_rollout_hash_and_conversion() {
3308 let mut mz = super::v1::Materialize {
3309 spec: super::v1::MaterializeSpec {
3310 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3311 ..Default::default()
3312 },
3313 metadata: ObjectMeta::default(),
3314 status: None,
3315 };
3316 let hash = mz.generate_rollout_hash();
3317 assert!(
3319 serde_json::to_value(&mz.spec)
3320 .unwrap()
3321 .get("balancerdExternallyScaled")
3322 .is_none()
3323 );
3324 mz.spec.balancerd_externally_scaled = Some(true);
3325 assert_eq!(mz.generate_rollout_hash(), hash);
3326 let alpha = Materialize::from(mz.clone());
3327 assert_eq!(alpha.spec.balancerd_externally_scaled, Some(true));
3328 assert_eq!(
3329 super::v1::Materialize::from(alpha)
3330 .spec
3331 .balancerd_externally_scaled,
3332 Some(true),
3333 );
3334 for value in [serde_json::json!(true), serde_json::Value::Null] {
3335 let subset = serde_json::json!({
3336 "apiVersion": "materialize.cloud/v1alpha1",
3337 "kind": "Materialize",
3338 "metadata": {"name": "mz"},
3339 "spec": {"balancerdExternallyScaled": value},
3340 });
3341 let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3342 assert_eq!(v1["spec"]["balancerdExternallyScaled"], value);
3343 let roundtrip = super::convert_v1_to_v1alpha1(v1).unwrap();
3344 assert_eq!(roundtrip, subset);
3345 }
3346 }
3347
3348 #[mz_ore::test]
3349 #[cfg_attr(miri, ignore)]
3350 fn environmentd_probes_trigger_rollout_and_survive_conversion() {
3351 let mut mz = super::v1::Materialize {
3352 spec: super::v1::MaterializeSpec {
3353 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3354 ..Default::default()
3355 },
3356 metadata: ObjectMeta::default(),
3357 status: None,
3358 };
3359 let hash = mz.generate_rollout_hash();
3360 let spec = serde_json::to_value(&mz.spec).unwrap();
3362 assert!(spec.get("environmentdReadinessProbe").is_none());
3363 assert!(spec.get("environmentdLivenessProbe").is_none());
3364 assert!(spec.get("environmentdStartupProbe").is_none());
3365
3366 let probe = k8s_openapi::api::core::v1::Probe {
3367 failure_threshold: Some(60),
3368 ..Default::default()
3369 };
3370 mz.spec.environmentd_readiness_probe = Some(probe.clone());
3371 let readiness_hash = mz.generate_rollout_hash();
3372 assert_ne!(readiness_hash, hash);
3373 mz.spec.environmentd_liveness_probe = Some(probe.clone());
3374 let liveness_hash = mz.generate_rollout_hash();
3375 assert_ne!(liveness_hash, readiness_hash);
3376 mz.spec.environmentd_startup_probe = Some(probe);
3377 assert_ne!(mz.generate_rollout_hash(), liveness_hash);
3378
3379 let alpha = Materialize::from(mz.clone());
3380 assert_eq!(
3381 alpha.spec.environmentd_readiness_probe,
3382 mz.spec.environmentd_readiness_probe
3383 );
3384 assert_eq!(
3385 alpha.spec.environmentd_liveness_probe,
3386 mz.spec.environmentd_liveness_probe
3387 );
3388 assert_eq!(
3389 alpha.spec.environmentd_startup_probe,
3390 mz.spec.environmentd_startup_probe
3391 );
3392 let v1 = super::v1::Materialize::from(alpha);
3393 assert_eq!(
3394 v1.spec.environmentd_readiness_probe,
3395 mz.spec.environmentd_readiness_probe
3396 );
3397 assert_eq!(
3398 v1.spec.environmentd_liveness_probe,
3399 mz.spec.environmentd_liveness_probe
3400 );
3401 assert_eq!(
3402 v1.spec.environmentd_startup_probe,
3403 mz.spec.environmentd_startup_probe
3404 );
3405
3406 let subset = serde_json::json!({
3407 "apiVersion": "materialize.cloud/v1alpha1",
3408 "kind": "Materialize",
3409 "metadata": {"name": "mz"},
3410 "spec": {
3411 "environmentdReadinessProbe": {"periodSeconds": 5},
3412 "environmentdLivenessProbe": null,
3413 "environmentdStartupProbe": {"failureThreshold": 360},
3414 },
3415 });
3416 let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3417 assert_eq!(v1["spec"], subset["spec"]);
3418 assert_eq!(super::convert_v1_to_v1alpha1(v1).unwrap(), subset);
3419 }
3420
3421 #[mz_ore::test]
3422 #[cfg_attr(miri, ignore)]
3423 fn additional_trust_bundle_triggers_rollout_and_survives_conversion() {
3424 let mut mz = super::v1::Materialize {
3425 spec: super::v1::MaterializeSpec {
3426 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3427 ..Default::default()
3428 },
3429 metadata: ObjectMeta::default(),
3430 status: None,
3431 };
3432 let hash = mz.generate_rollout_hash();
3433 assert!(
3435 serde_json::to_value(&mz.spec)
3436 .unwrap()
3437 .get("additionalTrustBundle")
3438 .is_none()
3439 );
3440
3441 mz.spec.additional_trust_bundle = Some(AdditionalTrustBundle {
3442 config_map_key_ref: Some(TrustBundleKeyRef {
3443 name: "private-ca".to_owned(),
3444 key: "ca.crt".to_owned(),
3445 }),
3446 secret_key_ref: None,
3447 });
3448 assert_ne!(mz.generate_rollout_hash(), hash);
3449
3450 let alpha = Materialize::from(mz.clone());
3451 assert_eq!(
3452 alpha.spec.additional_trust_bundle,
3453 mz.spec.additional_trust_bundle
3454 );
3455 assert_eq!(
3456 super::v1::Materialize::from(alpha)
3457 .spec
3458 .additional_trust_bundle,
3459 mz.spec.additional_trust_bundle
3460 );
3461
3462 let key_ref = TrustBundleKeyRef {
3463 name: "private-ca".to_owned(),
3464 key: "ca.crt".to_owned(),
3465 };
3466 let both = AdditionalTrustBundle {
3467 config_map_key_ref: Some(key_ref.clone()),
3468 secret_key_ref: Some(key_ref.clone()),
3469 };
3470 assert!(both.source().is_err(), "both refs set must be rejected");
3471 let neither = AdditionalTrustBundle {
3472 config_map_key_ref: None,
3473 secret_key_ref: None,
3474 };
3475 assert!(neither.source().is_err(), "no ref set must be rejected");
3476 let secret = AdditionalTrustBundle {
3477 config_map_key_ref: None,
3478 secret_key_ref: Some(key_ref.clone()),
3479 };
3480 assert_eq!(
3481 secret.source().unwrap(),
3482 TrustBundleSource::Secret(&key_ref)
3483 );
3484
3485 for value in [
3486 serde_json::json!({"secretKeyRef": {"name": "private-ca", "key": "ca.crt"}}),
3487 serde_json::Value::Null,
3488 ] {
3489 let subset = serde_json::json!({
3490 "apiVersion": "materialize.cloud/v1alpha1",
3491 "kind": "Materialize",
3492 "metadata": {"name": "mz"},
3493 "spec": {"additionalTrustBundle": value},
3494 });
3495 let v1 = super::convert_v1alpha1_to_v1(subset.clone()).unwrap();
3496 assert_eq!(v1["spec"]["additionalTrustBundle"], value);
3497 assert_eq!(super::convert_v1_to_v1alpha1(v1).unwrap(), subset);
3498 }
3499 }
3500
3501 #[mz_ore::test]
3502 fn meets_minimum_version() {
3503 let mut mz = Materialize {
3504 spec: MaterializeSpec {
3505 environmentd_image_ref:
3506 "materialize/environmentd:devel-47116c24b8d0df33d3f60a9ee476aa8d7bce5953"
3507 .to_owned(),
3508 ..Default::default()
3509 },
3510 metadata: ObjectMeta {
3511 ..Default::default()
3512 },
3513 status: None,
3514 };
3515
3516 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3518 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
3519 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3520 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.35.0".to_owned();
3521 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3522 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.3".to_owned();
3523 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3524 mz.spec.environmentd_image_ref = "materialize/environmentd@41af286dc0b172ed2f1ca934fd2278de4a1192302ffa07087cea2682e7d372e3".to_owned();
3525 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3526 mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.34.3".to_owned();
3527 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3528 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.asdf.0".to_owned();
3529 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3530 mz.spec.environmentd_image_ref =
3531 "materialize/environmentd:v0.146.0-dev.0--pr.g5a05a9e4ba873be8adaa528644aaae6e4c7cd29b"
3532 .to_owned();
3533 assert!(mz.meets_minimum_version(&Version::parse("0.146.0-dev.0").unwrap()));
3534
3535 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0-dev".to_owned();
3537 assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3538 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.33.0".to_owned();
3539 assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3540 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
3541 assert!(!mz.meets_minimum_version(&Version::parse("1.0.0").unwrap()));
3542 mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.33.3".to_owned();
3543 assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
3544 }
3545
3546 #[mz_ore::test]
3547 fn within_upgrade_window() {
3548 let mut mz = Materialize {
3549 spec: MaterializeSpec {
3550 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3551 ..Default::default()
3552 },
3553 metadata: ObjectMeta {
3554 ..Default::default()
3555 },
3556 status: Some(MaterializeStatus {
3557 last_completed_rollout_environmentd_image_ref: Some(
3558 "materialize/environmentd:v26.0.0".to_owned(),
3559 ),
3560 ..Default::default()
3561 }),
3562 };
3563
3564 mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.3".to_owned();
3566 assert!(mz.within_upgrade_window());
3567
3568 mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.8-dev.0".to_owned();
3570 assert!(mz.within_upgrade_window());
3571
3572 mz.spec.environmentd_image_ref = "materialize/environmentd:v28.0.1".to_owned();
3574 assert!(!mz.within_upgrade_window());
3575
3576 mz.spec.environmentd_image_ref =
3578 "materialize/environmentd:v28.0.1.not_a_valid_version".to_owned();
3579 assert!(mz.within_upgrade_window());
3580
3581 mz.status
3583 .as_mut()
3584 .unwrap()
3585 .last_completed_rollout_environmentd_image_ref =
3586 Some("materialize/environmentd:v0.147.20".to_owned());
3587 mz.spec.environmentd_image_ref = "materialize/environmentd:v26.1.0".to_owned();
3588 assert!(mz.within_upgrade_window());
3589
3590 mz.status
3592 .as_mut()
3593 .unwrap()
3594 .last_completed_rollout_environmentd_image_ref =
3595 Some("materialize/environmentd:v26.11.0-dev.0+b".to_owned());
3596 mz.spec.environmentd_image_ref = "materialize/environmentd:v26.11.0-dev.0+a".to_owned();
3597 assert!(mz.within_upgrade_window());
3598 }
3599
3600 #[mz_ore::test]
3601 fn is_valid_upgrade_version() {
3602 let success_tests = [
3603 (Version::new(0, 83, 0), Version::new(0, 83, 0)),
3604 (Version::new(0, 83, 0), Version::new(0, 84, 0)),
3605 (Version::new(0, 9, 0), Version::new(0, 10, 0)),
3606 (Version::new(0, 99, 0), Version::new(0, 100, 0)),
3607 (Version::new(0, 83, 0), Version::new(0, 83, 1)),
3608 (Version::new(0, 83, 0), Version::new(0, 83, 2)),
3609 (Version::new(0, 83, 2), Version::new(0, 83, 10)),
3610 (Version::new(0, 147, 20), Version::new(26, 0, 0)),
3612 (Version::new(0, 164, 0), Version::new(26, 0, 0)),
3613 (Version::new(26, 0, 0), Version::new(26, 1, 0)),
3614 (Version::new(26, 5, 3), Version::new(26, 10, 0)),
3615 (Version::new(0, 130, 0), Version::new(0, 147, 0)),
3616 ];
3617 for (active_version, next_version) in success_tests {
3618 assert!(
3619 Materialize::is_valid_upgrade_version(&active_version, &next_version),
3620 "v{active_version} can upgrade to v{next_version}"
3621 );
3622 }
3623
3624 let failure_tests = [
3625 (Version::new(0, 83, 0), Version::new(0, 82, 0)),
3626 (Version::new(0, 83, 3), Version::new(0, 83, 2)),
3627 (Version::new(0, 83, 3), Version::new(1, 83, 3)),
3628 (Version::new(0, 83, 0), Version::new(0, 85, 0)),
3629 (Version::new(26, 0, 0), Version::new(28, 0, 0)),
3630 (Version::new(0, 130, 0), Version::new(26, 1, 0)),
3631 (Version::new(0, 147, 1), Version::new(26, 0, 0)),
3633 (Version::new(0, 148, 0), Version::new(26, 0, 0)),
3635 ];
3636 for (active_version, next_version) in failure_tests {
3637 assert!(
3638 !Materialize::is_valid_upgrade_version(&active_version, &next_version),
3639 "v{active_version} can't upgrade to v{next_version}"
3640 );
3641 }
3642 }
3643
3644 #[mz_ore::test]
3645 fn rollout_request_timeout() {
3646 let mz_with = |timeout: &str| Materialize {
3647 spec: MaterializeSpec {
3648 rollout_request_timeout: RolloutRequestTimeout(timeout.to_owned()),
3649 ..Default::default()
3650 },
3651 metadata: ObjectMeta::default(),
3652 status: None,
3653 };
3654
3655 let default = humantime::parse_duration(DEFAULT_ROLLOUT_REQUEST_TIMEOUT).unwrap();
3657 assert_eq!(default, Duration::from_secs(24 * 60 * 60));
3658
3659 assert_eq!(
3662 RolloutRequestTimeout::default().0,
3663 DEFAULT_ROLLOUT_REQUEST_TIMEOUT
3664 );
3665 assert_eq!(
3666 Materialize {
3667 spec: MaterializeSpec::default(),
3668 metadata: ObjectMeta::default(),
3669 status: None,
3670 }
3671 .rollout_request_timeout(),
3672 default
3673 );
3674
3675 assert_eq!(
3677 mz_with("1h").rollout_request_timeout(),
3678 Duration::from_secs(60 * 60)
3679 );
3680 assert_eq!(
3681 mz_with("90m").rollout_request_timeout(),
3682 Duration::from_secs(90 * 60)
3683 );
3684 assert_eq!(
3685 mz_with("1h 30m").rollout_request_timeout(),
3686 Duration::from_secs(90 * 60)
3687 );
3688 assert_eq!(mz_with("not a duration").rollout_request_timeout(), default);
3690 }
3691
3692 #[mz_ore::test]
3693 fn rollout_request_timeout_schema_default() {
3694 let crd = serde_json::to_value(<Materialize as kube::CustomResourceExt>::crd())
3698 .expect("CRD serializes");
3699 let default = &crd["spec"]["versions"][0]["schema"]["openAPIV3Schema"]["properties"]["spec"]
3700 ["properties"]["rolloutRequestTimeout"]["default"];
3701 assert_eq!(
3702 default,
3703 &serde_json::json!(DEFAULT_ROLLOUT_REQUEST_TIMEOUT),
3704 "rolloutRequestTimeout schema default missing/wrong in generated CRD",
3705 );
3706 }
3707
3708 #[mz_ore::test]
3709 fn rollout_in_progress_since() {
3710 let now = Timestamp::now();
3711 let condition = |type_: &str, status: &str| Condition {
3712 type_: type_.to_owned(),
3713 status: status.to_owned(),
3714 last_transition_time: Time(now),
3715 message: String::new(),
3716 observed_generation: None,
3717 reason: "Test".to_owned(),
3718 };
3719 let mz_with = |conditions: Vec<Condition>| Materialize {
3720 spec: MaterializeSpec::default(),
3721 metadata: ObjectMeta::default(),
3722 status: Some(MaterializeStatus {
3723 conditions,
3724 ..Default::default()
3725 }),
3726 };
3727
3728 let mz = Materialize {
3730 spec: MaterializeSpec::default(),
3731 metadata: ObjectMeta::default(),
3732 status: None,
3733 };
3734 assert_eq!(mz.rollout_in_progress_since(), None);
3735
3736 assert_eq!(
3739 mz_with(vec![condition("UpToDate", "Unknown")]).rollout_in_progress_since(),
3740 Some(now)
3741 );
3742
3743 assert_eq!(
3747 mz_with(vec![Condition {
3748 reason: "Promoting".to_owned(),
3749 ..condition("UpToDate", "Unknown")
3750 }])
3751 .rollout_in_progress_since(),
3752 None
3753 );
3754
3755 assert_eq!(
3757 mz_with(vec![condition("UpToDate", "True")]).rollout_in_progress_since(),
3758 None
3759 );
3760 assert_eq!(
3761 mz_with(vec![condition("UpToDate", "False")]).rollout_in_progress_since(),
3762 None
3763 );
3764 }
3765
3766 #[mz_ore::test]
3767 fn up_to_date_transition_time() {
3768 let stored = Timestamp::from_second(1_000).unwrap();
3771 let now = Timestamp::from_second(2_000).unwrap();
3772
3773 let condition = |status: &str| Condition {
3774 type_: "UpToDate".to_owned(),
3775 status: status.to_owned(),
3776 last_transition_time: Time(stored),
3777 message: String::new(),
3778 observed_generation: None,
3779 reason: "Test".to_owned(),
3780 };
3781 let mz_with = |conditions: Vec<Condition>| Materialize {
3782 spec: MaterializeSpec::default(),
3783 metadata: ObjectMeta::default(),
3784 status: Some(MaterializeStatus {
3785 conditions,
3786 ..Default::default()
3787 }),
3788 };
3789
3790 let mz = Materialize {
3792 spec: MaterializeSpec::default(),
3793 metadata: ObjectMeta::default(),
3794 status: None,
3795 };
3796 assert_eq!(mz.up_to_date_transition_time("Unknown", now), now);
3797
3798 assert_eq!(
3802 mz_with(vec![condition("Unknown")]).up_to_date_transition_time("Unknown", now),
3803 stored
3804 );
3805
3806 assert_eq!(
3808 mz_with(vec![condition("Unknown")]).up_to_date_transition_time("True", now),
3809 now
3810 );
3811 }
3812
3813 #[mz_ore::test]
3814 fn active_environmentd_image_ref() {
3815 const OLD: &str = "materialize/environmentd:v26.0.0";
3816 const NEW: &str = "materialize/environmentd:v27.0.0";
3817
3818 let mz_with = |spec_image: &str, status: Option<MaterializeStatus>| Materialize {
3819 spec: MaterializeSpec {
3820 environmentd_image_ref: spec_image.to_owned(),
3821 ..Default::default()
3822 },
3823 metadata: ObjectMeta::default(),
3824 status,
3825 };
3826
3827 let mz = mz_with(NEW, None);
3829 assert_eq!(mz.active_environmentd_image_ref(), NEW);
3830
3831 let mz = mz_with(
3835 NEW,
3836 Some(MaterializeStatus {
3837 last_completed_rollout_environmentd_image_ref: None,
3838 ..Default::default()
3839 }),
3840 );
3841 assert_eq!(mz.active_environmentd_image_ref(), NEW);
3842
3843 let mz = mz_with(
3846 NEW,
3847 Some(MaterializeStatus {
3848 last_completed_rollout_environmentd_image_ref: Some(NEW.to_owned()),
3849 ..Default::default()
3850 }),
3851 );
3852 assert_eq!(mz.active_environmentd_image_ref(), NEW);
3853
3854 let mz = mz_with(
3863 NEW,
3864 Some(MaterializeStatus {
3865 last_completed_rollout_environmentd_image_ref: Some(OLD.to_owned()),
3866 ..Default::default()
3867 }),
3868 );
3869 assert_eq!(mz.active_environmentd_image_ref(), OLD);
3870 }
3871
3872 #[mz_ore::test]
3876 fn convert_partial_v1alpha1_to_v1() {
3877 let subset = serde_json::json!({
3878 "apiVersion": "materialize.cloud/v1alpha1",
3879 "kind": "Materialize",
3880 "metadata": {"name": "mz", "namespace": "materialize"},
3881 "spec": {
3882 "environmentdIamRoleArn": "arn:aws:iam::123456789012:role/mz",
3883 "requestRollout": "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6",
3884 "inPlaceRollout": false,
3885 "forcePromote": "",
3886 "serviceAccountLabels": {"team": "data"},
3887 },
3888 "status": {
3889 "activeGeneration": 3,
3890 "lastCompletedRolloutRequest": "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6",
3891 "resourcesHash": "abc123",
3892 },
3893 });
3894 let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
3895 assert_eq!(converted["apiVersion"], "materialize.cloud/v1");
3896 assert_eq!(converted["kind"], "Materialize");
3897 assert_eq!(converted["metadata"]["name"], "mz");
3898 let spec = converted["spec"].as_object().unwrap();
3899 assert!(!spec.contains_key("requestRollout"));
3900 assert!(!spec.contains_key("inPlaceRollout"));
3901 assert!(!spec.contains_key("forcePromote"));
3902 assert!(!spec.contains_key("environmentdIamRoleArn"));
3903 assert_eq!(
3904 spec["serviceAccountAnnotations"]["eks.amazonaws.com/role-arn"],
3905 "arn:aws:iam::123456789012:role/mz"
3906 );
3907 assert_eq!(spec["serviceAccountLabels"]["team"], "data");
3908 let status = converted["status"].as_object().unwrap();
3909 assert_eq!(status["activeGeneration"], 3);
3910 assert!(!status.contains_key("lastCompletedRolloutRequest"));
3911 assert!(!status.contains_key("resourcesHash"));
3912 assert!(!status.contains_key("requestedRolloutHash"));
3913
3914 let subset = serde_json::json!({
3916 "apiVersion": "materialize.cloud/v1alpha1",
3917 "kind": "Materialize",
3918 "metadata": {"name": "mz"},
3919 "spec": {"forcePromote": "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6"},
3920 });
3921 let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
3922 assert_eq!(
3923 converted["spec"]["forcePromote"],
3924 "1e6ef7bc-bff2-4bd4-90dc-eda5697bd0e6"
3925 );
3926 }
3927
3928 #[mz_ore::test]
3929 fn convert_partial_v1_to_v1alpha1() {
3930 let subset = serde_json::json!({
3931 "apiVersion": "materialize.cloud/v1",
3932 "kind": "Materialize",
3933 "metadata": {"name": "mz"},
3934 "spec": {"environmentdImageRef": "materialize/environmentd:v26.0.0"},
3935 "status": {"requestedRolloutHash": "abc123", "activeGeneration": 1},
3936 });
3937 let converted = super::convert_v1_to_v1alpha1(subset).unwrap();
3938 assert_eq!(converted["apiVersion"], "materialize.cloud/v1alpha1");
3939 assert_eq!(
3940 converted["spec"]["environmentdImageRef"],
3941 "materialize/environmentd:v26.0.0"
3942 );
3943 let status = converted["status"].as_object().unwrap();
3944 assert_eq!(status["activeGeneration"], 1);
3945 assert!(!status.contains_key("requestedRolloutHash"));
3946 assert!(!status.contains_key("resourcesHash"));
3947 assert!(
3950 !converted["spec"]
3951 .as_object()
3952 .unwrap()
3953 .contains_key("requestRollout")
3954 );
3955 }
3956
3957 #[mz_ore::test]
3958 #[cfg_attr(miri, ignore)] fn convert_full_v1alpha1_to_v1_derives_fields() {
3960 let mz = Materialize {
3961 metadata: ObjectMeta {
3962 name: Some("mz".to_owned()),
3963 namespace: Some("materialize".to_owned()),
3964 ..Default::default()
3965 },
3966 spec: MaterializeSpec {
3967 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
3968 backend_secret_name: "mz-backend".to_owned(),
3969 ..Default::default()
3970 },
3971 status: Some(MaterializeStatus::default()),
3972 };
3973 let value = serde_json::to_value(&mz).unwrap();
3974 let converted = super::convert_v1alpha1_to_v1(value).unwrap();
3975 assert_eq!(converted["apiVersion"], "materialize.cloud/v1");
3976 assert!(converted["status"]["requestedRolloutHash"].is_string());
3979 }
3980
3981 #[mz_ore::test]
3982 fn convert_rejects_non_objects() {
3983 assert!(super::convert_v1alpha1_to_v1(serde_json::json!("not an object")).is_err());
3984 assert!(super::convert_v1_to_v1alpha1(serde_json::json!(42)).is_err());
3985 assert!(
3986 super::convert_v1alpha1_to_v1(serde_json::json!({"spec": "not an object"})).is_err()
3987 );
3988 }
3989
3990 #[mz_ore::test]
3991 fn convert_preserves_null_vs_absent() {
3992 let subset = serde_json::json!({
3993 "apiVersion": "materialize.cloud/v1alpha1",
3994 "kind": "Materialize",
3995 "metadata": {"name": "mz"},
3996 "spec": {
3997 "environmentdExtraArgs": null,
3998 "backendSecretName": "mz-backend",
3999 },
4000 });
4001 let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
4002 let spec = converted["spec"].as_object().unwrap();
4003 assert!(spec.contains_key("environmentdExtraArgs"));
4004 assert!(spec["environmentdExtraArgs"].is_null());
4005 assert!(!spec.contains_key("consoleReplicas"));
4006 }
4007
4008 #[mz_ore::test]
4013 #[cfg_attr(miri, ignore)] fn convert_faithful_output_for_required_field_subsets() {
4015 let subset = serde_json::json!({
4016 "apiVersion": "materialize.cloud/v1alpha1",
4017 "kind": "Materialize",
4018 "metadata": {"name": "mz"},
4019 "spec": {
4020 "environmentdImageRef": "materialize/environmentd:v26.0.0",
4021 "backendSecretName": "mz-backend",
4022 },
4023 });
4024 let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
4025 let spec = converted["spec"].as_object().unwrap();
4026 let mut keys: Vec<_> = spec.keys().cloned().collect();
4027 keys.sort();
4028 assert_eq!(keys, ["backendSecretName", "environmentdImageRef"]);
4029 }
4030
4031 #[mz_ore::test]
4032 fn convert_passes_unknown_fields_through() {
4033 let subset = serde_json::json!({
4034 "apiVersion": "materialize.cloud/v1alpha1",
4035 "kind": "Materialize",
4036 "metadata": {"name": "mz"},
4037 "spec": {"someFutureField": {"a": 1}},
4038 "someTopLevelField": true,
4039 });
4040 let converted = super::convert_v1alpha1_to_v1(subset).unwrap();
4041 assert_eq!(converted["spec"]["someFutureField"]["a"], 1);
4042 assert_eq!(converted["someTopLevelField"], true);
4043 }
4044
4045 #[mz_ore::test]
4046 #[cfg_attr(miri, ignore)] fn convert_full_v1_to_v1alpha1_derives_request_rollout() {
4048 let mz = super::v1::Materialize {
4049 metadata: ObjectMeta {
4050 name: Some("mz".to_owned()),
4051 namespace: Some("materialize".to_owned()),
4052 ..Default::default()
4053 },
4054 spec: super::v1::MaterializeSpec {
4055 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
4056 backend_secret_name: "mz-backend".to_owned(),
4057 ..Default::default()
4058 },
4059 status: Some(super::v1::MaterializeStatus::default()),
4060 };
4061 let expected = Materialize::from(mz.clone()).spec.request_rollout;
4062 let converted = super::convert_v1_to_v1alpha1(serde_json::to_value(&mz).unwrap()).unwrap();
4063 assert_eq!(converted["apiVersion"], "materialize.cloud/v1alpha1");
4064 assert_eq!(
4065 converted["spec"]["requestRollout"],
4066 expected.hyphenated().to_string()
4067 );
4068 let status = converted["status"].as_object().unwrap();
4072 assert!(status["resourcesHash"].is_string());
4073 assert!(status["lastCompletedRolloutRequest"].is_string());
4074 }
4075
4076 #[mz_ore::test]
4081 fn partial_mirror_from_typed_omits_unset_fields() {
4082 let mz = Materialize {
4083 metadata: ObjectMeta::default(),
4084 spec: MaterializeSpec {
4085 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
4086 backend_secret_name: "mz-backend".to_owned(),
4087 ..Default::default()
4088 },
4089 status: None,
4090 };
4091 let value = serde_json::to_value(super::v1alpha1::PartialMaterialize::from(mz)).unwrap();
4092 let spec = value["spec"].as_object().unwrap();
4093 assert!(!spec.contains_key("balancerdReplicas"));
4094 for (key, field_value) in spec {
4095 assert!(!field_value.is_null(), "unexpected null for {key}");
4096 }
4097 assert!(!value.as_object().unwrap().contains_key("status"));
4098 }
4099}