Skip to main content

mz_catalog/durable/objects/
state_update.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! This module contains various representations of a single catalog update and the logic necessary
11//! for converting between representations.
12//!
13//! The general lifecycle of a single update when read from persist is as follows:
14//!
15//!   1. The update is stored in persist as a [`PersistStateUpdate`].
16//!   2. After being read from persist the update is immediately converted into a
17//!      [`StateUpdate<StateUpdateKindJson>`], which models the update as a JSON.
18//!   3. The [`StateUpdateKindJson`] is converted into a protobuf message,
19//!      [`proto::StateUpdateKind`].
20//!   4. The update is then converted into a [`StateUpdate<StateUpdateKind>`], which is a strongly
21//!      typed Rust object.
22//!   5. Finally, the update is converted into an [`Option<memory::objects::StateUpdate>`], and
23//!      `Some` variants are given to the in-memory catalog. The in-memory catalog is only
24//!      interested in a subset of catalog updates which is why the [`Option`] is necessary.
25//!
26//! TLDR: [`PersistStateUpdate`] -> [`StateUpdate<StateUpdateKindJson>`] ->
27//!       [`proto::StateUpdateKind`] -> [`StateUpdate<StateUpdateKind>`] ->
28//!       [`Option<memory::objects::StateUpdate>`]
29//!
30//! The process of writing a catalog update to persist is the exact opposite.
31//!
32//! When running catalog protobuf upgrades/migrations we may need to take a detour and convert the
33//! [`StateUpdateKindJson`] to some `proto::object_v{x}::StateUpdateKind` before applying specific
34//! upgrades to get us to a valid [`proto::StateUpdateKind`].
35
36use std::fmt::Debug;
37use std::sync::LazyLock;
38
39use mz_ore::collections::HashSet;
40use mz_proto::TryFromProtoError;
41use mz_repr::Diff;
42use mz_repr::adt::jsonb::Jsonb;
43use mz_storage_types::StorageDiff;
44use mz_storage_types::sources::SourceData;
45#[cfg(test)]
46use proptest_derive::Arbitrary;
47use tracing::error;
48
49use crate::durable::debug::CollectionType;
50use crate::durable::objects::serialization::{ProtoType, RustType, proto};
51use crate::durable::objects::{DurableType, FenceToken};
52use crate::durable::persist::Timestamp;
53use crate::durable::transaction::TransactionBatch;
54use crate::durable::{DurableCatalogError, Epoch};
55use crate::memory;
56
57/// Trait for objects that can be converted to/from a [`StateUpdateKindJson`].
58pub trait IntoStateUpdateKindJson:
59    Into<StateUpdateKindJson> + PartialEq + Eq + PartialOrd + Ord + Debug + Clone
60{
61    type Error: Debug;
62
63    fn try_from(raw: StateUpdateKindJson) -> Result<Self, Self::Error>;
64}
65impl<
66    T: Into<StateUpdateKindJson>
67        + TryFrom<StateUpdateKindJson>
68        + PartialEq
69        + Eq
70        + PartialOrd
71        + Ord
72        + Debug
73        + Clone,
74> IntoStateUpdateKindJson for T
75where
76    T::Error: Debug,
77{
78    type Error = T::Error;
79
80    fn try_from(raw: StateUpdateKindJson) -> Result<Self, Self::Error> {
81        <T as TryFrom<StateUpdateKindJson>>::try_from(raw)
82    }
83}
84
85/// Trait for objects that can be converted to/from a [`StateUpdateKind`].
86pub(crate) trait TryIntoStateUpdateKind: IntoStateUpdateKindJson {
87    type Error: Debug;
88
89    fn try_into(self) -> Result<StateUpdateKind, <Self as TryIntoStateUpdateKind>::Error>;
90}
91impl<T: IntoStateUpdateKindJson + TryInto<StateUpdateKind>> TryIntoStateUpdateKind for T
92where
93    <T as TryInto<StateUpdateKind>>::Error: Debug,
94{
95    type Error = <T as TryInto<StateUpdateKind>>::Error;
96
97    fn try_into(self) -> Result<StateUpdateKind, <T as TryInto<StateUpdateKind>>::Error> {
98        <T as TryInto<StateUpdateKind>>::try_into(self)
99    }
100}
101
102/// A single update to the catalog state.
103#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
104pub struct StateUpdate<T: IntoStateUpdateKindJson = StateUpdateKind> {
105    /// They kind and contents of the state update.
106    pub kind: T,
107    /// The timestamp at which the update occurred.
108    pub ts: Timestamp,
109    /// Record count difference for the update.
110    pub diff: Diff,
111}
112
113impl StateUpdate {
114    /// Convert a [`TransactionBatch`] to a list of [`StateUpdate`]s at timestamp `ts`.
115    pub(crate) fn from_txn_batch_ts(
116        txn_batch: TransactionBatch,
117        ts: Timestamp,
118    ) -> impl Iterator<Item = StateUpdate> {
119        Self::from_txn_batch(txn_batch).map(move |(kind, diff)| StateUpdate { kind, ts, diff })
120    }
121
122    /// Convert a [`TransactionBatch`] to a list of [`StateUpdate`]s and [`Diff`]s.
123    pub(crate) fn from_txn_batch(
124        txn_batch: TransactionBatch,
125    ) -> impl Iterator<Item = (StateUpdateKind, Diff)> {
126        fn from_batch<K, V>(
127            batch: Vec<(K, V, Diff)>,
128            kind: fn(K, V) -> StateUpdateKind,
129        ) -> impl Iterator<Item = (StateUpdateKind, Diff)> {
130            batch
131                .into_iter()
132                .map(move |(k, v, diff)| (kind(k, v), diff))
133        }
134        let TransactionBatch {
135            databases,
136            schemas,
137            items,
138            item_columns,
139            index_columns,
140            comments,
141            roles,
142            role_auth,
143            clusters,
144            cluster_replicas,
145            network_policies,
146            cluster_replica_sizes,
147            query_policies,
148            introspection_sources,
149            id_allocator,
150            configs,
151            settings,
152            source_references,
153            system_gid_mapping,
154            system_configurations,
155            cluster_system_configurations,
156            replica_system_configurations,
157            default_privileges,
158            system_privileges,
159            storage_collection_metadata,
160            unfinalized_shards,
161            txn_wal_shard,
162            audit_log_updates,
163            upper: _,
164            ..
165        } = txn_batch;
166        let databases = from_batch(databases, StateUpdateKind::Database);
167        let schemas = from_batch(schemas, StateUpdateKind::Schema);
168        let items = from_batch(items, StateUpdateKind::Item);
169        let item_columns = from_batch(item_columns, StateUpdateKind::ItemColumns);
170        let index_columns = from_batch(index_columns, StateUpdateKind::IndexColumns);
171        let comments = from_batch(comments, StateUpdateKind::Comment);
172        let roles = from_batch(roles, StateUpdateKind::Role);
173        let role_auth = from_batch(role_auth, StateUpdateKind::RoleAuth);
174        let clusters = from_batch(clusters, StateUpdateKind::Cluster);
175        let cluster_replicas = from_batch(cluster_replicas, StateUpdateKind::ClusterReplica);
176        let network_policies = from_batch(network_policies, StateUpdateKind::NetworkPolicy);
177        let cluster_replica_sizes =
178            from_batch(cluster_replica_sizes, StateUpdateKind::ClusterReplicaSize);
179        let query_policies = from_batch(query_policies, StateUpdateKind::QueryPolicy);
180        let introspection_sources = from_batch(
181            introspection_sources,
182            StateUpdateKind::IntrospectionSourceIndex,
183        );
184        let id_allocators = from_batch(id_allocator, StateUpdateKind::IdAllocator);
185        let configs = from_batch(configs, StateUpdateKind::Config);
186        let settings = from_batch(settings, StateUpdateKind::Setting);
187        let system_object_mappings =
188            from_batch(system_gid_mapping, StateUpdateKind::SystemObjectMapping);
189        let system_configurations =
190            from_batch(system_configurations, StateUpdateKind::SystemConfiguration);
191        let cluster_system_configurations = from_batch(
192            cluster_system_configurations,
193            StateUpdateKind::ClusterSystemConfiguration,
194        );
195        let replica_system_configurations = from_batch(
196            replica_system_configurations,
197            StateUpdateKind::ReplicaSystemConfiguration,
198        );
199        let default_privileges = from_batch(default_privileges, StateUpdateKind::DefaultPrivilege);
200        let source_references = from_batch(source_references, StateUpdateKind::SourceReferences);
201        let system_privileges = from_batch(system_privileges, StateUpdateKind::SystemPrivilege);
202        let storage_collection_metadata = from_batch(
203            storage_collection_metadata,
204            StateUpdateKind::StorageCollectionMetadata,
205        );
206        let unfinalized_shards = from_batch(unfinalized_shards, StateUpdateKind::UnfinalizedShard);
207        let txn_wal_shard = from_batch(txn_wal_shard, StateUpdateKind::TxnWalShard);
208        let audit_logs = from_batch(audit_log_updates, StateUpdateKind::AuditLog);
209
210        databases
211            .chain(schemas)
212            .chain(items)
213            .chain(item_columns)
214            .chain(index_columns)
215            .chain(comments)
216            .chain(roles)
217            .chain(role_auth)
218            .chain(clusters)
219            .chain(cluster_replicas)
220            .chain(network_policies)
221            .chain(cluster_replica_sizes)
222            .chain(query_policies)
223            .chain(introspection_sources)
224            .chain(id_allocators)
225            .chain(configs)
226            .chain(settings)
227            .chain(source_references)
228            .chain(system_object_mappings)
229            .chain(system_configurations)
230            .chain(cluster_system_configurations)
231            .chain(replica_system_configurations)
232            .chain(default_privileges)
233            .chain(system_privileges)
234            .chain(storage_collection_metadata)
235            .chain(unfinalized_shards)
236            .chain(txn_wal_shard)
237            .chain(audit_logs)
238    }
239}
240
241/// The contents of a single state update.
242///
243/// The entire catalog is serialized as bytes and saved in a single persist shard. We use this
244/// enum to determine what collection something in the catalog belongs to.
245#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
246#[cfg_attr(test, derive(Arbitrary))]
247pub enum StateUpdateKind {
248    AuditLog(proto::AuditLogKey, ()),
249    Cluster(proto::ClusterKey, proto::ClusterValue),
250    ClusterReplica(proto::ClusterReplicaKey, proto::ClusterReplicaValue),
251    ClusterReplicaSize(proto::ClusterReplicaSizeKey, proto::ClusterReplicaSizeValue),
252    Comment(proto::CommentKey, proto::CommentValue),
253    Config(proto::ConfigKey, proto::ConfigValue),
254    Database(proto::DatabaseKey, proto::DatabaseValue),
255    DefaultPrivilege(proto::DefaultPrivilegesKey, proto::DefaultPrivilegesValue),
256    FenceToken(FenceToken),
257    IdAllocator(proto::IdAllocKey, proto::IdAllocValue),
258    IndexColumns(proto::IndexColumnsKey, proto::IndexColumnsValue),
259    IntrospectionSourceIndex(
260        proto::ClusterIntrospectionSourceIndexKey,
261        proto::ClusterIntrospectionSourceIndexValue,
262    ),
263    Item(proto::ItemKey, proto::ItemValue),
264    ItemColumns(proto::ItemColumnsKey, proto::ItemColumnsValue),
265    NetworkPolicy(proto::NetworkPolicyKey, proto::NetworkPolicyValue),
266    QueryPolicy(proto::QueryPolicyKey, proto::QueryPolicyValue),
267    Role(proto::RoleKey, proto::RoleValue),
268    RoleAuth(proto::RoleAuthKey, proto::RoleAuthValue),
269    Schema(proto::SchemaKey, proto::SchemaValue),
270    Setting(proto::SettingKey, proto::SettingValue),
271    SourceReferences(proto::SourceReferencesKey, proto::SourceReferencesValue),
272    SystemConfiguration(
273        proto::ServerConfigurationKey,
274        proto::ServerConfigurationValue,
275    ),
276    ClusterSystemConfiguration(
277        proto::ClusterSystemConfigurationKey,
278        proto::ClusterSystemConfigurationValue,
279    ),
280    ReplicaSystemConfiguration(
281        proto::ReplicaSystemConfigurationKey,
282        proto::ReplicaSystemConfigurationValue,
283    ),
284    SystemObjectMapping(proto::GidMappingKey, proto::GidMappingValue),
285    SystemPrivilege(proto::SystemPrivilegesKey, proto::SystemPrivilegesValue),
286    StorageCollectionMetadata(
287        proto::StorageCollectionMetadataKey,
288        proto::StorageCollectionMetadataValue,
289    ),
290    UnfinalizedShard(proto::UnfinalizedShardKey, ()),
291    TxnWalShard((), proto::TxnWalShardValue),
292}
293
294impl StateUpdateKind {
295    pub(crate) fn collection_type(&self) -> Option<CollectionType> {
296        match self {
297            StateUpdateKind::AuditLog(_, _) => Some(CollectionType::AuditLog),
298            StateUpdateKind::Cluster(_, _) => Some(CollectionType::ComputeInstance),
299            StateUpdateKind::ClusterReplica(_, _) => Some(CollectionType::ComputeReplicas),
300            StateUpdateKind::ClusterReplicaSize(_, _) => Some(CollectionType::ClusterReplicaSize),
301            StateUpdateKind::Comment(_, _) => Some(CollectionType::Comments),
302            StateUpdateKind::Config(_, _) => Some(CollectionType::Config),
303            StateUpdateKind::Database(_, _) => Some(CollectionType::Database),
304            StateUpdateKind::DefaultPrivilege(_, _) => Some(CollectionType::DefaultPrivileges),
305            StateUpdateKind::FenceToken(_) => None,
306            StateUpdateKind::IdAllocator(_, _) => Some(CollectionType::IdAlloc),
307            StateUpdateKind::IndexColumns(_, _) => Some(CollectionType::IndexColumns),
308            StateUpdateKind::IntrospectionSourceIndex(_, _) => {
309                Some(CollectionType::ComputeIntrospectionSourceIndex)
310            }
311            StateUpdateKind::Item(_, _) => Some(CollectionType::Item),
312            StateUpdateKind::ItemColumns(_, _) => Some(CollectionType::ItemColumns),
313            StateUpdateKind::NetworkPolicy(_, _) => Some(CollectionType::NetworkPolicy),
314            StateUpdateKind::QueryPolicy(_, _) => Some(CollectionType::QueryPolicy),
315            StateUpdateKind::Role(_, _) => Some(CollectionType::Role),
316            StateUpdateKind::RoleAuth(_, _) => Some(CollectionType::RoleAuth),
317            StateUpdateKind::Schema(_, _) => Some(CollectionType::Schema),
318            StateUpdateKind::Setting(_, _) => Some(CollectionType::Setting),
319            StateUpdateKind::SourceReferences(_, _) => Some(CollectionType::SourceReferences),
320            StateUpdateKind::SystemConfiguration(_, _) => Some(CollectionType::SystemConfiguration),
321            StateUpdateKind::ClusterSystemConfiguration(_, _) => {
322                Some(CollectionType::ClusterSystemConfiguration)
323            }
324            StateUpdateKind::ReplicaSystemConfiguration(_, _) => {
325                Some(CollectionType::ReplicaSystemConfiguration)
326            }
327            StateUpdateKind::SystemObjectMapping(_, _) => Some(CollectionType::SystemGidMapping),
328            StateUpdateKind::SystemPrivilege(_, _) => Some(CollectionType::SystemPrivileges),
329            StateUpdateKind::StorageCollectionMetadata(_, _) => {
330                Some(CollectionType::StorageCollectionMetadata)
331            }
332            StateUpdateKind::UnfinalizedShard(_, _) => Some(CollectionType::UnfinalizedShard),
333            StateUpdateKind::TxnWalShard(_, _) => Some(CollectionType::TxnWalShard),
334        }
335    }
336}
337
338/// Version of [`StateUpdateKind`] to allow reading/writing raw json from/to persist.
339#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
340pub struct StateUpdateKindJson(Jsonb);
341
342impl StateUpdateKindJson {
343    pub(crate) fn from_serde<S: serde::Serialize>(s: S) -> Self {
344        let serde_value = serde_json::to_value(s).expect("valid json");
345        let row = Jsonb::from_serde_json(serde_value).expect("valid json");
346        StateUpdateKindJson(row)
347    }
348
349    pub(crate) fn to_serde<D: serde::de::DeserializeOwned>(&self) -> D {
350        self.try_to_serde().expect("jsonb should roundtrip")
351    }
352
353    pub(crate) fn try_to_serde<D: serde::de::DeserializeOwned>(
354        &self,
355    ) -> Result<D, serde_json::error::Error> {
356        let serde_value = self.0.as_ref().to_serde_json();
357        serde_json::from_value::<D>(serde_value)
358    }
359
360    fn kind(&self) -> &str {
361        let row = self.0.row();
362        let mut iter = row.unpack_first().unwrap_map().iter();
363        let datum = iter
364            .find_map(|(field, datum)| if field == "kind" { Some(datum) } else { None })
365            .expect("kind field must exist");
366        datum.unwrap_str()
367    }
368
369    /// Returns true if this is an update kind that is always deserializable, even before migrations. Otherwise, returns false.
370    pub(crate) fn is_always_deserializable(&self) -> bool {
371        // Construct some fake update kinds so we can extract exactly what the kind field will
372        // serialize as.
373        static DESERIALIZABLE_KINDS: LazyLock<HashSet<String>> = LazyLock::new(|| {
374            [
375                StateUpdateKind::FenceToken(FenceToken {
376                    deploy_generation: 1,
377                    epoch: Epoch::new(1).expect("non-zero"),
378                }),
379                StateUpdateKind::Config(
380                    proto::ConfigKey { key: String::new() },
381                    proto::ConfigValue { value: 1 },
382                ),
383                StateUpdateKind::Setting(
384                    proto::SettingKey {
385                        name: String::new(),
386                    },
387                    proto::SettingValue {
388                        value: String::new(),
389                    },
390                ),
391                StateUpdateKind::AuditLog(
392                    proto::AuditLogKey {
393                        event: proto::AuditLogEvent::V1(proto::AuditLogEventV1 {
394                            id: 1,
395                            event_type: proto::audit_log_event_v1::EventType::Create,
396                            object_type: proto::audit_log_event_v1::ObjectType::Cluster,
397                            user: None,
398                            occurred_at: proto::EpochMillis { millis: 1 },
399                            details: proto::audit_log_event_v1::Details::ResetAllV1(
400                                proto::Empty {},
401                            ),
402                        }),
403                    },
404                    (),
405                ),
406            ]
407            .into_iter()
408            .map(|kind| {
409                let json_kind: StateUpdateKindJson = kind.into();
410                json_kind.kind().to_string()
411            })
412            .collect()
413        });
414        DESERIALIZABLE_KINDS.contains(self.kind())
415    }
416
417    /// Returns true if this is an audit log update. Otherwise, returns false.
418    pub(crate) fn is_audit_log(&self) -> bool {
419        // Construct a fake audit log so we can extract exactly what the kind field will serialize
420        // as.
421        static AUDIT_LOG_KIND: LazyLock<String> = LazyLock::new(|| {
422            let audit_log = StateUpdateKind::AuditLog(
423                proto::AuditLogKey {
424                    event: proto::AuditLogEvent::V1(proto::AuditLogEventV1 {
425                        id: 1,
426                        event_type: proto::audit_log_event_v1::EventType::Create,
427                        object_type: proto::audit_log_event_v1::ObjectType::Cluster,
428                        user: None,
429                        occurred_at: proto::EpochMillis { millis: 1 },
430                        details: proto::audit_log_event_v1::Details::ResetAllV1(proto::Empty {}),
431                    }),
432                },
433                (),
434            );
435            let json_kind: StateUpdateKindJson = audit_log.into();
436            json_kind.kind().to_string()
437        });
438        &*AUDIT_LOG_KIND == self.kind()
439    }
440}
441
442/// Version of [`StateUpdateKind`] that is stored directly in persist.
443type PersistStateUpdate = ((SourceData, ()), Timestamp, StorageDiff);
444
445impl TryFrom<&StateUpdate<StateUpdateKind>> for Option<memory::objects::StateUpdate> {
446    type Error = DurableCatalogError;
447
448    fn try_from(
449        StateUpdate { kind, ts, diff }: &StateUpdate<StateUpdateKind>,
450    ) -> Result<Self, Self::Error> {
451        let kind: Option<memory::objects::StateUpdateKind> = TryInto::try_into(kind)?;
452        let update = kind.map(|kind| memory::objects::StateUpdate {
453            kind,
454            ts: ts.clone(),
455            diff: diff.clone().try_into().expect("invalid diff"),
456        });
457        Ok(update)
458    }
459}
460
461impl TryFrom<&StateUpdateKind> for Option<memory::objects::StateUpdateKind> {
462    type Error = DurableCatalogError;
463
464    fn try_from(kind: &StateUpdateKind) -> Result<Self, Self::Error> {
465        fn into_durable<PK, PV, T>(key: &PK, value: &PV) -> Result<T, DurableCatalogError>
466        where
467            PK: ProtoType<T::Key> + Clone,
468            PV: ProtoType<T::Value> + Clone,
469            T: DurableType,
470        {
471            let key = key.clone().into_rust()?;
472            let value = value.clone().into_rust()?;
473            Ok(T::from_key_value(key, value))
474        }
475
476        Ok(match kind {
477            StateUpdateKind::AuditLog(key, value) => {
478                let audit_log = into_durable(key, value)?;
479                Some(memory::objects::StateUpdateKind::AuditLog(audit_log))
480            }
481            StateUpdateKind::Cluster(key, value) => {
482                let cluster = into_durable(key, value)?;
483                Some(memory::objects::StateUpdateKind::Cluster(cluster))
484            }
485            StateUpdateKind::ClusterReplica(key, value) => {
486                let cluster_replica = into_durable(key, value)?;
487                Some(memory::objects::StateUpdateKind::ClusterReplica(
488                    cluster_replica,
489                ))
490            }
491            StateUpdateKind::Comment(key, value) => {
492                let comment = into_durable(key, value)?;
493                Some(memory::objects::StateUpdateKind::Comment(comment))
494            }
495            StateUpdateKind::Database(key, value) => {
496                let database = into_durable(key, value)?;
497                Some(memory::objects::StateUpdateKind::Database(database))
498            }
499            StateUpdateKind::DefaultPrivilege(key, value) => {
500                let default_privilege = into_durable(key, value)?;
501                Some(memory::objects::StateUpdateKind::DefaultPrivilege(
502                    default_privilege,
503                ))
504            }
505            StateUpdateKind::Item(key, value) => {
506                let item = into_durable(key, value)?;
507                Some(memory::objects::StateUpdateKind::Item(item))
508            }
509            StateUpdateKind::IntrospectionSourceIndex(key, value) => {
510                let introspection_source_index = into_durable(key, value)?;
511                Some(memory::objects::StateUpdateKind::IntrospectionSourceIndex(
512                    introspection_source_index,
513                ))
514            }
515            StateUpdateKind::NetworkPolicy(key, value) => {
516                let policy = into_durable(key, value)?;
517                Some(memory::objects::StateUpdateKind::NetworkPolicy(policy))
518            }
519            StateUpdateKind::ClusterReplicaSize(key, value) => {
520                let size = into_durable(key, value)?;
521                Some(memory::objects::StateUpdateKind::ClusterReplicaSize(size))
522            }
523            StateUpdateKind::QueryPolicy(key, value) => {
524                let policy = into_durable(key, value)?;
525                Some(memory::objects::StateUpdateKind::QueryPolicy(policy))
526            }
527            StateUpdateKind::Role(key, value) => {
528                let role = into_durable(key, value)?;
529                Some(memory::objects::StateUpdateKind::Role(role))
530            }
531            StateUpdateKind::RoleAuth(key, value) => {
532                let role_auth = into_durable(key, value)?;
533                Some(memory::objects::StateUpdateKind::RoleAuth(role_auth))
534            }
535            StateUpdateKind::Schema(key, value) => {
536                let schema = into_durable(key, value)?;
537                Some(memory::objects::StateUpdateKind::Schema(schema))
538            }
539            StateUpdateKind::SourceReferences(key, value) => {
540                let source_references = into_durable(key, value)?;
541                Some(memory::objects::StateUpdateKind::SourceReferences(
542                    source_references,
543                ))
544            }
545            StateUpdateKind::StorageCollectionMetadata(key, value) => {
546                let storage_collection_metadata = into_durable(key, value)?;
547                Some(memory::objects::StateUpdateKind::StorageCollectionMetadata(
548                    storage_collection_metadata,
549                ))
550            }
551            StateUpdateKind::SystemConfiguration(key, value) => {
552                let system_configuration = into_durable(key, value)?;
553                Some(memory::objects::StateUpdateKind::SystemConfiguration(
554                    system_configuration,
555                ))
556            }
557            StateUpdateKind::ClusterSystemConfiguration(key, value) => {
558                let cluster_system_configuration = into_durable(key, value)?;
559                Some(
560                    memory::objects::StateUpdateKind::ClusterSystemConfiguration(
561                        cluster_system_configuration,
562                    ),
563                )
564            }
565            StateUpdateKind::ReplicaSystemConfiguration(key, value) => {
566                let replica_system_configuration = into_durable(key, value)?;
567                Some(
568                    memory::objects::StateUpdateKind::ReplicaSystemConfiguration(
569                        replica_system_configuration,
570                    ),
571                )
572            }
573            StateUpdateKind::SystemObjectMapping(key, value) => {
574                let system_object_mapping = into_durable(key, value)?;
575                Some(memory::objects::StateUpdateKind::SystemObjectMapping(
576                    system_object_mapping,
577                ))
578            }
579            StateUpdateKind::SystemPrivilege(key, value) => {
580                let system_privilege = into_durable(key, value)?;
581                Some(memory::objects::StateUpdateKind::SystemPrivilege(
582                    system_privilege,
583                ))
584            }
585            StateUpdateKind::UnfinalizedShard(key, value) => {
586                let unfinalized_shard = into_durable(key, value)?;
587                Some(memory::objects::StateUpdateKind::UnfinalizedShard(
588                    unfinalized_shard,
589                ))
590            }
591            // Not exposed to higher layers.
592            StateUpdateKind::Config(_, _)
593            | StateUpdateKind::FenceToken(_)
594            | StateUpdateKind::IdAllocator(_, _)
595            | StateUpdateKind::IndexColumns(_, _)
596            | StateUpdateKind::ItemColumns(_, _)
597            | StateUpdateKind::Setting(_, _)
598            | StateUpdateKind::TxnWalShard(_, _) => None,
599        })
600    }
601}
602
603impl TryFrom<StateUpdate<StateUpdateKindJson>> for StateUpdate<StateUpdateKind> {
604    type Error = String;
605
606    fn try_from(update: StateUpdate<StateUpdateKindJson>) -> Result<Self, Self::Error> {
607        Ok(StateUpdate {
608            kind: TryInto::try_into(update.kind)?,
609            ts: update.ts,
610            diff: update.diff,
611        })
612    }
613}
614
615impl TryFrom<StateUpdateKindJson> for StateUpdateKind {
616    type Error = String;
617
618    fn try_from(value: StateUpdateKindJson) -> Result<Self, Self::Error> {
619        let kind: proto::StateUpdateKind = value.try_to_serde().map_err(|err| err.to_string())?;
620        StateUpdateKind::from_proto(kind).map_err(|err| err.to_string())
621    }
622}
623
624impl TryFrom<&StateUpdateKindJson> for StateUpdateKind {
625    type Error = String;
626
627    fn try_from(value: &StateUpdateKindJson) -> Result<Self, Self::Error> {
628        let kind: proto::StateUpdateKind = value.try_to_serde().map_err(|err| err.to_string())?;
629        StateUpdateKind::from_proto(kind).map_err(|err| err.to_string())
630    }
631}
632
633impl From<StateUpdateKind> for StateUpdateKindJson {
634    fn from(value: StateUpdateKind) -> Self {
635        let kind = value.into_proto_owned();
636        StateUpdateKindJson::from_serde(kind)
637    }
638}
639
640// Be very careful about changing these implementations. The default impl of `into_proto_owned`
641// calls `into_proto`, and this impl of `into_proto` calls `into_proto_owned`. It would be very
642// easy to accidentally cause infinite recursion.
643impl RustType<proto::StateUpdateKind> for StateUpdateKind {
644    fn into_proto(&self) -> proto::StateUpdateKind {
645        error!("unexpected clone of catalog data");
646        self.clone().into_proto_owned()
647    }
648
649    fn into_proto_owned(self) -> proto::StateUpdateKind {
650        match self {
651            StateUpdateKind::AuditLog(key, ()) => {
652                proto::StateUpdateKind::AuditLog(proto::AuditLog { key })
653            }
654            StateUpdateKind::Cluster(key, value) => {
655                proto::StateUpdateKind::Cluster(proto::Cluster { key, value })
656            }
657            StateUpdateKind::ClusterReplica(key, value) => {
658                proto::StateUpdateKind::ClusterReplica(proto::ClusterReplica { key, value })
659            }
660            StateUpdateKind::Comment(key, value) => {
661                proto::StateUpdateKind::Comment(proto::Comment { key, value })
662            }
663            StateUpdateKind::IndexColumns(key, value) => {
664                proto::StateUpdateKind::IndexColumns(proto::IndexColumns { key, value })
665            }
666            StateUpdateKind::ItemColumns(key, value) => {
667                proto::StateUpdateKind::ItemColumns(proto::ItemColumns { key, value })
668            }
669            StateUpdateKind::Config(key, value) => {
670                proto::StateUpdateKind::Config(proto::Config { key, value })
671            }
672            StateUpdateKind::Database(key, value) => {
673                proto::StateUpdateKind::Database(proto::Database { key, value })
674            }
675            StateUpdateKind::DefaultPrivilege(key, value) => {
676                proto::StateUpdateKind::DefaultPrivileges(proto::DefaultPrivileges { key, value })
677            }
678            StateUpdateKind::FenceToken(fence_token) => {
679                proto::StateUpdateKind::FenceToken(proto::FenceToken {
680                    deploy_generation: fence_token.deploy_generation,
681                    epoch: fence_token.epoch.get(),
682                })
683            }
684            StateUpdateKind::IdAllocator(key, value) => {
685                proto::StateUpdateKind::IdAlloc(proto::IdAlloc { key, value })
686            }
687            StateUpdateKind::IntrospectionSourceIndex(key, value) => {
688                proto::StateUpdateKind::ClusterIntrospectionSourceIndex(
689                    proto::ClusterIntrospectionSourceIndex { key, value },
690                )
691            }
692            StateUpdateKind::Item(key, value) => {
693                proto::StateUpdateKind::Item(proto::Item { key, value })
694            }
695            StateUpdateKind::NetworkPolicy(key, value) => {
696                proto::StateUpdateKind::NetworkPolicy(proto::NetworkPolicy { key, value })
697            }
698            StateUpdateKind::ClusterReplicaSize(key, value) => {
699                proto::StateUpdateKind::ClusterReplicaSize(proto::ClusterReplicaSize { key, value })
700            }
701            StateUpdateKind::QueryPolicy(key, value) => {
702                proto::StateUpdateKind::QueryPolicy(proto::QueryPolicy { key, value })
703            }
704            StateUpdateKind::Role(key, value) => {
705                proto::StateUpdateKind::Role(proto::Role { key, value })
706            }
707            StateUpdateKind::RoleAuth(key, value) => {
708                proto::StateUpdateKind::RoleAuth(proto::RoleAuth { key, value })
709            }
710            StateUpdateKind::Schema(key, value) => {
711                proto::StateUpdateKind::Schema(proto::Schema { key, value })
712            }
713            StateUpdateKind::Setting(key, value) => {
714                proto::StateUpdateKind::Setting(proto::Setting { key, value })
715            }
716            StateUpdateKind::SourceReferences(key, value) => {
717                proto::StateUpdateKind::SourceReferences(proto::SourceReferences { key, value })
718            }
719            StateUpdateKind::SystemConfiguration(key, value) => {
720                proto::StateUpdateKind::ServerConfiguration(proto::ServerConfiguration {
721                    key,
722                    value,
723                })
724            }
725            StateUpdateKind::ClusterSystemConfiguration(key, value) => {
726                proto::StateUpdateKind::ClusterSystemConfiguration(
727                    proto::ClusterSystemConfiguration { key, value },
728                )
729            }
730            StateUpdateKind::ReplicaSystemConfiguration(key, value) => {
731                proto::StateUpdateKind::ReplicaSystemConfiguration(
732                    proto::ReplicaSystemConfiguration { key, value },
733                )
734            }
735            StateUpdateKind::SystemObjectMapping(key, value) => {
736                proto::StateUpdateKind::GidMapping(proto::GidMapping { key, value })
737            }
738            StateUpdateKind::SystemPrivilege(key, value) => {
739                proto::StateUpdateKind::SystemPrivileges(proto::SystemPrivileges { key, value })
740            }
741            StateUpdateKind::StorageCollectionMetadata(key, value) => {
742                proto::StateUpdateKind::StorageCollectionMetadata(
743                    proto::StorageCollectionMetadata { key, value },
744                )
745            }
746            StateUpdateKind::UnfinalizedShard(key, ()) => {
747                proto::StateUpdateKind::UnfinalizedShard(proto::UnfinalizedShard { key })
748            }
749            StateUpdateKind::TxnWalShard((), value) => {
750                proto::StateUpdateKind::TxnWalShard(proto::TxnWalShard { value })
751            }
752        }
753    }
754
755    fn from_proto(proto: proto::StateUpdateKind) -> Result<StateUpdateKind, TryFromProtoError> {
756        Ok(match proto {
757            proto::StateUpdateKind::AuditLog(proto::AuditLog { key }) => {
758                StateUpdateKind::AuditLog(key, ())
759            }
760            proto::StateUpdateKind::Cluster(proto::Cluster { key, value }) => {
761                StateUpdateKind::Cluster(key, value)
762            }
763            proto::StateUpdateKind::ClusterReplica(proto::ClusterReplica { key, value }) => {
764                StateUpdateKind::ClusterReplica(key, value)
765            }
766            proto::StateUpdateKind::Comment(proto::Comment { key, value }) => {
767                StateUpdateKind::Comment(key, value)
768            }
769            proto::StateUpdateKind::IndexColumns(proto::IndexColumns { key, value }) => {
770                StateUpdateKind::IndexColumns(key, value)
771            }
772            proto::StateUpdateKind::ItemColumns(proto::ItemColumns { key, value }) => {
773                StateUpdateKind::ItemColumns(key, value)
774            }
775            proto::StateUpdateKind::Config(proto::Config { key, value }) => {
776                StateUpdateKind::Config(key, value)
777            }
778            proto::StateUpdateKind::Database(proto::Database { key, value }) => {
779                StateUpdateKind::Database(key, value)
780            }
781            proto::StateUpdateKind::DefaultPrivileges(proto::DefaultPrivileges { key, value }) => {
782                StateUpdateKind::DefaultPrivilege(key, value)
783            }
784            proto::StateUpdateKind::FenceToken(proto::FenceToken {
785                deploy_generation,
786                epoch,
787            }) => StateUpdateKind::FenceToken(FenceToken {
788                deploy_generation,
789                epoch: Epoch::new(epoch).ok_or_else(|| {
790                    TryFromProtoError::missing_field("state_update_kind::Epoch::epoch")
791                })?,
792            }),
793            proto::StateUpdateKind::IdAlloc(proto::IdAlloc { key, value }) => {
794                StateUpdateKind::IdAllocator(key, value)
795            }
796            proto::StateUpdateKind::ClusterIntrospectionSourceIndex(
797                proto::ClusterIntrospectionSourceIndex { key, value },
798            ) => StateUpdateKind::IntrospectionSourceIndex(key, value),
799            proto::StateUpdateKind::Item(proto::Item { key, value }) => {
800                StateUpdateKind::Item(key, value)
801            }
802            proto::StateUpdateKind::Role(proto::Role { key, value }) => {
803                StateUpdateKind::Role(key, value)
804            }
805            proto::StateUpdateKind::RoleAuth(proto::RoleAuth { key, value }) => {
806                StateUpdateKind::RoleAuth(key, value)
807            }
808            proto::StateUpdateKind::Schema(proto::Schema { key, value }) => {
809                StateUpdateKind::Schema(key, value)
810            }
811            proto::StateUpdateKind::Setting(proto::Setting { key, value }) => {
812                StateUpdateKind::Setting(key, value)
813            }
814            proto::StateUpdateKind::ServerConfiguration(proto::ServerConfiguration {
815                key,
816                value,
817            }) => StateUpdateKind::SystemConfiguration(key, value),
818            proto::StateUpdateKind::ClusterSystemConfiguration(
819                proto::ClusterSystemConfiguration { key, value },
820            ) => StateUpdateKind::ClusterSystemConfiguration(key, value),
821            proto::StateUpdateKind::ReplicaSystemConfiguration(
822                proto::ReplicaSystemConfiguration { key, value },
823            ) => StateUpdateKind::ReplicaSystemConfiguration(key, value),
824            proto::StateUpdateKind::GidMapping(proto::GidMapping { key, value }) => {
825                StateUpdateKind::SystemObjectMapping(key, value)
826            }
827            proto::StateUpdateKind::SystemPrivileges(proto::SystemPrivileges { key, value }) => {
828                StateUpdateKind::SystemPrivilege(key, value)
829            }
830            proto::StateUpdateKind::StorageCollectionMetadata(
831                proto::StorageCollectionMetadata { key, value },
832            ) => StateUpdateKind::StorageCollectionMetadata(key, value),
833            proto::StateUpdateKind::UnfinalizedShard(proto::UnfinalizedShard { key }) => {
834                StateUpdateKind::UnfinalizedShard(key, ())
835            }
836            proto::StateUpdateKind::TxnWalShard(proto::TxnWalShard { value }) => {
837                StateUpdateKind::TxnWalShard((), value)
838            }
839            proto::StateUpdateKind::SourceReferences(proto::SourceReferences { key, value }) => {
840                StateUpdateKind::SourceReferences(key, value)
841            }
842            proto::StateUpdateKind::NetworkPolicy(proto::NetworkPolicy { key, value }) => {
843                StateUpdateKind::NetworkPolicy(key, value)
844            }
845            proto::StateUpdateKind::ClusterReplicaSize(proto::ClusterReplicaSize {
846                key,
847                value,
848            }) => StateUpdateKind::ClusterReplicaSize(key, value),
849            proto::StateUpdateKind::QueryPolicy(proto::QueryPolicy { key, value }) => {
850                StateUpdateKind::QueryPolicy(key, value)
851            }
852        })
853    }
854}
855
856/// Decodes a [`StateUpdate<StateUpdateKindJson>`] from the `(key, value, ts,
857/// diff)` tuple/update we store in persist.
858impl From<PersistStateUpdate> for StateUpdate<StateUpdateKindJson> {
859    fn from(kvtd: PersistStateUpdate) -> Self {
860        let ((key, ()), ts, diff) = kvtd;
861        StateUpdate {
862            kind: StateUpdateKindJson::from(key),
863            ts,
864            diff: diff.into(),
865        }
866    }
867}
868
869impl From<StateUpdateKindJson> for SourceData {
870    fn from(value: StateUpdateKindJson) -> SourceData {
871        let row = value.0.into_row();
872        SourceData(Ok(row))
873    }
874}
875
876impl From<SourceData> for StateUpdateKindJson {
877    fn from(value: SourceData) -> Self {
878        let row = value.0.expect("only Ok values stored in catalog shard");
879        StateUpdateKindJson(Jsonb::from_row(row))
880    }
881}
882
883#[cfg(test)]
884mod tests {
885    use mz_persist_types::Codec;
886    use mz_repr::{RelationDesc, SqlScalarType};
887    use mz_storage_types::sources::SourceData;
888    use proptest::prelude::*;
889
890    use crate::durable::Epoch;
891    use crate::durable::objects::FenceToken;
892    use crate::durable::objects::serialization::proto;
893    use crate::durable::objects::state_update::{StateUpdateKind, StateUpdateKindJson};
894
895    #[mz_ore::test]
896    #[cfg_attr(miri, ignore)]
897    fn kind_test() {
898        let test_cases = [
899            (
900                StateUpdateKind::FenceToken(FenceToken {
901                    deploy_generation: 1,
902                    epoch: Epoch::new(1).expect("non-zero"),
903                }),
904                "FenceToken",
905            ),
906            (
907                StateUpdateKind::Config(
908                    proto::ConfigKey { key: String::new() },
909                    proto::ConfigValue { value: 1 },
910                ),
911                "Config",
912            ),
913            (
914                StateUpdateKind::Setting(
915                    proto::SettingKey {
916                        name: String::new(),
917                    },
918                    proto::SettingValue {
919                        value: String::new(),
920                    },
921                ),
922                "Setting",
923            ),
924            (
925                StateUpdateKind::AuditLog(
926                    proto::AuditLogKey {
927                        event: proto::AuditLogEvent::V1(proto::AuditLogEventV1 {
928                            id: 1,
929                            event_type: proto::audit_log_event_v1::EventType::Create,
930                            object_type: proto::audit_log_event_v1::ObjectType::Cluster,
931                            user: None,
932                            occurred_at: proto::EpochMillis { millis: 4 },
933                            details: proto::audit_log_event_v1::Details::ResetAllV1(
934                                proto::Empty {},
935                            ),
936                        }),
937                    },
938                    (),
939                ),
940                "AuditLog",
941            ),
942        ];
943
944        for (kind, expected) in test_cases {
945            let json_kind: StateUpdateKindJson = kind.into();
946            let kind = json_kind.kind().to_string();
947            assert_eq!(expected, kind);
948        }
949    }
950
951    proptest! {
952        #[mz_ore::test]
953        #[cfg_attr(miri, ignore)] // slow
954        fn proptest_state_update_kind_roundtrip(kind: StateUpdateKind) {
955            // Verify that we can map encode into the "raw" json format. This
956            // validates things like contained integers fitting in f64.
957            let raw = StateUpdateKindJson::from(kind.clone());
958            let desc = RelationDesc::builder().with_column("a", SqlScalarType::Jsonb.nullable(false)).finish();
959
960            // Verify that the raw roundtrips through the SourceData Codec impl.
961            let source_data = SourceData::from(raw.clone());
962            let mut encoded = Vec::new();
963            source_data.encode(&mut encoded);
964            let decoded = SourceData::decode(&encoded, &desc).expect("should be valid SourceData");
965            prop_assert_eq!(&source_data, &decoded);
966            let decoded = StateUpdateKindJson::from(decoded);
967            prop_assert_eq!(&raw, &decoded);
968
969            // Verify that the enum roundtrips.
970            let decoded = StateUpdateKind::try_from(decoded).expect("should be valid StateUpdateKind");
971            prop_assert_eq!(&kind, &decoded);
972        }
973    }
974}