1use std::fmt::Debug;
13use std::num::NonZeroI64;
14use std::sync::Arc;
15use std::time::Duration;
16
17use async_trait::async_trait;
18use mz_audit_log::VersionedEvent;
19use mz_controller_types::{ClusterId, ReplicaId};
20use mz_ore::collections::CollectionExt;
21use mz_ore::metrics::MetricsRegistry;
22use mz_persist_client::PersistClient;
23use mz_persist_types::ShardId;
24use mz_repr::{CatalogItemId, GlobalId, RelationDesc, SqlScalarType};
25use mz_sql::catalog::CatalogError as SqlCatalogError;
26use uuid::Uuid;
27
28use crate::config::ClusterReplicaSizeMap;
29use crate::durable::debug::{DebugCatalogState, Trace};
30pub use crate::durable::error::{CatalogError, DurableCatalogError, FenceError};
31pub use crate::durable::metrics::Metrics;
32pub use crate::durable::objects::Snapshot;
33pub use crate::durable::objects::state_update::StateUpdate;
34pub use crate::durable::objects::{
35 BurstState, Cluster, ClusterConfig, ClusterReplica, ClusterReplicaSize,
36 ClusterSystemConfiguration, ClusterVariant, ClusterVariantManaged, Comment, Database,
37 DefaultPrivilege, IndexColumn, IndexColumns, IntrospectionSourceIndex, Item, ItemColumn,
38 ItemColumns, ItemMetadata, NetworkPolicy, QueryPolicy, ReconfigurationState,
39 ReconfigurationStatus, ReconfigurationTarget, ReplicaConfig, ReplicaLocation,
40 ReplicaSystemConfiguration, Role, RoleAuth, Schema, SourceReference, SourceReferences,
41 StorageCollectionMetadata, SystemConfiguration, SystemObjectDescription, SystemObjectMapping,
42 UnfinalizedShard, managed_cluster_replica_name,
43};
44pub use crate::durable::persist::shard_id;
45use crate::durable::persist::{Timestamp, UnopenedPersistCatalogState};
46use crate::durable::transaction::TransactionBatch;
47pub use crate::durable::transaction::{DryRunTransaction, Transaction};
48pub use crate::durable::upgrade::CATALOG_VERSION;
49use crate::memory;
50
51pub mod debug;
52mod error;
53pub mod initialize;
54mod metrics;
55pub mod objects;
56mod persist;
57mod traits;
58mod transaction;
59mod upgrade;
60
61pub const DATABASE_ID_ALLOC_KEY: &str = "database";
62pub const SCHEMA_ID_ALLOC_KEY: &str = "schema";
63pub const USER_ITEM_ALLOC_KEY: &str = "user";
64pub const SYSTEM_ITEM_ALLOC_KEY: &str = "system";
65pub const USER_ROLE_ID_ALLOC_KEY: &str = "user_role";
66pub const USER_CLUSTER_ID_ALLOC_KEY: &str = "user_compute";
67pub const SYSTEM_CLUSTER_ID_ALLOC_KEY: &str = "system_compute";
68pub const USER_REPLICA_ID_ALLOC_KEY: &str = "replica";
69pub const SYSTEM_REPLICA_ID_ALLOC_KEY: &str = "system_replica";
70pub const AUDIT_LOG_ID_ALLOC_KEY: &str = "auditlog";
71pub const STORAGE_USAGE_ID_ALLOC_KEY: &str = "storage_usage";
72pub const USER_NETWORK_POLICY_ID_ALLOC_KEY: &str = "user_network_policy";
73pub const USER_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY: &str = "user_cluster_replica_size";
74pub const SYSTEM_CLUSTER_REPLICA_SIZE_ID_ALLOC_KEY: &str = "system_cluster_replica_size";
75pub const USER_QUERY_POLICY_ID_ALLOC_KEY: &str = "user_query_policy";
76pub const OID_ALLOC_KEY: &str = "oid";
77pub(crate) const CATALOG_CONTENT_VERSION_KEY: &str = "catalog_content_version";
78pub const BUILTIN_MIGRATION_SHARD_KEY: &str = "builtin_migration_shard";
79pub const EXPRESSION_CACHE_SHARD_KEY: &str = "expression_cache_shard";
80pub const MOCK_AUTHENTICATION_NONCE_KEY: &str = "mock_authentication_nonce";
81
82#[derive(Clone, Debug)]
83pub struct BootstrapArgs {
84 pub cluster_replica_size_map: ClusterReplicaSizeMap,
85 pub default_cluster_replica_size: String,
86 pub default_cluster_replication_factor: u32,
87 pub bootstrap_role: Option<String>,
88 pub force_catalog_migration: bool,
90}
91
92pub type Epoch = NonZeroI64;
93
94#[async_trait]
98pub trait OpenableDurableCatalogState: Debug + Send {
99 async fn open_savepoint(
116 mut self: Box<Self>,
117 initial_ts: Timestamp,
118 bootstrap_args: &BootstrapArgs,
119 ) -> Result<Box<dyn DurableCatalogState>, CatalogError>;
120
121 async fn open_read_only(
127 mut self: Box<Self>,
128 bootstrap_args: &BootstrapArgs,
129 ) -> Result<Box<dyn DurableCatalogState>, CatalogError>;
130
131 async fn open(
137 mut self: Box<Self>,
138 initial_ts: Timestamp,
139 bootstrap_args: &BootstrapArgs,
140 ) -> Result<Box<dyn DurableCatalogState>, CatalogError>;
141
142 async fn open_debug(mut self: Box<Self>) -> Result<DebugCatalogState, CatalogError>;
145
146 async fn is_initialized(&mut self) -> Result<bool, CatalogError>;
148
149 async fn epoch(&mut self) -> Result<Epoch, CatalogError>;
159
160 async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError>;
163
164 async fn get_0dt_deployment_max_wait(&mut self) -> Result<Option<Duration>, CatalogError>;
170
171 async fn get_0dt_deployment_ddl_check_interval(
177 &mut self,
178 ) -> Result<Option<Duration>, CatalogError>;
179
180 async fn get_enable_0dt_deployment_panic_after_timeout(
187 &mut self,
188 ) -> Result<Option<bool>, CatalogError>;
189
190 async fn has_system_config_synced_once(&mut self) -> Result<bool, DurableCatalogError>;
192
193 async fn trace_unconsolidated(&mut self) -> Result<Trace, CatalogError>;
195
196 async fn trace_consolidated(&mut self) -> Result<Trace, CatalogError>;
198
199 async fn expire(self: Box<Self>);
201}
202
203#[async_trait]
205pub trait ReadOnlyDurableCatalogState: Debug + Send + Sync {
206 fn epoch(&self) -> Epoch;
216
217 fn metrics(&self) -> &Metrics;
219
220 async fn expire(self: Box<Self>);
222
223 fn is_bootstrap_complete(&self) -> bool;
225
226 async fn get_audit_logs(&mut self) -> Result<Vec<VersionedEvent>, CatalogError>;
232
233 async fn get_next_id(&mut self, id_type: &str) -> Result<u64, CatalogError>;
235
236 async fn get_next_user_item_id(&mut self) -> Result<u64, CatalogError> {
238 self.get_next_id(USER_ITEM_ALLOC_KEY).await
239 }
240
241 async fn get_next_system_item_id(&mut self) -> Result<u64, CatalogError> {
243 self.get_next_id(SYSTEM_ITEM_ALLOC_KEY).await
244 }
245
246 async fn get_next_system_replica_id(&mut self) -> Result<u64, CatalogError> {
248 self.get_next_id(SYSTEM_REPLICA_ID_ALLOC_KEY).await
249 }
250
251 async fn get_next_user_replica_id(&mut self) -> Result<u64, CatalogError> {
253 self.get_next_id(USER_REPLICA_ID_ALLOC_KEY).await
254 }
255
256 async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError>;
258
259 async fn snapshot(&mut self) -> Result<Snapshot, CatalogError>;
261
262 async fn sync_to_current_updates(
268 &mut self,
269 ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError>;
270
271 async fn sync_updates(
280 &mut self,
281 target_upper: Timestamp,
282 ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError>;
283
284 async fn ensure_not_out_of_sync(&mut self, target_upper: Timestamp)
288 -> Result<(), CatalogError>;
289
290 async fn current_upper(&mut self) -> Timestamp;
292}
293
294#[async_trait]
296#[allow(mismatched_lifetime_syntaxes)]
297pub trait DurableCatalogState: ReadOnlyDurableCatalogState {
298 fn is_read_only(&self) -> bool;
300
301 fn is_savepoint(&self) -> bool;
303
304 async fn mark_bootstrap_complete(&mut self);
306
307 async fn transaction(&mut self) -> Result<Transaction, CatalogError>;
311
312 fn transaction_from_snapshot(
316 &mut self,
317 snapshot: Snapshot,
318 ) -> Result<DryRunTransaction, CatalogError>;
319
320 async fn commit_transaction(
328 &mut self,
329 txn_batch: TransactionBatch,
330 commit_ts: Timestamp,
331 ) -> Result<Timestamp, CatalogError>;
332
333 async fn advance_upper(&mut self, new_upper: Timestamp) -> Result<(), CatalogError>;
339
340 async fn allocate_id(
345 &mut self,
346 id_type: &str,
347 amount: u64,
348 commit_ts: Timestamp,
349 ) -> Result<Vec<u64>, CatalogError>;
350
351 async fn allocate_user_ids(
355 &mut self,
356 amount: u64,
357 commit_ts: Timestamp,
358 ) -> Result<Vec<(CatalogItemId, GlobalId)>, CatalogError> {
359 let ids = self
360 .allocate_id(USER_ITEM_ALLOC_KEY, amount, commit_ts)
361 .await?;
362 let ids = ids
363 .iter()
364 .map(|id| (CatalogItemId::User(*id), GlobalId::User(*id)))
365 .collect();
366 Ok(ids)
367 }
368
369 async fn allocate_user_id(
373 &mut self,
374 commit_ts: Timestamp,
375 ) -> Result<(CatalogItemId, GlobalId), CatalogError> {
376 let id = self.allocate_id(USER_ITEM_ALLOC_KEY, 1, commit_ts).await?;
377 let id = id.into_element();
378 Ok((CatalogItemId::User(id), GlobalId::User(id)))
379 }
380
381 async fn allocate_user_cluster_id(
385 &mut self,
386 commit_ts: Timestamp,
387 ) -> Result<ClusterId, CatalogError> {
388 let id = self
389 .allocate_id(USER_CLUSTER_ID_ALLOC_KEY, 1, commit_ts)
390 .await?
391 .into_element();
392 Ok(ClusterId::user(id).ok_or(SqlCatalogError::IdExhaustion)?)
393 }
394
395 async fn allocate_user_replica_ids(
399 &mut self,
400 amount: u64,
401 commit_ts: Timestamp,
402 ) -> Result<Vec<ReplicaId>, CatalogError> {
403 let ids = self
404 .allocate_id(USER_REPLICA_ID_ALLOC_KEY, amount, commit_ts)
405 .await?;
406 let ids = ids.into_iter().map(ReplicaId::User).collect();
407 Ok(ids)
408 }
409
410 async fn allocate_system_replica_ids(
414 &mut self,
415 amount: u64,
416 commit_ts: Timestamp,
417 ) -> Result<Vec<ReplicaId>, CatalogError> {
418 let ids = self
419 .allocate_id(SYSTEM_REPLICA_ID_ALLOC_KEY, amount, commit_ts)
420 .await?;
421 let ids = ids.into_iter().map(ReplicaId::System).collect();
422 Ok(ids)
423 }
424
425 fn shard_id(&self) -> ShardId;
426}
427
428pub fn persist_desc() -> RelationDesc {
431 RelationDesc::builder()
432 .with_column("data", SqlScalarType::Jsonb.nullable(false))
433 .finish()
434}
435
436#[derive(Debug, Clone)]
438pub struct TestCatalogStateBuilder {
439 persist_client: PersistClient,
440 organization_id: Uuid,
441 version: semver::Version,
442 deploy_generation: Option<u64>,
443 metrics: Arc<Metrics>,
444}
445
446impl TestCatalogStateBuilder {
447 pub fn new(persist_client: PersistClient) -> Self {
448 Self {
449 persist_client,
450 organization_id: Uuid::new_v4(),
451 version: semver::Version::new(0, 0, 0),
452 deploy_generation: None,
453 metrics: Arc::new(Metrics::new(&MetricsRegistry::new())),
454 }
455 }
456
457 pub fn with_organization_id(mut self, organization_id: Uuid) -> Self {
458 self.organization_id = organization_id;
459 self
460 }
461
462 pub fn with_version(mut self, version: semver::Version) -> Self {
463 self.version = version;
464 self
465 }
466
467 pub fn with_deploy_generation(mut self, deploy_generation: u64) -> Self {
468 self.deploy_generation = Some(deploy_generation);
469 self
470 }
471
472 pub fn with_default_deploy_generation(self) -> Self {
473 self.with_deploy_generation(0)
474 }
475
476 pub fn with_metrics(mut self, metrics: Arc<Metrics>) -> Self {
477 self.metrics = metrics;
478 self
479 }
480
481 pub async fn build(self) -> Result<Box<dyn OpenableDurableCatalogState>, DurableCatalogError> {
482 persist_backed_catalog_state(
483 self.persist_client,
484 self.organization_id,
485 self.version,
486 self.deploy_generation,
487 self.metrics,
488 )
489 .await
490 }
491
492 pub async fn unwrap_build(self) -> Box<dyn OpenableDurableCatalogState> {
493 self.expect_build("failed to build").await
494 }
495
496 pub async fn expect_build(self, msg: &str) -> Box<dyn OpenableDurableCatalogState> {
497 self.build().await.expect(msg)
498 }
499}
500
501pub async fn persist_backed_catalog_state(
505 persist_client: PersistClient,
506 organization_id: Uuid,
507 version: semver::Version,
508 deploy_generation: Option<u64>,
509 metrics: Arc<Metrics>,
510) -> Result<Box<dyn OpenableDurableCatalogState>, DurableCatalogError> {
511 let state = UnopenedPersistCatalogState::new(
512 persist_client,
513 organization_id,
514 version,
515 deploy_generation,
516 metrics,
517 )
518 .await?;
519 Ok(Box::new(state))
520}
521
522pub fn test_bootstrap_args() -> BootstrapArgs {
523 BootstrapArgs {
524 default_cluster_replica_size: "scale=1,workers=1".into(),
525 default_cluster_replication_factor: 1,
526 bootstrap_role: None,
527 cluster_replica_size_map: ClusterReplicaSizeMap::for_tests(),
528 force_catalog_migration: false,
529 }
530}