Skip to main content

mz_catalog/durable/
objects.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! The current types used to represent catalog data stored on disk. These objects generally fall
11//! into two categories.
12//!
13//! The key-value objects are a one-to-one mapping of the protobuf objects used to save catalog
14//! data durably. They can be converted to and from protobuf via the
15//! [`RustType`](crate::durable::objects::serialization::RustType) trait.
16//! These objects should not be exposed anywhere outside the [`crate::durable`] module.
17//!
18//! The other type of objects combine the information from keys and values into a single struct,
19//! but are still a direct representation of the data stored on disk. They can be converted to and
20//! from the key-value objects via the [`DurableType`] trait. These objects are used to pass
21//! information to other modules in this crate and other catalog related code.
22//!
23//! All non-catalog code should interact with the objects in [`crate::memory::objects`] and never
24//! directly interact with the objects in this module.
25//!
26//! As an example, [`DatabaseKey`] and [`DatabaseValue`] are key-value objects, while [`Database`]
27//! is the non-key-value counterpart.
28
29pub mod serialization;
30pub(crate) mod state_update;
31
32use std::cmp::Ordering;
33use std::collections::BTreeMap;
34use std::num::NonZero;
35use std::time::Duration;
36
37use bytesize::ByteSize;
38use mz_audit_log::VersionedEvent;
39use mz_controller::clusters::{ReplicaAllocation, ReplicaLogging};
40use mz_controller_types::{ClusterId, ReplicaId};
41use mz_orchestrator::{CpuLimit, DiskLimit, MemoryLimit};
42use mz_ore::cast::CastFrom;
43use mz_persist_types::ShardId;
44use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
45use mz_repr::cluster_replica_size_id::ClusterReplicaSizeId;
46use mz_repr::network_policy_id::NetworkPolicyId;
47use mz_repr::query_policy_id::QueryPolicyId;
48use mz_repr::role_id::RoleId;
49use mz_repr::{CatalogItemId, ColumnName, GlobalId, RelationVersion};
50use mz_sql::catalog::{
51    CatalogItemType, DefaultPrivilegeAclItem, DefaultPrivilegeObject, ObjectType, RoleAttributes,
52    RoleMembership, RoleVars,
53};
54use mz_sql::names::{CommentObjectId, DatabaseId, SchemaId};
55use mz_sql::plan::{AutoScalingStrategy, ClusterSchedule, NetworkPolicyRule, OnTimeoutAction};
56use mz_sql::plan::{QueryPolicyMode, QueryPolicyRule};
57#[cfg(test)]
58use proptest_derive::Arbitrary;
59use uuid::Uuid;
60
61use crate::builtin::RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL;
62use crate::durable::Epoch;
63use crate::durable::objects::serialization::proto;
64
65/// A proptest strategy for [`Uuid`]s, which don't implement `Arbitrary`.
66#[cfg(test)]
67fn any_uuid() -> impl proptest::strategy::Strategy<Value = Uuid> {
68    use proptest::strategy::Strategy;
69    proptest::arbitrary::any::<u128>().prop_map(Uuid::from_u128)
70}
71
72// Structs used to pass information to outside modules.
73
74/// A trait for representing `Self` as a key-value pair of type
75/// `(Key, Value)` for the purpose of storing this value durably.
76///
77/// To encode a key-value pair, use [`DurableType::into_key_value`].
78///
79/// To decode a key-value pair, use [`DurableType::from_key_value`].
80///
81/// This trait is based on [`RustType`], however it is meant to
82/// convert the types used in [`RustType`] to a more consumable and
83/// condensed type.
84///
85/// [`RustType`]: crate::durable::objects::serialization::RustType
86pub trait DurableType: Sized {
87    type Key;
88    type Value;
89
90    /// Consume and convert `Self` into a `(Key, Value)` key-value pair.
91    fn into_key_value(self) -> (Self::Key, Self::Value);
92
93    /// Consume and convert a `(Key, Value)` key-value pair back into a
94    /// `Self` value.
95    fn from_key_value(key: Self::Key, value: Self::Value) -> Self;
96
97    // TODO(jkosh44) Would be great to not clone, since this is always used for lookups which only
98    // needs a reference. In practice, we currently almost always use this method to clone a single
99    // 64-bit integer, so it's not a huge deal.
100    /// Produce a `Key` from self. This may involve cloning/copying required fields.
101    fn key(&self) -> Self::Key;
102}
103
104#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
105pub struct Database {
106    pub id: DatabaseId,
107    pub oid: u32,
108    pub name: String,
109    pub owner_id: RoleId,
110    pub privileges: Vec<MzAclItem>,
111}
112
113impl DurableType for Database {
114    type Key = DatabaseKey;
115    type Value = DatabaseValue;
116
117    fn into_key_value(self) -> (Self::Key, Self::Value) {
118        (
119            DatabaseKey { id: self.id },
120            DatabaseValue {
121                oid: self.oid,
122                name: self.name,
123                owner_id: self.owner_id,
124                privileges: self.privileges,
125            },
126        )
127    }
128
129    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
130        Self {
131            id: key.id,
132            oid: value.oid,
133            name: value.name,
134            owner_id: value.owner_id,
135            privileges: value.privileges,
136        }
137    }
138
139    fn key(&self) -> Self::Key {
140        DatabaseKey { id: self.id }
141    }
142}
143
144#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
145pub struct Schema {
146    pub id: SchemaId,
147    pub oid: u32,
148    pub name: String,
149    pub database_id: Option<DatabaseId>,
150    pub owner_id: RoleId,
151    pub privileges: Vec<MzAclItem>,
152}
153
154impl DurableType for Schema {
155    type Key = SchemaKey;
156    type Value = SchemaValue;
157
158    fn into_key_value(self) -> (Self::Key, Self::Value) {
159        (
160            SchemaKey { id: self.id },
161            SchemaValue {
162                oid: self.oid,
163                database_id: self.database_id,
164                name: self.name,
165                owner_id: self.owner_id,
166                privileges: self.privileges,
167            },
168        )
169    }
170
171    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
172        Self {
173            id: key.id,
174            oid: value.oid,
175            name: value.name,
176            database_id: value.database_id,
177            owner_id: value.owner_id,
178            privileges: value.privileges,
179        }
180    }
181
182    fn key(&self) -> Self::Key {
183        SchemaKey { id: self.id }
184    }
185}
186
187#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
188pub struct Role {
189    pub id: RoleId,
190    pub oid: u32,
191    pub name: String,
192    pub attributes: RoleAttributes,
193    pub membership: RoleMembership,
194    pub vars: RoleVars,
195}
196
197impl DurableType for Role {
198    type Key = RoleKey;
199    type Value = RoleValue;
200
201    fn into_key_value(self) -> (Self::Key, Self::Value) {
202        (
203            RoleKey { id: self.id },
204            RoleValue {
205                oid: self.oid,
206                name: self.name,
207                attributes: self.attributes,
208                membership: self.membership,
209                vars: self.vars,
210            },
211        )
212    }
213
214    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
215        Self {
216            id: key.id,
217            oid: value.oid,
218            name: value.name,
219            attributes: value.attributes,
220            membership: value.membership,
221            vars: value.vars,
222        }
223    }
224
225    fn key(&self) -> Self::Key {
226        RoleKey { id: self.id }
227    }
228}
229
230#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
231pub struct RoleAuth {
232    pub role_id: RoleId,
233    pub password_hash: Option<String>,
234    pub updated_at: u64,
235}
236
237impl DurableType for RoleAuth {
238    type Key = RoleAuthKey;
239    type Value = RoleAuthValue;
240
241    fn into_key_value(self) -> (Self::Key, Self::Value) {
242        (
243            RoleAuthKey {
244                role_id: self.role_id,
245            },
246            RoleAuthValue {
247                password_hash: self.password_hash,
248                updated_at: self.updated_at,
249            },
250        )
251    }
252
253    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
254        Self {
255            role_id: key.role_id,
256            password_hash: value.password_hash,
257            updated_at: value.updated_at,
258        }
259    }
260
261    fn key(&self) -> Self::Key {
262        RoleAuthKey {
263            role_id: self.role_id,
264        }
265    }
266}
267
268#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
269pub struct QueryPolicy {
270    pub name: String,
271    pub id: QueryPolicyId,
272    pub oid: u32,
273    pub mode: QueryPolicyMode,
274    pub rules: Vec<QueryPolicyRule>,
275    pub owner_id: RoleId,
276    pub privileges: Vec<MzAclItem>,
277}
278
279impl DurableType for QueryPolicy {
280    type Key = QueryPolicyKey;
281    type Value = QueryPolicyValue;
282
283    fn into_key_value(self) -> (Self::Key, Self::Value) {
284        (
285            QueryPolicyKey { id: self.id },
286            QueryPolicyValue {
287                name: self.name,
288                oid: self.oid,
289                mode: self.mode,
290                rules: self.rules,
291                owner_id: self.owner_id,
292                privileges: self.privileges,
293            },
294        )
295    }
296
297    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
298        Self {
299            id: key.id,
300            name: value.name,
301            oid: value.oid,
302            mode: value.mode,
303            rules: value.rules,
304            owner_id: value.owner_id,
305            privileges: value.privileges,
306        }
307    }
308
309    fn key(&self) -> Self::Key {
310        QueryPolicyKey { id: self.id }
311    }
312}
313
314#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
315pub struct NetworkPolicy {
316    pub name: String,
317    pub id: NetworkPolicyId,
318    pub oid: u32,
319    pub rules: Vec<NetworkPolicyRule>,
320    pub owner_id: RoleId,
321    pub(crate) privileges: Vec<MzAclItem>,
322}
323
324impl DurableType for NetworkPolicy {
325    type Key = NetworkPolicyKey;
326    type Value = NetworkPolicyValue;
327
328    fn into_key_value(self) -> (Self::Key, Self::Value) {
329        (
330            NetworkPolicyKey { id: self.id },
331            NetworkPolicyValue {
332                oid: self.oid,
333                name: self.name,
334                rules: self.rules,
335                owner_id: self.owner_id,
336                privileges: self.privileges,
337            },
338        )
339    }
340
341    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
342        Self {
343            id: key.id,
344            oid: value.oid,
345            name: value.name,
346            rules: value.rules,
347            owner_id: value.owner_id,
348            privileges: value.privileges,
349        }
350    }
351
352    fn key(&self) -> Self::Key {
353        NetworkPolicyKey { id: self.id }
354    }
355}
356
357#[derive(Debug, Clone)]
358pub struct ClusterReplicaSize {
359    pub id: ClusterReplicaSizeId,
360    pub name: String,
361    pub allocation: ReplicaAllocation,
362}
363
364// `ReplicaAllocation` contains a `Numeric`, which is not `Eq` or `Ord`, so
365// compare by the durable representation instead.
366impl PartialEq for ClusterReplicaSize {
367    fn eq(&self, other: &Self) -> bool {
368        self.cmp(other) == Ordering::Equal
369    }
370}
371
372impl Eq for ClusterReplicaSize {}
373
374impl PartialOrd for ClusterReplicaSize {
375    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
376        Some(self.cmp(other))
377    }
378}
379
380impl Ord for ClusterReplicaSize {
381    fn cmp(&self, other: &Self) -> Ordering {
382        self.clone()
383            .into_key_value()
384            .cmp(&other.clone().into_key_value())
385    }
386}
387
388impl DurableType for ClusterReplicaSize {
389    type Key = ClusterReplicaSizeKey;
390    type Value = ClusterReplicaSizeValue;
391
392    fn into_key_value(self) -> (Self::Key, Self::Value) {
393        let ReplicaAllocation {
394            memory_limit,
395            cpu_limit,
396            cpu_request,
397            disk_limit,
398            scale,
399            workers,
400            credits_per_hour,
401            cpu_exclusive,
402            is_cc,
403            family,
404            swap_enabled,
405            disabled,
406            selectors,
407        } = self.allocation;
408        (
409            ClusterReplicaSizeKey { id: self.id },
410            ClusterReplicaSizeValue {
411                name: self.name,
412                memory_limit: memory_limit.map(|m| m.0.as_u64()),
413                cpu_limit: cpu_limit.map(|c| c.as_nanocpus()),
414                cpu_request: cpu_request.map(|c| c.as_nanocpus()),
415                disk_limit: disk_limit.map(|d| d.0.as_u64()),
416                scale: scale.get(),
417                workers: u64::cast_from(workers.get()),
418                credits_per_hour: credits_per_hour.to_string(),
419                cpu_exclusive,
420                is_cc,
421                family,
422                swap_enabled,
423                disabled,
424                selectors,
425            },
426        )
427    }
428
429    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
430        // CpuLimit is stored in millicpus, so nanocpus round-trip exactly.
431        let cpu = |nanocpus: u64| CpuLimit::from_millicpus(usize::cast_from(nanocpus / 1_000_000));
432        Self {
433            id: key.id,
434            name: value.name,
435            allocation: ReplicaAllocation {
436                memory_limit: value.memory_limit.map(|b| MemoryLimit(ByteSize(b))),
437                cpu_limit: value.cpu_limit.map(cpu),
438                cpu_request: value.cpu_request.map(cpu),
439                disk_limit: value.disk_limit.map(|b| DiskLimit(ByteSize(b))),
440                scale: NonZero::new(value.scale).expect("scale is non-zero"),
441                workers: NonZero::new(usize::cast_from(value.workers))
442                    .expect("workers is non-zero"),
443                credits_per_hour: value
444                    .credits_per_hour
445                    .parse()
446                    .expect("credits_per_hour is a valid numeric"),
447                cpu_exclusive: value.cpu_exclusive,
448                is_cc: value.is_cc,
449                family: value.family,
450                swap_enabled: value.swap_enabled,
451                disabled: value.disabled,
452                selectors: value.selectors,
453            },
454        }
455    }
456
457    fn key(&self) -> Self::Key {
458        ClusterReplicaSizeKey { id: self.id }
459    }
460}
461
462#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
463pub struct Cluster {
464    pub id: ClusterId,
465    pub name: String,
466    pub owner_id: RoleId,
467    pub privileges: Vec<MzAclItem>,
468    pub config: ClusterConfig,
469}
470
471impl DurableType for Cluster {
472    type Key = ClusterKey;
473    type Value = ClusterValue;
474
475    fn into_key_value(self) -> (Self::Key, Self::Value) {
476        (
477            ClusterKey { id: self.id },
478            ClusterValue {
479                name: self.name,
480                owner_id: self.owner_id,
481                privileges: self.privileges,
482                config: self.config,
483            },
484        )
485    }
486
487    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
488        Self {
489            id: key.id,
490            name: value.name,
491            owner_id: value.owner_id,
492            privileges: value.privileges,
493            config: value.config,
494        }
495    }
496
497    fn key(&self) -> Self::Key {
498        ClusterKey { id: self.id }
499    }
500}
501
502#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
503pub struct ClusterConfig {
504    pub variant: ClusterVariant,
505    pub workload_class: Option<String>,
506    pub query_policy: Option<QueryPolicyId>,
507}
508
509#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
510pub enum ClusterVariant {
511    Managed(ClusterVariantManaged),
512    Unmanaged,
513}
514
515impl ClusterVariant {
516    /// The replica sizes a managed cluster references: its size, its hydration
517    /// size, an in-progress reconfiguration's target size, and its burst size.
518    pub fn sizes(&self) -> impl Iterator<Item = &str> {
519        let managed = match self {
520            ClusterVariant::Managed(managed) => Some(managed),
521            ClusterVariant::Unmanaged => None,
522        };
523        managed.into_iter().flat_map(|managed| {
524            [
525                Some(&managed.size),
526                managed
527                    .auto_scaling_strategy
528                    .as_ref()
529                    .and_then(|s| s.on_hydration.as_ref())
530                    .map(|h| &h.hydration_size),
531                managed
532                    .reconfiguration
533                    .as_ref()
534                    .filter(|r| r.is_in_progress())
535                    .map(|r| &r.target.size),
536                managed.burst.as_ref().map(|b| &b.burst_size),
537            ]
538            .into_iter()
539            .flatten()
540            .map(String::as_str)
541        })
542    }
543}
544
545#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
546pub struct ClusterVariantManaged {
547    pub size: String,
548    pub availability_zones: Vec<String>,
549    pub logging: ReplicaLogging,
550    /// Whether arrangements on this cluster's replicas request dictionary compression.
551    pub arrangement_compression: bool,
552    pub replication_factor: u32,
553    pub optimizer_feature_overrides: BTreeMap<String, String>,
554    pub schedule: ClusterSchedule,
555    /// User-configured autoscaling policy, distinct from the in-flight runtime
556    /// records below.
557    pub auto_scaling_strategy: Option<AutoScalingStrategy>,
558    /// Latest graceful reconfiguration record, if one has been written.
559    pub reconfiguration: Option<ReconfigurationState>,
560    /// In-flight hydration burst the controller is running.
561    pub burst: Option<BurstState>,
562}
563
564/// The canonical name of the `index`-th (zero-based) replica of a managed
565/// cluster.
566///
567/// A managed cluster's replicas are derived from its `replication_factor`: for a
568/// factor of N they are named `r1` through `rN`.
569///
570/// The catalog-open reconciler that materializes builtin replicas converges on
571/// this rule, `CREATE CLUSTER` names its replicas by it, and the
572/// unmanaged-to-managed conversion validates the existing names against it. The
573/// cluster controller deliberately does not: its `ReplicaNameGen` picks names
574/// that avoid the observed set, which is why it drops by observed id rather
575/// than by derived name.
576pub fn managed_cluster_replica_name(index: u32) -> String {
577    format!("r{}", index + 1)
578}
579
580/// The latest graceful reconfiguration: the config shape the cluster is moving
581/// to or most recently moved toward, plus its deadline and terminal state.
582///
583/// `ALTER` writes this record with [`ReconfigurationStatus::InProgress`] and
584/// returns. The realized config (`cluster.size`, ...) is advanced by the
585/// controller only at cut-over. When the reconfiguration settles, the controller
586/// retains the record with a terminal status so readers can inspect the latest
587/// outcome without reconstructing it from the audit log.
588#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
589pub struct ReconfigurationState {
590    pub target: ReconfigurationTarget,
591    pub deadline: mz_repr::Timestamp,
592    /// The action the controller applies if `deadline` passes before the
593    /// target hydrates. Success takes precedence: a hydrated target cuts over
594    /// regardless of this field.
595    pub on_timeout: OnTimeoutAction,
596    pub status: ReconfigurationStatus,
597}
598
599/// The lifecycle status of the latest graceful reconfiguration.
600#[derive(Clone, Copy, Debug, PartialOrd, PartialEq, Eq, Ord)]
601pub enum ReconfigurationStatus {
602    /// The controller is converging the cluster onto the target shape.
603    InProgress,
604    /// The realized config reached the target shape.
605    Finalized,
606    /// The deadline fired under rollback and the realized config stayed put.
607    TimedOut,
608    /// The user retargeted the reconfiguration back to the realized shape.
609    Cancelled,
610    /// The controller could not create the target replicas within the budget.
611    ResourceExhausted,
612}
613
614impl ReconfigurationState {
615    /// Whether this record should still drive target-replica convergence.
616    pub fn is_in_progress(&self) -> bool {
617        matches!(self.status, ReconfigurationStatus::InProgress)
618    }
619}
620
621/// The full config shape a reconfiguration is moving the cluster to, so a
622/// combined size + replication-factor + availability-zone change is one record.
623#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
624pub struct ReconfigurationTarget {
625    pub size: String,
626    pub replication_factor: u32,
627    pub availability_zones: Vec<String>,
628    pub logging: ReplicaLogging,
629    pub arrangement_compression: bool,
630}
631
632/// An active hydration burst the controller is running.
633#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
634pub struct BurstState {
635    pub burst_size: String,
636    pub linger_duration: Duration,
637    /// Start of the current observed readiness period for the steady set.
638    /// Cleared after a failed readiness check.
639    pub steady_ready_at: Option<mz_repr::Timestamp>,
640}
641
642#[derive(Clone, Debug, Ord, PartialOrd, PartialEq, Eq)]
643pub struct IntrospectionSourceIndex {
644    pub cluster_id: ClusterId,
645    pub name: String,
646    pub item_id: CatalogItemId,
647    pub index_id: GlobalId,
648    pub oid: u32,
649}
650
651impl DurableType for IntrospectionSourceIndex {
652    type Key = ClusterIntrospectionSourceIndexKey;
653    type Value = ClusterIntrospectionSourceIndexValue;
654
655    fn into_key_value(self) -> (Self::Key, Self::Value) {
656        (
657            ClusterIntrospectionSourceIndexKey {
658                cluster_id: self.cluster_id,
659                name: self.name,
660            },
661            ClusterIntrospectionSourceIndexValue {
662                catalog_id: self
663                    .item_id
664                    .try_into()
665                    .expect("cluster introspection source index mapping must be an Introspection Source Index ID"),
666                global_id: self
667                    .index_id
668                    .try_into()
669                    .expect("cluster introspection source index mapping must be a Introspection Source Index ID"),
670                oid: self.oid,
671            },
672        )
673    }
674
675    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
676        Self {
677            cluster_id: key.cluster_id,
678            name: key.name,
679            item_id: value.catalog_id.into(),
680            index_id: value.global_id.into(),
681            oid: value.oid,
682        }
683    }
684
685    fn key(&self) -> Self::Key {
686        ClusterIntrospectionSourceIndexKey {
687            cluster_id: self.cluster_id,
688            name: self.name.clone(),
689        }
690    }
691}
692
693#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
694pub struct ClusterReplica {
695    pub cluster_id: ClusterId,
696    pub replica_id: ReplicaId,
697    pub name: String,
698    pub config: ReplicaConfig,
699    pub owner_id: RoleId,
700}
701
702impl DurableType for ClusterReplica {
703    type Key = ClusterReplicaKey;
704    type Value = ClusterReplicaValue;
705
706    fn into_key_value(self) -> (Self::Key, Self::Value) {
707        (
708            ClusterReplicaKey {
709                id: self.replica_id,
710            },
711            ClusterReplicaValue {
712                cluster_id: self.cluster_id,
713                name: self.name,
714                config: self.config,
715                owner_id: self.owner_id,
716            },
717        )
718    }
719
720    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
721        Self {
722            cluster_id: value.cluster_id,
723            replica_id: key.id,
724            name: value.name,
725            config: value.config,
726            owner_id: value.owner_id,
727        }
728    }
729
730    fn key(&self) -> Self::Key {
731        ClusterReplicaKey {
732            id: self.replica_id,
733        }
734    }
735}
736
737// The on-disk replica configuration does not match the in-memory replica configuration, so we need
738// separate structs. As of writing this comment, it is mainly due to the fact that we don't persist
739// the replica allocation.
740#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
741pub struct ReplicaConfig {
742    pub location: ReplicaLocation,
743    pub logging: ReplicaLogging,
744    pub arrangement_compression: bool,
745}
746
747impl From<mz_controller::clusters::ReplicaConfig> for ReplicaConfig {
748    fn from(config: mz_controller::clusters::ReplicaConfig) -> Self {
749        Self {
750            location: config.location.into(),
751            logging: config.compute.logging,
752            arrangement_compression: config.compute.arrangement_compression,
753        }
754    }
755}
756
757#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
758pub enum ReplicaLocation {
759    Unmanaged {
760        storagectl_addrs: Vec<String>,
761        computectl_addrs: Vec<String>,
762    },
763    Managed {
764        size: String,
765        /// The availability zones the replica was provisioned under.
766        ///
767        /// For a replica of a managed cluster this is the cluster's
768        /// `AVAILABILITY ZONES` pool at provision time; the cluster controller
769        /// compares it against a cluster's target `availability_zones` to tell
770        /// realized- from target-shape replicas (including an
771        /// `AVAILABILITY ZONES` divergence). For a replica of an unmanaged
772        /// cluster it is the user-pinned `AVAILABILITY ZONE`, as a zero- or
773        /// one-element list. Empty when no zones constrain placement.
774        availability_zones: Vec<String>,
775        internal: bool,
776        billed_as: Option<String>,
777        pending: bool,
778    },
779}
780
781impl ReplicaLocation {
782    /// The replica size of a managed location.
783    pub fn size(&self) -> Option<&str> {
784        match self {
785            ReplicaLocation::Managed { size, .. } => Some(size),
786            ReplicaLocation::Unmanaged { .. } => None,
787        }
788    }
789}
790
791impl From<mz_controller::clusters::ReplicaLocation> for ReplicaLocation {
792    fn from(loc: mz_controller::clusters::ReplicaLocation) -> Self {
793        match loc {
794            mz_controller::clusters::ReplicaLocation::Unmanaged(
795                mz_controller::clusters::UnmanagedReplicaLocation {
796                    storagectl_addrs,
797                    computectl_addrs,
798                },
799            ) => Self::Unmanaged {
800                storagectl_addrs,
801                computectl_addrs,
802            },
803            mz_controller::clusters::ReplicaLocation::Managed(
804                mz_controller::clusters::ManagedReplicaLocation {
805                    allocation: _,
806                    size,
807                    availability_zones,
808                    billed_as,
809                    internal,
810                    pending,
811                },
812            ) => ReplicaLocation::Managed {
813                size,
814                availability_zones,
815                internal,
816                billed_as,
817                pending,
818            },
819        }
820    }
821}
822
823#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
824pub struct Item {
825    pub id: CatalogItemId,
826    pub oid: u32,
827    pub global_id: GlobalId,
828    pub schema_id: SchemaId,
829    pub name: String,
830    pub create_sql: String,
831    pub owner_id: RoleId,
832    pub privileges: Vec<MzAclItem>,
833    pub extra_versions: BTreeMap<RelationVersion, GlobalId>,
834    /// `Some(uuid)` marks a temporary item owned by, and only visible to, the
835    /// session with that UUID. `None` is a normal durable item.
836    pub ephemeral_owner_session: Option<Uuid>,
837}
838
839impl Item {
840    pub fn item_type(&self) -> CatalogItemType {
841        item_type(&self.create_sql)
842    }
843}
844
845/// The columns of a relation item as planning resolved them. Written with
846/// every change to the item's definition and refreshed at bootstrap, so that
847/// catalog views can report columns without the planner.
848#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
849pub struct ItemColumns {
850    pub id: CatalogItemId,
851    /// In position order: a column's 0-based position, which `mz_columns` and
852    /// column comments refer to, is its index here.
853    pub columns: Vec<ItemColumn>,
854}
855
856impl DurableType for ItemColumns {
857    type Key = ItemColumnsKey;
858    type Value = ItemColumnsValue;
859
860    fn into_key_value(self) -> (Self::Key, Self::Value) {
861        (
862            ItemColumnsKey { id: self.id },
863            ItemColumnsValue {
864                columns: self.columns,
865            },
866        )
867    }
868
869    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
870        Self {
871            id: key.id,
872            columns: value.columns,
873        }
874    }
875
876    fn key(&self) -> Self::Key {
877        ItemColumnsKey { id: self.id }
878    }
879}
880
881/// A column of a relation item. See [`ItemColumns`].
882#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
883#[cfg_attr(test, derive(Arbitrary))]
884pub struct ItemColumn {
885    pub name: ColumnName,
886    pub nullable: bool,
887    pub type_oid: u32,
888    pub type_mod: i32,
889    pub custom_type: Option<CatalogItemId>,
890}
891
892/// The keys of an index item, as planning resolved them. Maintained like
893/// [`ItemColumns`].
894#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
895pub struct IndexColumns {
896    pub id: CatalogItemId,
897    /// In key order.
898    pub columns: Vec<IndexColumn>,
899}
900
901impl DurableType for IndexColumns {
902    type Key = IndexColumnsKey;
903    type Value = IndexColumnsValue;
904
905    fn into_key_value(self) -> (Self::Key, Self::Value) {
906        (
907            IndexColumnsKey { id: self.id },
908            IndexColumnsValue {
909                columns: self.columns,
910            },
911        )
912    }
913
914    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
915        Self {
916            id: key.id,
917            columns: value.columns,
918        }
919    }
920
921    fn key(&self) -> Self::Key {
922        IndexColumnsKey { id: self.id }
923    }
924}
925
926/// A key of an index. See [`IndexColumns`].
927#[derive(Debug, Clone, Copy, Ord, PartialOrd, PartialEq, Eq)]
928#[cfg_attr(test, derive(Arbitrary))]
929pub struct IndexColumn {
930    /// The 0-based position of the relation's column the index is on.
931    /// `None` when the key is an expression rather than a column reference.
932    pub column: Option<usize>,
933    /// Whether the key can evaluate to `NULL`.
934    pub nullable: bool,
935}
936
937/// The planner-resolved metadata the durable catalog records for an item
938#[derive(Debug, Clone, Default, PartialEq, Eq)]
939pub struct ItemMetadata {
940    /// The columns of a relation
941    pub columns: Vec<ItemColumn>,
942    /// The keys of an index
943    pub index_columns: Vec<IndexColumn>,
944}
945
946impl DurableType for Item {
947    type Key = ItemKey;
948    type Value = ItemValue;
949
950    fn into_key_value(self) -> (Self::Key, Self::Value) {
951        (
952            ItemKey { id: self.id },
953            ItemValue {
954                oid: self.oid,
955                global_id: self.global_id,
956                schema_id: self.schema_id,
957                name: self.name,
958                create_sql: self.create_sql,
959                owner_id: self.owner_id,
960                privileges: self.privileges,
961                extra_versions: self.extra_versions,
962                ephemeral_owner_session: self.ephemeral_owner_session,
963            },
964        )
965    }
966
967    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
968        Self {
969            id: key.id,
970            oid: value.oid,
971            global_id: value.global_id,
972            schema_id: value.schema_id,
973            name: value.name,
974            create_sql: value.create_sql,
975            owner_id: value.owner_id,
976            privileges: value.privileges,
977            extra_versions: value.extra_versions,
978            ephemeral_owner_session: value.ephemeral_owner_session,
979        }
980    }
981
982    fn key(&self) -> Self::Key {
983        ItemKey { id: self.id }
984    }
985}
986
987#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
988pub struct SourceReferences {
989    pub source_id: CatalogItemId,
990    pub updated_at: u64,
991    pub references: Vec<SourceReference>,
992}
993
994#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
995#[cfg_attr(test, derive(Arbitrary))]
996pub struct SourceReference {
997    pub name: String,
998    pub namespace: Option<String>,
999    pub columns: Vec<String>,
1000}
1001
1002impl DurableType for SourceReferences {
1003    type Key = SourceReferencesKey;
1004    type Value = SourceReferencesValue;
1005
1006    fn into_key_value(self) -> (Self::Key, Self::Value) {
1007        (
1008            SourceReferencesKey {
1009                source_id: self.source_id,
1010            },
1011            SourceReferencesValue {
1012                updated_at: self.updated_at,
1013                references: self.references,
1014            },
1015        )
1016    }
1017
1018    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1019        Self {
1020            source_id: key.source_id,
1021            updated_at: value.updated_at,
1022            references: value.references,
1023        }
1024    }
1025
1026    fn key(&self) -> Self::Key {
1027        SourceReferencesKey {
1028            source_id: self.source_id,
1029        }
1030    }
1031}
1032
1033/// A newtype wrapper for [`CatalogItemId`] that is only for the "system" namespace.
1034#[derive(Debug, Copy, Clone, Ord, PartialOrd, PartialEq, Eq)]
1035pub struct SystemCatalogItemId(u64);
1036
1037impl TryFrom<CatalogItemId> for SystemCatalogItemId {
1038    type Error = &'static str;
1039
1040    fn try_from(val: CatalogItemId) -> Result<Self, Self::Error> {
1041        match val {
1042            CatalogItemId::System(x) => Ok(SystemCatalogItemId(x)),
1043            CatalogItemId::IntrospectionSourceIndex(_) => Err("introspection_source_index"),
1044            CatalogItemId::User(_) => Err("user"),
1045            CatalogItemId::Transient(_) => Err("transient"),
1046        }
1047    }
1048}
1049
1050impl From<SystemCatalogItemId> for CatalogItemId {
1051    fn from(val: SystemCatalogItemId) -> Self {
1052        CatalogItemId::System(val.0)
1053    }
1054}
1055
1056/// A newtype wrapper for [`CatalogItemId`] that is only for the "introspection source index" namespace.
1057#[derive(Debug, Copy, Clone, Ord, PartialOrd, PartialEq, Eq)]
1058pub struct IntrospectionSourceIndexCatalogItemId(u64);
1059
1060impl TryFrom<CatalogItemId> for IntrospectionSourceIndexCatalogItemId {
1061    type Error = &'static str;
1062
1063    fn try_from(val: CatalogItemId) -> Result<Self, Self::Error> {
1064        match val {
1065            CatalogItemId::System(_) => Err("system"),
1066            CatalogItemId::IntrospectionSourceIndex(x) => {
1067                Ok(IntrospectionSourceIndexCatalogItemId(x))
1068            }
1069            CatalogItemId::User(_) => Err("user"),
1070            CatalogItemId::Transient(_) => Err("transient"),
1071        }
1072    }
1073}
1074
1075impl From<IntrospectionSourceIndexCatalogItemId> for CatalogItemId {
1076    fn from(val: IntrospectionSourceIndexCatalogItemId) -> Self {
1077        CatalogItemId::IntrospectionSourceIndex(val.0)
1078    }
1079}
1080
1081/// A newtype wrapper for [`GlobalId`] that is only for the "system" namespace.
1082#[derive(Debug, Copy, Clone, Ord, PartialOrd, PartialEq, Eq)]
1083pub struct SystemGlobalId(u64);
1084
1085impl TryFrom<GlobalId> for SystemGlobalId {
1086    type Error = &'static str;
1087
1088    fn try_from(val: GlobalId) -> Result<Self, Self::Error> {
1089        match val {
1090            GlobalId::System(x) => Ok(SystemGlobalId(x)),
1091            GlobalId::IntrospectionSourceIndex(_) => Err("introspection_source_index"),
1092            GlobalId::User(_) => Err("user"),
1093            GlobalId::Transient(_) => Err("transient"),
1094            GlobalId::Explain => Err("explain"),
1095        }
1096    }
1097}
1098
1099impl From<SystemGlobalId> for GlobalId {
1100    fn from(val: SystemGlobalId) -> Self {
1101        GlobalId::System(val.0)
1102    }
1103}
1104
1105/// A newtype wrapper for [`GlobalId`] that is only for the "introspection source index" namespace.
1106#[derive(Debug, Copy, Clone, Ord, PartialOrd, PartialEq, Eq)]
1107pub struct IntrospectionSourceIndexGlobalId(u64);
1108
1109impl TryFrom<GlobalId> for IntrospectionSourceIndexGlobalId {
1110    type Error = &'static str;
1111
1112    fn try_from(val: GlobalId) -> Result<Self, Self::Error> {
1113        match val {
1114            GlobalId::System(_) => Err("system"),
1115            GlobalId::IntrospectionSourceIndex(x) => Ok(IntrospectionSourceIndexGlobalId(x)),
1116            GlobalId::User(_) => Err("user"),
1117            GlobalId::Transient(_) => Err("transient"),
1118            GlobalId::Explain => Err("explain"),
1119        }
1120    }
1121}
1122
1123impl From<IntrospectionSourceIndexGlobalId> for GlobalId {
1124    fn from(val: IntrospectionSourceIndexGlobalId) -> Self {
1125        GlobalId::IntrospectionSourceIndex(val.0)
1126    }
1127}
1128
1129#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
1130pub struct SystemObjectDescription {
1131    pub schema_name: String,
1132    pub object_type: CatalogItemType,
1133    pub object_name: String,
1134}
1135
1136#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1137pub struct SystemObjectUniqueIdentifier {
1138    pub catalog_id: CatalogItemId,
1139    pub global_id: GlobalId,
1140    pub fingerprint: String,
1141}
1142
1143impl SystemObjectUniqueIdentifier {
1144    pub fn runtime_alterable(&self) -> bool {
1145        self.fingerprint == RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL
1146    }
1147}
1148
1149/// Functions can share the same name as any other catalog item type
1150/// within a given schema.
1151/// For example, a function can have the same name as a type, e.g.
1152/// 'date'.
1153/// As such, system objects are keyed in the catalog storage by the
1154/// tuple (schema_name, object_type, object_name), which is guaranteed
1155/// to be unique.
1156#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1157pub struct SystemObjectMapping {
1158    pub description: SystemObjectDescription,
1159    pub unique_identifier: SystemObjectUniqueIdentifier,
1160}
1161
1162impl DurableType for SystemObjectMapping {
1163    type Key = GidMappingKey;
1164    type Value = GidMappingValue;
1165
1166    fn into_key_value(self) -> (Self::Key, Self::Value) {
1167        (
1168            GidMappingKey {
1169                schema_name: self.description.schema_name,
1170                object_type: self.description.object_type,
1171                object_name: self.description.object_name,
1172            },
1173            GidMappingValue {
1174                catalog_id: self
1175                    .unique_identifier
1176                    .catalog_id
1177                    .try_into()
1178                    .expect("catalog_id to be in the system namespace"),
1179                global_id: self
1180                    .unique_identifier
1181                    .global_id
1182                    .try_into()
1183                    .expect("collection_id to be in the system namespace"),
1184                fingerprint: self.unique_identifier.fingerprint,
1185            },
1186        )
1187    }
1188
1189    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1190        Self {
1191            description: SystemObjectDescription {
1192                schema_name: key.schema_name,
1193                object_type: key.object_type,
1194                object_name: key.object_name,
1195            },
1196            unique_identifier: SystemObjectUniqueIdentifier {
1197                catalog_id: value.catalog_id.into(),
1198                global_id: value.global_id.into(),
1199                fingerprint: value.fingerprint,
1200            },
1201        }
1202    }
1203
1204    fn key(&self) -> Self::Key {
1205        GidMappingKey {
1206            schema_name: self.description.schema_name.clone(),
1207            object_type: self.description.object_type.clone(),
1208            object_name: self.description.object_name.clone(),
1209        }
1210    }
1211}
1212
1213#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1214pub struct DefaultPrivilege {
1215    pub object: DefaultPrivilegeObject,
1216    pub acl_item: DefaultPrivilegeAclItem,
1217}
1218
1219impl DurableType for DefaultPrivilege {
1220    type Key = DefaultPrivilegesKey;
1221    type Value = DefaultPrivilegesValue;
1222
1223    fn into_key_value(self) -> (Self::Key, Self::Value) {
1224        (
1225            DefaultPrivilegesKey {
1226                role_id: self.object.role_id,
1227                database_id: self.object.database_id,
1228                schema_id: self.object.schema_id,
1229                object_type: self.object.object_type,
1230                grantee: self.acl_item.grantee,
1231            },
1232            DefaultPrivilegesValue {
1233                privileges: self.acl_item.acl_mode,
1234            },
1235        )
1236    }
1237
1238    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1239        Self {
1240            object: DefaultPrivilegeObject {
1241                role_id: key.role_id,
1242                database_id: key.database_id,
1243                schema_id: key.schema_id,
1244                object_type: key.object_type,
1245            },
1246            acl_item: DefaultPrivilegeAclItem {
1247                grantee: key.grantee,
1248                acl_mode: value.privileges,
1249            },
1250        }
1251    }
1252
1253    fn key(&self) -> Self::Key {
1254        DefaultPrivilegesKey {
1255            role_id: self.object.role_id,
1256            database_id: self.object.database_id,
1257            schema_id: self.object.schema_id,
1258            object_type: self.object.object_type,
1259            grantee: self.acl_item.grantee,
1260        }
1261    }
1262}
1263
1264#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1265pub struct Comment {
1266    pub object_id: CommentObjectId,
1267    pub sub_component: Option<usize>,
1268    pub comment: String,
1269}
1270
1271impl DurableType for Comment {
1272    type Key = CommentKey;
1273    type Value = CommentValue;
1274
1275    fn into_key_value(self) -> (Self::Key, Self::Value) {
1276        (
1277            CommentKey {
1278                object_id: self.object_id,
1279                sub_component: self.sub_component,
1280            },
1281            CommentValue {
1282                comment: self.comment,
1283            },
1284        )
1285    }
1286
1287    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1288        Self {
1289            object_id: key.object_id,
1290            sub_component: key.sub_component,
1291            comment: value.comment,
1292        }
1293    }
1294
1295    fn key(&self) -> Self::Key {
1296        CommentKey {
1297            object_id: self.object_id,
1298            sub_component: self.sub_component,
1299        }
1300    }
1301}
1302
1303#[derive(Debug, Clone, PartialEq, Eq)]
1304pub struct IdAlloc {
1305    pub name: String,
1306    pub next_id: u64,
1307}
1308
1309impl DurableType for IdAlloc {
1310    type Key = IdAllocKey;
1311    type Value = IdAllocValue;
1312
1313    fn into_key_value(self) -> (Self::Key, Self::Value) {
1314        (
1315            IdAllocKey { name: self.name },
1316            IdAllocValue {
1317                next_id: self.next_id,
1318            },
1319        )
1320    }
1321
1322    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1323        Self {
1324            name: key.name,
1325            next_id: value.next_id,
1326        }
1327    }
1328
1329    fn key(&self) -> Self::Key {
1330        IdAllocKey {
1331            name: self.name.clone(),
1332        }
1333    }
1334}
1335
1336#[derive(Debug, Clone, PartialEq, Eq)]
1337pub struct Config {
1338    pub key: String,
1339    pub value: u64,
1340}
1341
1342impl DurableType for Config {
1343    type Key = ConfigKey;
1344    type Value = ConfigValue;
1345
1346    fn into_key_value(self) -> (Self::Key, Self::Value) {
1347        (
1348            ConfigKey { key: self.key },
1349            ConfigValue { value: self.value },
1350        )
1351    }
1352
1353    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1354        Self {
1355            key: key.key,
1356            value: value.value,
1357        }
1358    }
1359
1360    fn key(&self) -> Self::Key {
1361        ConfigKey {
1362            key: self.key.clone(),
1363        }
1364    }
1365}
1366
1367#[derive(Debug, Clone)]
1368pub struct Setting {
1369    pub name: String,
1370    pub value: String,
1371}
1372
1373impl DurableType for Setting {
1374    type Key = SettingKey;
1375    type Value = SettingValue;
1376
1377    fn into_key_value(self) -> (Self::Key, Self::Value) {
1378        (
1379            SettingKey { name: self.name },
1380            SettingValue { value: self.value },
1381        )
1382    }
1383
1384    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1385        Self {
1386            name: key.name,
1387            value: value.value,
1388        }
1389    }
1390
1391    fn key(&self) -> Self::Key {
1392        SettingKey {
1393            name: self.name.clone(),
1394        }
1395    }
1396}
1397
1398#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1399pub struct SystemConfiguration {
1400    pub name: String,
1401    pub value: String,
1402}
1403
1404impl DurableType for SystemConfiguration {
1405    type Key = ServerConfigurationKey;
1406    type Value = ServerConfigurationValue;
1407
1408    fn into_key_value(self) -> (Self::Key, Self::Value) {
1409        (
1410            ServerConfigurationKey { name: self.name },
1411            ServerConfigurationValue { value: self.value },
1412        )
1413    }
1414
1415    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1416        Self {
1417            name: key.name,
1418            value: value.value,
1419        }
1420    }
1421
1422    fn key(&self) -> Self::Key {
1423        ServerConfigurationKey {
1424            name: self.name.clone(),
1425        }
1426    }
1427}
1428
1429/// A single cluster-coherent scoped system-parameter override: parameter `name`
1430/// has value `value` on the cluster `cluster_id`.
1431///
1432/// This is the in-memory shape of the durable `cluster_system_configurations`
1433/// collection that backs cluster-coherent scoped feature flags. The collection
1434/// — keyed by `(ClusterId, name)` — is the analog of `system_configurations`
1435/// (`ALTER SYSTEM`), but for per-cluster values; it is written solely by the
1436/// system-parameter sync loop, and the coordinator's in-memory working copy is
1437/// maintained from it on every catalog update.
1438#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1439pub struct ClusterSystemConfiguration {
1440    pub cluster_id: ClusterId,
1441    pub name: String,
1442    pub value: String,
1443}
1444
1445impl DurableType for ClusterSystemConfiguration {
1446    type Key = ClusterSystemConfigurationKey;
1447    type Value = ClusterSystemConfigurationValue;
1448
1449    fn into_key_value(self) -> (Self::Key, Self::Value) {
1450        (
1451            ClusterSystemConfigurationKey {
1452                cluster_id: self.cluster_id,
1453                name: self.name,
1454            },
1455            ClusterSystemConfigurationValue { value: self.value },
1456        )
1457    }
1458
1459    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1460        Self {
1461            cluster_id: key.cluster_id,
1462            name: key.name,
1463            value: value.value,
1464        }
1465    }
1466
1467    fn key(&self) -> Self::Key {
1468        ClusterSystemConfigurationKey {
1469            cluster_id: self.cluster_id,
1470            name: self.name.clone(),
1471        }
1472    }
1473}
1474
1475/// A single replica-local scoped system-parameter override: parameter `name`
1476/// has value `value` on the replica `replica_id`.
1477///
1478/// This is the in-memory shape of the durable `replica_system_configurations`
1479/// collection that backs replica-local scoped feature flags. The collection —
1480/// keyed by `(ReplicaId, name)` — is the analog of `system_configurations`
1481/// (`ALTER SYSTEM`), but for per-replica values; it is written solely by the
1482/// system-parameter sync loop, and the coordinator's in-memory working copy is
1483/// maintained from it on every catalog update.
1484#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1485pub struct ReplicaSystemConfiguration {
1486    pub replica_id: ReplicaId,
1487    pub name: String,
1488    pub value: String,
1489}
1490
1491impl DurableType for ReplicaSystemConfiguration {
1492    type Key = ReplicaSystemConfigurationKey;
1493    type Value = ReplicaSystemConfigurationValue;
1494
1495    fn into_key_value(self) -> (Self::Key, Self::Value) {
1496        (
1497            ReplicaSystemConfigurationKey {
1498                replica_id: self.replica_id,
1499                name: self.name,
1500            },
1501            ReplicaSystemConfigurationValue { value: self.value },
1502        )
1503    }
1504
1505    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1506        Self {
1507            replica_id: key.replica_id,
1508            name: key.name,
1509            value: value.value,
1510        }
1511    }
1512
1513    fn key(&self) -> Self::Key {
1514        ReplicaSystemConfigurationKey {
1515            replica_id: self.replica_id,
1516            name: self.name.clone(),
1517        }
1518    }
1519}
1520
1521impl DurableType for MzAclItem {
1522    type Key = SystemPrivilegesKey;
1523    type Value = SystemPrivilegesValue;
1524
1525    fn into_key_value(self) -> (Self::Key, Self::Value) {
1526        (
1527            SystemPrivilegesKey {
1528                grantee: self.grantee,
1529                grantor: self.grantor,
1530            },
1531            SystemPrivilegesValue {
1532                acl_mode: self.acl_mode,
1533            },
1534        )
1535    }
1536
1537    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1538        Self {
1539            grantee: key.grantee,
1540            grantor: key.grantor,
1541            acl_mode: value.acl_mode,
1542        }
1543    }
1544
1545    fn key(&self) -> Self::Key {
1546        SystemPrivilegesKey {
1547            grantee: self.grantee,
1548            grantor: self.grantor,
1549        }
1550    }
1551}
1552
1553#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1554pub struct AuditLog {
1555    pub event: VersionedEvent,
1556}
1557
1558impl DurableType for AuditLog {
1559    type Key = AuditLogKey;
1560    type Value = ();
1561
1562    fn into_key_value(self) -> (Self::Key, Self::Value) {
1563        (AuditLogKey { event: self.event }, ())
1564    }
1565
1566    fn from_key_value(key: Self::Key, _value: Self::Value) -> Self {
1567        Self { event: key.event }
1568    }
1569
1570    fn key(&self) -> Self::Key {
1571        AuditLogKey {
1572            event: self.event.clone(),
1573        }
1574    }
1575}
1576
1577#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1578pub struct StorageCollectionMetadata {
1579    pub id: GlobalId,
1580    pub shard: ShardId,
1581}
1582
1583impl DurableType for StorageCollectionMetadata {
1584    type Key = StorageCollectionMetadataKey;
1585    type Value = StorageCollectionMetadataValue;
1586
1587    fn into_key_value(self) -> (Self::Key, Self::Value) {
1588        (
1589            StorageCollectionMetadataKey { id: self.id },
1590            StorageCollectionMetadataValue { shard: self.shard },
1591        )
1592    }
1593
1594    fn from_key_value(key: Self::Key, value: Self::Value) -> Self {
1595        Self {
1596            id: key.id,
1597            shard: value.shard,
1598        }
1599    }
1600
1601    fn key(&self) -> Self::Key {
1602        StorageCollectionMetadataKey { id: self.id }
1603    }
1604}
1605
1606#[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)]
1607pub struct UnfinalizedShard {
1608    pub shard: ShardId,
1609}
1610
1611impl DurableType for UnfinalizedShard {
1612    type Key = UnfinalizedShardKey;
1613    type Value = ();
1614
1615    fn into_key_value(self) -> (Self::Key, Self::Value) {
1616        (UnfinalizedShardKey { shard: self.shard }, ())
1617    }
1618
1619    fn from_key_value(key: Self::Key, _value: Self::Value) -> Self {
1620        Self { shard: key.shard }
1621    }
1622
1623    fn key(&self) -> Self::Key {
1624        UnfinalizedShardKey {
1625            shard: self.shard.clone(),
1626        }
1627    }
1628}
1629
1630// Structs used internally to represent on-disk state.
1631
1632/// A snapshot of the current on-disk state.
1633#[derive(Debug, Clone, PartialEq, Eq, Default)]
1634pub struct Snapshot {
1635    pub databases: BTreeMap<proto::DatabaseKey, proto::DatabaseValue>,
1636    pub schemas: BTreeMap<proto::SchemaKey, proto::SchemaValue>,
1637    pub roles: BTreeMap<proto::RoleKey, proto::RoleValue>,
1638    pub role_auth: BTreeMap<proto::RoleAuthKey, proto::RoleAuthValue>,
1639    pub items: BTreeMap<proto::ItemKey, proto::ItemValue>,
1640    pub item_columns: BTreeMap<proto::ItemColumnsKey, proto::ItemColumnsValue>,
1641    pub index_columns: BTreeMap<proto::IndexColumnsKey, proto::IndexColumnsValue>,
1642    pub comments: BTreeMap<proto::CommentKey, proto::CommentValue>,
1643    pub clusters: BTreeMap<proto::ClusterKey, proto::ClusterValue>,
1644    pub network_policies: BTreeMap<proto::NetworkPolicyKey, proto::NetworkPolicyValue>,
1645    pub cluster_replica_sizes:
1646        BTreeMap<proto::ClusterReplicaSizeKey, proto::ClusterReplicaSizeValue>,
1647    pub query_policies: BTreeMap<proto::QueryPolicyKey, proto::QueryPolicyValue>,
1648    pub cluster_replicas: BTreeMap<proto::ClusterReplicaKey, proto::ClusterReplicaValue>,
1649    pub introspection_sources: BTreeMap<
1650        proto::ClusterIntrospectionSourceIndexKey,
1651        proto::ClusterIntrospectionSourceIndexValue,
1652    >,
1653    pub id_allocator: BTreeMap<proto::IdAllocKey, proto::IdAllocValue>,
1654    pub configs: BTreeMap<proto::ConfigKey, proto::ConfigValue>,
1655    pub settings: BTreeMap<proto::SettingKey, proto::SettingValue>,
1656    pub system_object_mappings: BTreeMap<proto::GidMappingKey, proto::GidMappingValue>,
1657    pub system_configurations:
1658        BTreeMap<proto::ServerConfigurationKey, proto::ServerConfigurationValue>,
1659    pub cluster_system_configurations:
1660        BTreeMap<proto::ClusterSystemConfigurationKey, proto::ClusterSystemConfigurationValue>,
1661    pub replica_system_configurations:
1662        BTreeMap<proto::ReplicaSystemConfigurationKey, proto::ReplicaSystemConfigurationValue>,
1663    pub default_privileges: BTreeMap<proto::DefaultPrivilegesKey, proto::DefaultPrivilegesValue>,
1664    pub source_references: BTreeMap<proto::SourceReferencesKey, proto::SourceReferencesValue>,
1665    pub system_privileges: BTreeMap<proto::SystemPrivilegesKey, proto::SystemPrivilegesValue>,
1666    pub storage_collection_metadata:
1667        BTreeMap<proto::StorageCollectionMetadataKey, proto::StorageCollectionMetadataValue>,
1668    pub unfinalized_shards: BTreeMap<proto::UnfinalizedShardKey, ()>,
1669    pub txn_wal_shard: BTreeMap<(), proto::TxnWalShardValue>,
1670}
1671
1672impl Snapshot {
1673    pub fn empty() -> Snapshot {
1674        Snapshot::default()
1675    }
1676}
1677
1678/// Token used to fence out other processes.
1679///
1680/// Every time a new process takes over, the `epoch` should be incremented.
1681/// Every time a new version is deployed, the `deploy` generation should be incremented.
1682#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1683#[cfg_attr(test, derive(Arbitrary))]
1684pub struct FenceToken {
1685    pub(crate) deploy_generation: u64,
1686    pub(crate) epoch: Epoch,
1687}
1688
1689impl PartialOrd for FenceToken {
1690    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1691        Some(self.cmp(other))
1692    }
1693}
1694
1695impl Ord for FenceToken {
1696    fn cmp(&self, other: &Self) -> Ordering {
1697        self.deploy_generation
1698            .cmp(&other.deploy_generation)
1699            .then(self.epoch.cmp(&other.epoch))
1700    }
1701}
1702
1703#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1704pub struct SettingKey {
1705    pub(crate) name: String,
1706}
1707
1708#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
1709pub struct SettingValue {
1710    pub(crate) value: String,
1711}
1712
1713#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1714pub struct IdAllocKey {
1715    pub(crate) name: String,
1716}
1717
1718#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
1719pub struct IdAllocValue {
1720    pub(crate) next_id: u64,
1721}
1722
1723#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1724pub struct GidMappingKey {
1725    pub(crate) schema_name: String,
1726    pub(crate) object_type: CatalogItemType,
1727    pub(crate) object_name: String,
1728}
1729
1730#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
1731pub struct GidMappingValue {
1732    pub(crate) catalog_id: SystemCatalogItemId,
1733    pub(crate) global_id: SystemGlobalId,
1734    pub(crate) fingerprint: String,
1735}
1736
1737#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1738pub struct ClusterKey {
1739    pub(crate) id: ClusterId,
1740}
1741
1742#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
1743pub struct ClusterValue {
1744    pub(crate) name: String,
1745    pub(crate) owner_id: RoleId,
1746    pub(crate) privileges: Vec<MzAclItem>,
1747    pub(crate) config: ClusterConfig,
1748}
1749
1750#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1751pub struct ClusterIntrospectionSourceIndexKey {
1752    pub(crate) cluster_id: ClusterId,
1753    pub(crate) name: String,
1754}
1755
1756#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
1757pub struct ClusterIntrospectionSourceIndexValue {
1758    pub(crate) catalog_id: IntrospectionSourceIndexCatalogItemId,
1759    pub(crate) global_id: IntrospectionSourceIndexGlobalId,
1760    pub(crate) oid: u32,
1761}
1762
1763#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1764pub struct ClusterReplicaKey {
1765    pub(crate) id: ReplicaId,
1766}
1767
1768#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
1769pub struct ClusterReplicaValue {
1770    pub(crate) cluster_id: ClusterId,
1771    pub(crate) name: String,
1772    pub(crate) config: ReplicaConfig,
1773    pub(crate) owner_id: RoleId,
1774}
1775
1776#[derive(Clone, Copy, Debug, PartialOrd, PartialEq, Eq, Ord, Hash)]
1777#[cfg_attr(test, derive(Arbitrary))]
1778pub struct DatabaseKey {
1779    pub(crate) id: DatabaseId,
1780}
1781
1782#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1783#[cfg_attr(test, derive(Arbitrary))]
1784pub struct DatabaseValue {
1785    pub(crate) name: String,
1786    pub(crate) owner_id: RoleId,
1787    pub(crate) privileges: Vec<MzAclItem>,
1788    pub(crate) oid: u32,
1789}
1790
1791#[derive(Clone, Copy, Debug, PartialOrd, PartialEq, Eq, Ord, Hash)]
1792#[cfg_attr(test, derive(Arbitrary))]
1793pub struct SourceReferencesKey {
1794    pub(crate) source_id: CatalogItemId,
1795}
1796
1797#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1798#[cfg_attr(test, derive(Arbitrary))]
1799pub struct SourceReferencesValue {
1800    pub(crate) references: Vec<SourceReference>,
1801    pub(crate) updated_at: u64,
1802}
1803
1804#[derive(Clone, Copy, Debug, PartialOrd, PartialEq, Eq, Ord, Hash)]
1805#[cfg_attr(test, derive(Arbitrary))]
1806pub struct SchemaKey {
1807    pub(crate) id: SchemaId,
1808}
1809
1810#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1811#[cfg_attr(test, derive(Arbitrary))]
1812pub struct SchemaValue {
1813    pub(crate) database_id: Option<DatabaseId>,
1814    pub(crate) name: String,
1815    pub(crate) owner_id: RoleId,
1816    pub(crate) privileges: Vec<MzAclItem>,
1817    pub(crate) oid: u32,
1818}
1819
1820#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Hash, Debug)]
1821#[cfg_attr(test, derive(Arbitrary))]
1822pub struct ItemKey {
1823    pub(crate) id: CatalogItemId,
1824}
1825
1826#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1827#[cfg_attr(test, derive(Arbitrary))]
1828pub struct ItemValue {
1829    pub(crate) schema_id: SchemaId,
1830    pub(crate) name: String,
1831    pub(crate) create_sql: String,
1832    pub(crate) owner_id: RoleId,
1833    pub(crate) privileges: Vec<MzAclItem>,
1834    pub(crate) oid: u32,
1835    pub(crate) global_id: GlobalId,
1836    pub(crate) extra_versions: BTreeMap<RelationVersion, GlobalId>,
1837    #[cfg_attr(test, proptest(strategy = "proptest::option::of(any_uuid())"))]
1838    pub(crate) ephemeral_owner_session: Option<Uuid>,
1839}
1840
1841impl ItemValue {
1842    pub fn item_type(&self) -> CatalogItemType {
1843        item_type(&self.create_sql)
1844    }
1845}
1846
1847pub fn item_type(create_sql: &str) -> CatalogItemType {
1848    // NOTE(benesch): the implementation of this method is hideous, but is
1849    // there a better alternative? Storing the object type alongside the
1850    // `create_sql` would introduce the possibility of skew.
1851    let mut tokens = create_sql.split_whitespace();
1852    assert_eq!(tokens.next(), Some("CREATE"));
1853
1854    // Read away item type modifiers, if any.
1855    let next_token = match tokens.next() {
1856        Some("TEMPORARY") | Some("REPLACEMENT") => tokens.next(),
1857        token => token,
1858    };
1859
1860    match next_token {
1861        Some("TABLE") => CatalogItemType::Table,
1862        Some("SOURCE") | Some("SUBSOURCE") => CatalogItemType::Source,
1863        Some("SINK") => CatalogItemType::Sink,
1864        Some("VIEW") => CatalogItemType::View,
1865        Some("MATERIALIZED") => {
1866            assert_eq!(tokens.next(), Some("VIEW"));
1867            CatalogItemType::MaterializedView
1868        }
1869        Some("METRIC") => {
1870            assert_eq!(tokens.next(), Some("SINK"));
1871            CatalogItemType::MetricSink
1872        }
1873        Some("INDEX") => CatalogItemType::Index,
1874        Some("TYPE") => CatalogItemType::Type,
1875        Some("FUNCTION") => CatalogItemType::Func,
1876        Some("SECRET") => CatalogItemType::Secret,
1877        Some("CONNECTION") => CatalogItemType::Connection,
1878        _ => panic!("unexpected create sql: {}", create_sql),
1879    }
1880}
1881
1882#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1883pub struct ItemColumnsKey {
1884    pub(crate) id: CatalogItemId,
1885}
1886
1887#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1888#[cfg_attr(test, derive(Arbitrary))]
1889pub struct ItemColumnsValue {
1890    pub(crate) columns: Vec<ItemColumn>,
1891}
1892
1893#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1894pub struct IndexColumnsKey {
1895    pub(crate) id: CatalogItemId,
1896}
1897
1898#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1899#[cfg_attr(test, derive(Arbitrary))]
1900pub struct IndexColumnsValue {
1901    pub(crate) columns: Vec<IndexColumn>,
1902}
1903
1904#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1905pub struct CommentKey {
1906    pub(crate) object_id: CommentObjectId,
1907    pub(crate) sub_component: Option<usize>,
1908}
1909
1910#[derive(Clone, Debug, PartialOrd, PartialEq, Eq, Ord)]
1911#[cfg_attr(test, derive(Arbitrary))]
1912pub struct CommentValue {
1913    pub(crate) comment: String,
1914}
1915
1916#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Hash, Debug)]
1917pub struct RoleKey {
1918    pub(crate) id: RoleId,
1919}
1920
1921#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Debug)]
1922pub struct RoleValue {
1923    pub(crate) name: String,
1924    pub(crate) attributes: RoleAttributes,
1925    pub(crate) membership: RoleMembership,
1926    pub(crate) vars: RoleVars,
1927    pub(crate) oid: u32,
1928}
1929
1930#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Hash, Debug)]
1931pub struct QueryPolicyKey {
1932    pub(crate) id: QueryPolicyId,
1933}
1934
1935#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Debug)]
1936pub struct QueryPolicyValue {
1937    pub(crate) name: String,
1938    pub(crate) mode: QueryPolicyMode,
1939    pub(crate) rules: Vec<QueryPolicyRule>,
1940    pub(crate) owner_id: RoleId,
1941    pub(crate) privileges: Vec<MzAclItem>,
1942    pub(crate) oid: u32,
1943}
1944
1945#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Hash, Debug)]
1946pub struct NetworkPolicyKey {
1947    pub(crate) id: NetworkPolicyId,
1948}
1949
1950#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Debug)]
1951pub struct NetworkPolicyValue {
1952    pub(crate) name: String,
1953    pub(crate) rules: Vec<NetworkPolicyRule>,
1954    pub(crate) owner_id: RoleId,
1955    pub(crate) privileges: Vec<MzAclItem>,
1956    pub(crate) oid: u32,
1957}
1958
1959#[derive(Clone, Copy, PartialOrd, PartialEq, Eq, Ord, Hash, Debug)]
1960pub struct ClusterReplicaSizeKey {
1961    pub(crate) id: ClusterReplicaSizeId,
1962}
1963
1964/// A [`ReplicaAllocation`] in proto-compatible types, so it can be `Eq` and `Ord`.
1965#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Debug)]
1966pub struct ClusterReplicaSizeValue {
1967    pub(crate) name: String,
1968    pub(crate) memory_limit: Option<u64>,
1969    pub(crate) cpu_limit: Option<u64>,
1970    pub(crate) cpu_request: Option<u64>,
1971    pub(crate) disk_limit: Option<u64>,
1972    pub(crate) scale: u16,
1973    pub(crate) workers: u64,
1974    pub(crate) credits_per_hour: String,
1975    pub(crate) cpu_exclusive: bool,
1976    pub(crate) is_cc: bool,
1977    pub(crate) family: Option<String>,
1978    pub(crate) swap_enabled: bool,
1979    pub(crate) disabled: bool,
1980    pub(crate) selectors: BTreeMap<String, String>,
1981}
1982
1983#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
1984pub struct ConfigKey {
1985    pub(crate) key: String,
1986}
1987
1988#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1989pub struct ConfigValue {
1990    pub(crate) value: u64,
1991}
1992
1993#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1994pub struct AuditLogKey {
1995    pub(crate) event: VersionedEvent,
1996}
1997
1998#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
1999pub struct StorageCollectionMetadataKey {
2000    pub(crate) id: GlobalId,
2001}
2002
2003/// This value is stored transparently, however, it should only ever be
2004/// manipulated by the storage controller.
2005#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
2006pub struct StorageCollectionMetadataValue {
2007    pub(crate) shard: ShardId,
2008}
2009
2010/// This value is stored transparently, however, it should only ever be
2011/// manipulated by the storage controller.
2012#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
2013pub struct UnfinalizedShardKey {
2014    pub(crate) shard: ShardId,
2015}
2016
2017/// This value is stored transparently, however, it should only ever be
2018/// manipulated by the storage controller.
2019#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
2020pub struct TxnWalShardValue {
2021    pub(crate) shard: ShardId,
2022}
2023
2024#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2025pub struct ServerConfigurationKey {
2026    pub(crate) name: String,
2027}
2028
2029#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
2030pub struct ServerConfigurationValue {
2031    pub(crate) value: String,
2032}
2033
2034#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2035pub struct ClusterSystemConfigurationKey {
2036    pub(crate) cluster_id: ClusterId,
2037    pub(crate) name: String,
2038}
2039
2040#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
2041pub struct ClusterSystemConfigurationValue {
2042    pub(crate) value: String,
2043}
2044
2045#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2046pub struct ReplicaSystemConfigurationKey {
2047    pub(crate) replica_id: ReplicaId,
2048    pub(crate) name: String,
2049}
2050
2051#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord)]
2052pub struct ReplicaSystemConfigurationValue {
2053    pub(crate) value: String,
2054}
2055
2056#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2057pub struct DefaultPrivilegesKey {
2058    pub(crate) role_id: RoleId,
2059    pub(crate) database_id: Option<DatabaseId>,
2060    pub(crate) schema_id: Option<SchemaId>,
2061    pub(crate) object_type: ObjectType,
2062    pub(crate) grantee: RoleId,
2063}
2064
2065#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2066pub struct DefaultPrivilegesValue {
2067    pub(crate) privileges: AclMode,
2068}
2069
2070#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2071pub struct SystemPrivilegesKey {
2072    pub(crate) grantee: RoleId,
2073    pub(crate) grantor: RoleId,
2074}
2075
2076#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2077pub struct SystemPrivilegesValue {
2078    pub(crate) acl_mode: AclMode,
2079}
2080
2081#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2082pub struct RoleAuthKey {
2083    // TODO(auth): Depending on what the future holds, here is where
2084    // we might also want to key by a `version` field.
2085    // That way we can store password versions or what have you.
2086    pub(crate) role_id: RoleId,
2087}
2088
2089#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
2090pub struct RoleAuthValue {
2091    pub(crate) password_hash: Option<String>,
2092    pub(crate) updated_at: u64,
2093}
2094
2095#[cfg(test)]
2096mod test {
2097    use crate::durable::objects::serialization::{ProtoType, RustType};
2098    use proptest::prelude::*;
2099
2100    use super::{
2101        DatabaseKey, DatabaseValue, FenceToken, ItemKey, ItemValue, SchemaKey, SchemaValue,
2102    };
2103    use crate::durable::Epoch;
2104
2105    proptest! {
2106        #[mz_ore::test]
2107        #[cfg_attr(miri, ignore)] // slow
2108        fn proptest_database_key_roundtrip(key: DatabaseKey) {
2109            let proto = key.into_proto();
2110            let round = proto.into_rust().expect("to roundtrip");
2111
2112            prop_assert_eq!(key, round);
2113        }
2114
2115        #[mz_ore::test]
2116        #[cfg_attr(miri, ignore)] // slow
2117        fn proptest_database_value_roundtrip(value: DatabaseValue) {
2118            let proto = value.into_proto();
2119            let round = proto.into_rust().expect("to roundtrip");
2120
2121            prop_assert_eq!(value, round);
2122        }
2123
2124        #[mz_ore::test]
2125        #[cfg_attr(miri, ignore)] // slow
2126        fn proptest_schema_key_roundtrip(key: SchemaKey) {
2127            let proto = key.into_proto();
2128            let round = proto.into_rust().expect("to roundtrip");
2129
2130            prop_assert_eq!(key, round);
2131        }
2132
2133        #[mz_ore::test]
2134        #[cfg_attr(miri, ignore)] // slow
2135        fn proptest_schema_value_roundtrip(value: SchemaValue) {
2136            let proto = value.into_proto();
2137            let round = proto.into_rust().expect("to roundtrip");
2138
2139            prop_assert_eq!(value, round);
2140        }
2141
2142        #[mz_ore::test]
2143        #[cfg_attr(miri, ignore)] // slow
2144        fn proptest_item_key_roundtrip(key: ItemKey) {
2145            let proto = key.into_proto();
2146            let round = proto.into_rust().expect("to roundtrip");
2147
2148            prop_assert_eq!(key, round);
2149        }
2150
2151        #[mz_ore::test]
2152        #[cfg_attr(miri, ignore)] // slow
2153        fn proptest_item_value_roundtrip(value: ItemValue) {
2154            let proto = value.into_proto();
2155            let round = proto.into_rust().expect("to roundtrip");
2156
2157            prop_assert_eq!(value, round);
2158        }
2159    }
2160
2161    #[mz_ore::test]
2162    fn test_fence_token_order() {
2163        let ft1 = FenceToken {
2164            deploy_generation: 10,
2165            epoch: Epoch::new(20).expect("non-zero"),
2166        };
2167        let ft2 = FenceToken {
2168            deploy_generation: 10,
2169            epoch: Epoch::new(19).expect("non-zero"),
2170        };
2171
2172        assert!(ft1 > ft2);
2173
2174        let ft3 = FenceToken {
2175            deploy_generation: 11,
2176            epoch: Epoch::new(10).expect("non-zero"),
2177        };
2178
2179        assert!(ft3 > ft1);
2180
2181        let ft4 = FenceToken {
2182            deploy_generation: 11,
2183            epoch: Epoch::new(30).expect("non-zero"),
2184        };
2185
2186        assert!(ft4 > ft1);
2187    }
2188}