1use std::fmt::Debug;
13use std::num::NonZeroI64;
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use async_trait::async_trait;
18use itertools::Itertools;
19use mz_audit_log::VersionedEvent;
20use mz_controller_types::ClusterId;
21use mz_ore::collections::CollectionExt;
22use mz_ore::metrics::MetricsRegistry;
23use mz_persist_client::PersistClient;
24use mz_persist_types::ShardId;
25use mz_repr::{CatalogItemId, Diff, GlobalId, RelationDesc, SqlScalarType};
26use mz_sql::catalog::CatalogError as SqlCatalogError;
27use uuid::Uuid;
28
29use crate::config::ClusterReplicaSizeMap;
30use crate::durable::debug::{DebugCatalogState, Trace};
31pub use crate::durable::error::{CatalogError, DurableCatalogError, FenceError};
32pub use crate::durable::metrics::Metrics;
33use crate::durable::objects::AuditLog;
34pub use crate::durable::objects::Snapshot;
35pub use crate::durable::objects::state_update::StateUpdate;
36use crate::durable::objects::state_update::{StateUpdateKindJson, TryIntoStateUpdateKind};
37pub use crate::durable::objects::{
38 Cluster, ClusterConfig, ClusterReplica, ClusterVariant, ClusterVariantManaged, Comment,
39 Database, DefaultPrivilege, IntrospectionSourceIndex, Item, NetworkPolicy, ReplicaConfig,
40 ReplicaLocation, Role, RoleAuth, Schema, SourceReference, SourceReferences,
41 StorageCollectionMetadata, SystemConfiguration, SystemObjectDescription, SystemObjectMapping,
42 UnfinalizedShard,
43};
44pub use crate::durable::persist::shard_id;
45use crate::durable::persist::{Timestamp, UnopenedPersistCatalogState};
46pub use crate::durable::transaction::Transaction;
47use crate::durable::transaction::TransactionBatch;
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 OID_ALLOC_KEY: &str = "oid";
74pub(crate) const CATALOG_CONTENT_VERSION_KEY: &str = "catalog_content_version";
75pub const BUILTIN_MIGRATION_SHARD_KEY: &str = "builtin_migration_shard";
76pub const EXPRESSION_CACHE_SHARD_KEY: &str = "expression_cache_shard";
77pub const MOCK_AUTHENTICATION_NONCE_KEY: &str = "mock_authentication_nonce";
78
79#[derive(Clone, Debug)]
80pub struct BootstrapArgs {
81 pub cluster_replica_size_map: ClusterReplicaSizeMap,
82 pub default_cluster_replica_size: String,
83 pub default_cluster_replication_factor: u32,
84 pub bootstrap_role: Option<String>,
85}
86
87pub type Epoch = NonZeroI64;
88
89#[async_trait]
93pub trait OpenableDurableCatalogState: Debug + Send {
94 async fn open_savepoint(
113 mut self: Box<Self>,
114 initial_ts: Timestamp,
115 bootstrap_args: &BootstrapArgs,
116 ) -> Result<(Box<dyn DurableCatalogState>, AuditLogIterator), CatalogError>;
117
118 async fn open_read_only(
124 mut self: Box<Self>,
125 bootstrap_args: &BootstrapArgs,
126 ) -> Result<Box<dyn DurableCatalogState>, CatalogError>;
127
128 async fn open(
136 mut self: Box<Self>,
137 initial_ts: Timestamp,
138 bootstrap_args: &BootstrapArgs,
139 ) -> Result<(Box<dyn DurableCatalogState>, AuditLogIterator), CatalogError>;
140
141 async fn open_debug(mut self: Box<Self>) -> Result<DebugCatalogState, CatalogError>;
144
145 async fn is_initialized(&mut self) -> Result<bool, CatalogError>;
147
148 async fn epoch(&mut self) -> Result<Epoch, CatalogError>;
158
159 async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError>;
162
163 async fn get_0dt_deployment_max_wait(&mut self) -> Result<Option<Duration>, CatalogError>;
169
170 async fn get_0dt_deployment_ddl_check_interval(
176 &mut self,
177 ) -> Result<Option<Duration>, CatalogError>;
178
179 async fn get_enable_0dt_deployment_panic_after_timeout(
186 &mut self,
187 ) -> Result<Option<bool>, CatalogError>;
188
189 async fn has_system_config_synced_once(&mut self) -> Result<bool, DurableCatalogError>;
191
192 async fn trace_unconsolidated(&mut self) -> Result<Trace, CatalogError>;
194
195 async fn trace_consolidated(&mut self) -> Result<Trace, CatalogError>;
197
198 async fn expire(self: Box<Self>);
200}
201
202#[async_trait]
204pub trait ReadOnlyDurableCatalogState: Debug + Send + Sync {
205 fn epoch(&self) -> Epoch;
215
216 fn metrics(&self) -> &Metrics;
218
219 async fn expire(self: Box<Self>);
221
222 fn is_bootstrap_complete(&self) -> bool;
224
225 async fn get_audit_logs(&mut self) -> Result<Vec<VersionedEvent>, CatalogError>;
231
232 async fn get_next_id(&mut self, id_type: &str) -> Result<u64, CatalogError>;
234
235 async fn get_next_user_item_id(&mut self) -> Result<u64, CatalogError> {
237 self.get_next_id(USER_ITEM_ALLOC_KEY).await
238 }
239
240 async fn get_next_system_item_id(&mut self) -> Result<u64, CatalogError> {
242 self.get_next_id(SYSTEM_ITEM_ALLOC_KEY).await
243 }
244
245 async fn get_next_system_replica_id(&mut self) -> Result<u64, CatalogError> {
247 self.get_next_id(SYSTEM_REPLICA_ID_ALLOC_KEY).await
248 }
249
250 async fn get_next_user_replica_id(&mut self) -> Result<u64, CatalogError> {
252 self.get_next_id(USER_REPLICA_ID_ALLOC_KEY).await
253 }
254
255 async fn get_deployment_generation(&mut self) -> Result<u64, CatalogError>;
257
258 async fn snapshot(&mut self) -> Result<Snapshot, CatalogError>;
260
261 async fn sync_to_current_updates(
267 &mut self,
268 ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError>;
269
270 async fn sync_updates(
279 &mut self,
280 target_upper: Timestamp,
281 ) -> Result<Vec<memory::objects::StateUpdate>, CatalogError>;
282
283 async fn current_upper(&mut self) -> Timestamp;
285}
286
287#[async_trait]
289#[allow(mismatched_lifetime_syntaxes)]
290pub trait DurableCatalogState: ReadOnlyDurableCatalogState {
291 fn is_read_only(&self) -> bool;
293
294 fn is_savepoint(&self) -> bool;
296
297 async fn mark_bootstrap_complete(&mut self);
299
300 async fn transaction(&mut self) -> Result<Transaction, CatalogError>;
302
303 fn transaction_from_snapshot(
309 &mut self,
310 snapshot: Snapshot,
311 ) -> Result<Transaction, CatalogError>;
312
313 async fn commit_transaction(
321 &mut self,
322 txn_batch: TransactionBatch,
323 commit_ts: Timestamp,
324 ) -> Result<Timestamp, CatalogError>;
325
326 async fn confirm_leadership(&mut self) -> Result<(), CatalogError>;
330
331 #[mz_ore::instrument(level = "debug")]
335 async fn allocate_id(
336 &mut self,
337 id_type: &str,
338 amount: u64,
339 commit_ts: Timestamp,
340 ) -> Result<Vec<u64>, CatalogError> {
341 let start = Instant::now();
342 if amount == 0 {
343 return Ok(Vec::new());
344 }
345 let mut txn = self.transaction().await?;
346 let ids = txn.get_and_increment_id_by(id_type.to_string(), amount)?;
347 txn.commit_internal(commit_ts).await?;
348 self.metrics()
349 .allocate_id_seconds
350 .observe(start.elapsed().as_secs_f64());
351 Ok(ids)
352 }
353
354 async fn allocate_user_ids(
358 &mut self,
359 amount: u64,
360 commit_ts: Timestamp,
361 ) -> Result<Vec<(CatalogItemId, GlobalId)>, CatalogError> {
362 let ids = self
363 .allocate_id(USER_ITEM_ALLOC_KEY, amount, commit_ts)
364 .await?;
365 let ids = ids
366 .iter()
367 .map(|id| (CatalogItemId::User(*id), GlobalId::User(*id)))
368 .collect();
369 Ok(ids)
370 }
371
372 async fn allocate_user_id(
376 &mut self,
377 commit_ts: Timestamp,
378 ) -> Result<(CatalogItemId, GlobalId), CatalogError> {
379 let id = self.allocate_id(USER_ITEM_ALLOC_KEY, 1, commit_ts).await?;
380 let id = id.into_element();
381 Ok((CatalogItemId::User(id), GlobalId::User(id)))
382 }
383
384 async fn allocate_user_cluster_id(
388 &mut self,
389 commit_ts: Timestamp,
390 ) -> Result<ClusterId, CatalogError> {
391 let id = self
392 .allocate_id(USER_CLUSTER_ID_ALLOC_KEY, 1, commit_ts)
393 .await?
394 .into_element();
395 Ok(ClusterId::user(id).ok_or(SqlCatalogError::IdExhaustion)?)
396 }
397
398 fn shard_id(&self) -> ShardId;
399}
400
401trait AuditLogIteratorTrait: Iterator<Item = (AuditLog, Timestamp)> + Send + Sync + Debug {}
402impl<T: Iterator<Item = (AuditLog, Timestamp)> + Send + Sync + Debug> AuditLogIteratorTrait for T {}
403
404#[derive(Debug)]
406pub struct AuditLogIterator {
407 audit_logs: Box<dyn AuditLogIteratorTrait>,
410}
411
412impl AuditLogIterator {
413 fn new(audit_logs: Vec<(StateUpdateKindJson, Timestamp, Diff)>) -> Self {
414 let audit_logs = audit_logs
415 .into_iter()
416 .map(|(kind, ts, diff)| {
417 assert_eq!(
418 diff,
419 Diff::ONE,
420 "audit log is append only: ({kind:?}, {ts:?}, {diff:?})"
421 );
422 assert!(
423 kind.is_audit_log(),
424 "unexpected update kind: ({kind:?}, {ts:?}, {diff:?})"
425 );
426 let id = kind.audit_log_id();
427 (kind, ts, id)
428 })
429 .sorted_by_key(|(_, ts, id)| (*ts, *id))
430 .map(|(kind, ts, _id)| (kind, ts))
431 .rev()
432 .map(|(kind, ts)| {
433 let kind = TryIntoStateUpdateKind::try_into(kind).expect("kind decoding error");
435 let kind: Option<memory::objects::StateUpdateKind> = (&kind)
436 .try_into()
437 .expect("invalid persisted update: {update:#?}");
438 let kind = kind.expect("audit log always produces im-memory updates");
439 let audit_log = match kind {
440 memory::objects::StateUpdateKind::AuditLog(audit_log) => audit_log,
441 kind => unreachable!("invalid kind: {kind:?}"),
442 };
443 (audit_log, ts)
444 });
445 Self {
446 audit_logs: Box::new(audit_logs),
447 }
448 }
449}
450
451impl Iterator for AuditLogIterator {
452 type Item = (AuditLog, Timestamp);
453
454 fn next(&mut self) -> Option<Self::Item> {
455 self.audit_logs.next()
456 }
457}
458
459pub fn persist_desc() -> RelationDesc {
462 RelationDesc::builder()
463 .with_column("data", SqlScalarType::Jsonb.nullable(false))
464 .finish()
465}
466
467#[derive(Debug, Clone)]
469pub struct TestCatalogStateBuilder {
470 persist_client: PersistClient,
471 organization_id: Uuid,
472 version: semver::Version,
473 deploy_generation: Option<u64>,
474 metrics: Arc<Metrics>,
475}
476
477impl TestCatalogStateBuilder {
478 pub fn new(persist_client: PersistClient) -> Self {
479 Self {
480 persist_client,
481 organization_id: Uuid::new_v4(),
482 version: semver::Version::new(0, 0, 0),
483 deploy_generation: None,
484 metrics: Arc::new(Metrics::new(&MetricsRegistry::new())),
485 }
486 }
487
488 pub fn with_organization_id(mut self, organization_id: Uuid) -> Self {
489 self.organization_id = organization_id;
490 self
491 }
492
493 pub fn with_version(mut self, version: semver::Version) -> Self {
494 self.version = version;
495 self
496 }
497
498 pub fn with_deploy_generation(mut self, deploy_generation: u64) -> Self {
499 self.deploy_generation = Some(deploy_generation);
500 self
501 }
502
503 pub fn with_default_deploy_generation(self) -> Self {
504 self.with_deploy_generation(0)
505 }
506
507 pub fn with_metrics(mut self, metrics: Arc<Metrics>) -> Self {
508 self.metrics = metrics;
509 self
510 }
511
512 pub async fn build(self) -> Result<Box<dyn OpenableDurableCatalogState>, DurableCatalogError> {
513 persist_backed_catalog_state(
514 self.persist_client,
515 self.organization_id,
516 self.version,
517 self.deploy_generation,
518 self.metrics,
519 )
520 .await
521 }
522
523 pub async fn unwrap_build(self) -> Box<dyn OpenableDurableCatalogState> {
524 self.expect_build("failed to build").await
525 }
526
527 pub async fn expect_build(self, msg: &str) -> Box<dyn OpenableDurableCatalogState> {
528 self.build().await.expect(msg)
529 }
530}
531
532pub async fn persist_backed_catalog_state(
536 persist_client: PersistClient,
537 organization_id: Uuid,
538 version: semver::Version,
539 deploy_generation: Option<u64>,
540 metrics: Arc<Metrics>,
541) -> Result<Box<dyn OpenableDurableCatalogState>, DurableCatalogError> {
542 let state = UnopenedPersistCatalogState::new(
543 persist_client,
544 organization_id,
545 version,
546 deploy_generation,
547 metrics,
548 )
549 .await?;
550 Ok(Box::new(state))
551}
552
553pub fn test_bootstrap_args() -> BootstrapArgs {
554 BootstrapArgs {
555 default_cluster_replica_size: "scale=1,workers=1".into(),
556 default_cluster_replication_factor: 1,
557 bootstrap_role: None,
558 cluster_replica_size_map: ClusterReplicaSizeMap::for_tests(),
559 }
560}