1use std::collections::{BTreeMap, BTreeSet};
10use std::fmt;
11use std::io;
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use std::time::{SystemTime, UNIX_EPOCH};
15
16use crate::auth::AuthConfig;
17use crate::replication::ReplicationConfig;
18
19pub const DEFAULT_SNAPSHOT_RETENTION: usize = 16;
20pub const DEFAULT_EXPORT_RETENTION: usize = 16;
21
22pub const REDDB_PROTOCOL_VERSION: &str = "reddb-v2";
23pub const REDDB_FORMAT_VERSION: u32 = 2;
24pub const DEFAULT_GROUP_COMMIT_WINDOW_MS: u64 = 0;
37pub const DEFAULT_GROUP_COMMIT_MAX_STATEMENTS: usize = 128;
38pub const DEFAULT_GROUP_COMMIT_MAX_WAL_BYTES: u64 = 1024 * 1024;
39pub(crate) const EPHEMERAL_RUNTIME_METADATA_KEY: &str = "__reddb_ephemeral_runtime";
40
41pub type RedDBResult<T> = Result<T, RedDBError>;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
44pub enum StorageMode {
45 #[default]
47 Persistent,
48}
49
50impl StorageMode {
51 pub const fn is_persistent(self) -> bool {
52 matches!(self, Self::Persistent)
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
57pub enum DurabilityMode {
58 #[default]
59 Strict,
60 WalDurableGrouped,
61 Async,
69}
70
71impl DurabilityMode {
72 pub const fn as_str(self) -> &'static str {
73 match self {
74 Self::Strict => "strict",
75 Self::WalDurableGrouped => "wal_durable_grouped",
76 Self::Async => "async",
77 }
78 }
79
80 pub fn from_str(value: &str) -> Option<Self> {
81 let normalized = value.trim().to_ascii_lowercase();
82 match normalized.as_str() {
83 "strict" => Some(Self::Strict),
85 "sync"
91 | "wal_durable_grouped"
92 | "wal-durable-grouped"
93 | "grouped"
94 | "wal_grouped"
95 | "wal-grouped" => Some(Self::WalDurableGrouped),
96 "async" | "fire_and_forget" | "fire-and-forget" => Some(Self::Async),
100 _ => None,
101 }
102 }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub struct GroupCommitOptions {
107 pub window_ms: u64,
108 pub max_statements: usize,
109 pub max_wal_bytes: u64,
110}
111
112impl Default for GroupCommitOptions {
113 fn default() -> Self {
114 Self {
115 window_ms: DEFAULT_GROUP_COMMIT_WINDOW_MS,
116 max_statements: DEFAULT_GROUP_COMMIT_MAX_STATEMENTS,
117 max_wal_bytes: DEFAULT_GROUP_COMMIT_MAX_WAL_BYTES,
118 }
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
123pub enum Capability {
124 Table,
126 Graph,
128 Vector,
130 FullText,
132 Security,
134 Encryption,
136}
137
138impl Capability {
139 pub const fn as_str(self) -> &'static str {
140 match self {
141 Self::Table => "table",
142 Self::Graph => "graph",
143 Self::Vector => "vector",
144 Self::FullText => "fulltext",
145 Self::Security => "security",
146 Self::Encryption => "encryption",
147 }
148 }
149}
150
151#[derive(Debug, Clone, Default)]
152pub struct CapabilitySet {
153 items: BTreeSet<Capability>,
154}
155
156impl CapabilitySet {
157 pub fn new() -> Self {
158 Self::default()
159 }
160
161 pub fn with(mut self, capability: Capability) -> Self {
162 self.items.insert(capability);
163 self
164 }
165
166 pub fn with_all(mut self, capabilities: &[Capability]) -> Self {
167 capabilities.iter().copied().for_each(|capability| {
168 self.items.insert(capability);
169 });
170 self
171 }
172
173 pub fn has(&self, capability: Capability) -> bool {
174 self.items.contains(&capability)
175 }
176
177 pub fn as_slice(&self) -> Vec<Capability> {
178 self.items.iter().copied().collect()
179 }
180}
181
182pub struct RedDBOptions {
183 pub mode: StorageMode,
184 pub data_path: Option<PathBuf>,
185 pub read_only: bool,
186 pub create_if_missing: bool,
187 pub verify_checksums: bool,
188 pub durability_mode: DurabilityMode,
189 pub group_commit: GroupCommitOptions,
190 pub auto_checkpoint_pages: u32,
191 pub checkpoint_columnar_emission_budget_chunks: usize,
194 pub columnar_projection_size_floor_rows: usize,
197 pub cache_pages: usize,
198 pub snapshot_retention: usize,
199 pub export_retention: usize,
200 pub feature_gates: CapabilitySet,
201 pub force_create: bool,
202 pub metadata: BTreeMap<String, String>,
203 pub remote_backend: Option<Arc<dyn crate::storage::backend::RemoteBackend>>,
205 pub remote_backend_atomic: Option<Arc<dyn crate::storage::backend::AtomicRemoteBackend>>,
212 pub remote_key: Option<String>,
214 pub replication: ReplicationConfig,
216 pub replica_loop_enabled: bool,
218 pub auth: AuthConfig,
220 pub control_events: crate::runtime::control_events::ControlEventConfig,
223 pub query_audit: crate::runtime::query_audit::QueryAuditConfig,
227 pub auto_index_id: bool,
233 pub layout: crate::storage::layout::StorageLayout,
239 pub layout_overrides: crate::storage::layout::LayoutOverrides,
241 pub storage_profile: crate::storage::profile::StorageProfileSelection,
244 pub layout_explicit: bool,
250 pub memory_budget_bytes: Option<u64>,
256 pub bounded_disk_residency: bool,
261}
262
263impl fmt::Debug for RedDBOptions {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 let backend_name = self.remote_backend.as_ref().map(|b| b.name().to_string());
266 f.debug_struct("RedDBOptions")
267 .field("mode", &self.mode)
268 .field("data_path", &self.data_path)
269 .field("read_only", &self.read_only)
270 .field("create_if_missing", &self.create_if_missing)
271 .field("verify_checksums", &self.verify_checksums)
272 .field("durability_mode", &self.durability_mode)
273 .field("group_commit", &self.group_commit)
274 .field("auto_checkpoint_pages", &self.auto_checkpoint_pages)
275 .field(
276 "checkpoint_columnar_emission_budget_chunks",
277 &self.checkpoint_columnar_emission_budget_chunks,
278 )
279 .field(
280 "columnar_projection_size_floor_rows",
281 &self.columnar_projection_size_floor_rows,
282 )
283 .field("cache_pages", &self.cache_pages)
284 .field("snapshot_retention", &self.snapshot_retention)
285 .field("export_retention", &self.export_retention)
286 .field("feature_gates", &self.feature_gates)
287 .field("force_create", &self.force_create)
288 .field("metadata", &self.metadata)
289 .field("remote_backend", &backend_name)
290 .field("remote_key", &self.remote_key)
291 .field("replication", &self.replication)
292 .field("replica_loop_enabled", &self.replica_loop_enabled)
293 .field("auth", &self.auth)
294 .field("control_events", &self.control_events)
295 .field("query_audit", &self.query_audit)
296 .field("layout", &self.layout)
297 .field("layout_overrides", &self.layout_overrides)
298 .field("storage_profile", &self.storage_profile)
299 .field("memory_budget_bytes", &self.memory_budget_bytes)
300 .field("bounded_disk_residency", &self.bounded_disk_residency)
301 .finish()
302 }
303}
304
305impl Clone for RedDBOptions {
306 fn clone(&self) -> Self {
307 Self {
308 mode: self.mode,
309 data_path: self.data_path.clone(),
310 read_only: self.read_only,
311 create_if_missing: self.create_if_missing,
312 verify_checksums: self.verify_checksums,
313 durability_mode: self.durability_mode,
314 group_commit: self.group_commit,
315 auto_checkpoint_pages: self.auto_checkpoint_pages,
316 checkpoint_columnar_emission_budget_chunks: self
317 .checkpoint_columnar_emission_budget_chunks,
318 columnar_projection_size_floor_rows: self.columnar_projection_size_floor_rows,
319 cache_pages: self.cache_pages,
320 snapshot_retention: self.snapshot_retention,
321 export_retention: self.export_retention,
322 feature_gates: self.feature_gates.clone(),
323 force_create: self.force_create,
324 metadata: self.metadata.clone(),
325 remote_backend: self.remote_backend.clone(),
326 remote_backend_atomic: self.remote_backend_atomic.clone(),
327 remote_key: self.remote_key.clone(),
328 replication: self.replication.clone(),
329 replica_loop_enabled: self.replica_loop_enabled,
330 auth: self.auth.clone(),
331 control_events: self.control_events,
332 query_audit: self.query_audit.clone(),
333 auto_index_id: self.auto_index_id,
334 layout: self.layout,
335 layout_overrides: self.layout_overrides.clone(),
336 storage_profile: self.storage_profile,
337 layout_explicit: self.layout_explicit,
338 memory_budget_bytes: self.memory_budget_bytes,
339 bounded_disk_residency: self.bounded_disk_residency,
340 }
341 }
342}
343
344impl Default for RedDBOptions {
345 fn default() -> Self {
346 Self {
347 mode: StorageMode::Persistent,
348 data_path: None,
349 read_only: false,
350 create_if_missing: true,
351 verify_checksums: true,
352 durability_mode: DurabilityMode::WalDurableGrouped,
358 group_commit: GroupCommitOptions::default(),
359 auto_checkpoint_pages: 1000,
360 checkpoint_columnar_emission_budget_chunks: usize::MAX,
361 columnar_projection_size_floor_rows: 4,
362 cache_pages: 10_000,
363 snapshot_retention: DEFAULT_SNAPSHOT_RETENTION,
364 export_retention: DEFAULT_EXPORT_RETENTION,
365 feature_gates: CapabilitySet::new()
366 .with(Capability::Table)
367 .with(Capability::Graph)
368 .with(Capability::Vector),
369 force_create: true,
370 metadata: BTreeMap::new(),
371 remote_backend: None,
372 remote_backend_atomic: None,
373 remote_key: None,
374 replication: ReplicationConfig::standalone(),
375 replica_loop_enabled: true,
376 auth: AuthConfig::default(),
377 control_events: crate::runtime::control_events::ControlEventConfig::default(),
378 query_audit: crate::runtime::query_audit::QueryAuditConfig::default(),
379 auto_index_id: true,
380 layout: crate::storage::layout::StorageLayout::default(),
381 layout_overrides: crate::storage::layout::LayoutOverrides::default(),
382 storage_profile: crate::storage::profile::StorageProfileSelection::embedded_single_file(
383 ),
384 layout_explicit: false,
385 memory_budget_bytes: None,
386 bounded_disk_residency: false,
387 }
388 }
389}
390
391impl RedDBOptions {
392 pub fn persistent<P: Into<PathBuf>>(path: P) -> Self {
393 Self {
394 mode: StorageMode::Persistent,
395 data_path: Some(path.into()),
396 ..Default::default()
397 }
398 }
399
400 pub fn in_memory() -> Self {
407 static NEXT_EPHEMERAL_ID: std::sync::atomic::AtomicU64 =
408 std::sync::atomic::AtomicU64::new(0);
409
410 let now_nanos = std::time::SystemTime::now()
411 .duration_since(std::time::UNIX_EPOCH)
412 .map(|duration| duration.as_nanos())
413 .unwrap_or(0);
414 let unique = NEXT_EPHEMERAL_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
415 let dir = std::env::temp_dir().join(format!(
424 "reddb-ephemeral-{}-{}-{}",
425 std::process::id(),
426 now_nanos,
427 unique
428 ));
429 let _ = std::fs::create_dir_all(&dir);
430 let path = dir.join("db.rdb");
431 let _ = std::fs::remove_file(&path);
432 let mut metadata = BTreeMap::new();
433 metadata.insert(
434 EPHEMERAL_RUNTIME_METADATA_KEY.to_string(),
435 "true".to_string(),
436 );
437 Self {
438 mode: StorageMode::Persistent,
439 data_path: Some(path),
440 auto_checkpoint_pages: 0,
441 checkpoint_columnar_emission_budget_chunks: usize::MAX,
442 columnar_projection_size_floor_rows: 4,
443 cache_pages: 2_000,
444 snapshot_retention: DEFAULT_SNAPSHOT_RETENTION,
445 export_retention: DEFAULT_EXPORT_RETENTION,
446 read_only: false,
447 force_create: true,
448 metadata,
449 ..Default::default()
450 }
451 }
452
453 pub fn with_mode(mut self, mode: StorageMode) -> Self {
454 self.mode = mode;
455 self
456 }
457
458 pub fn with_data_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
459 if let Some(old) = self.data_path.take() {
465 let tmp = std::env::temp_dir();
466 if let Some(parent) = old.parent() {
467 let orphaned = parent
468 .file_name()
469 .and_then(|name| name.to_str())
470 .is_some_and(|name| name.starts_with("reddb-ephemeral-"))
471 && parent.parent() == Some(tmp.as_path());
472 if orphaned {
473 let _ = std::fs::remove_dir_all(parent);
474 }
475 }
476 }
477 self.data_path = Some(path.into());
478 self
479 }
480
481 pub fn with_read_only(mut self, read_only: bool) -> Self {
482 self.read_only = read_only;
483 self
484 }
485
486 pub fn with_auto_checkpoint(mut self, pages: u32) -> Self {
487 self.auto_checkpoint_pages = pages;
488 self
489 }
490
491 pub fn with_checkpoint_columnar_emission_budget_chunks(mut self, chunks: usize) -> Self {
492 self.checkpoint_columnar_emission_budget_chunks = chunks;
493 self
494 }
495
496 pub fn with_columnar_projection_size_floor_rows(mut self, rows: usize) -> Self {
497 self.columnar_projection_size_floor_rows = rows;
498 self
499 }
500
501 pub fn with_durability_mode(mut self, mode: DurabilityMode) -> Self {
502 self.durability_mode = mode;
503 self
504 }
505
506 pub fn with_group_commit_window_ms(mut self, window_ms: u64) -> Self {
507 self.group_commit.window_ms = window_ms;
510 self
511 }
512
513 pub fn with_group_commit_max_statements(mut self, max_statements: usize) -> Self {
514 self.group_commit.max_statements = max_statements.max(1);
515 self
516 }
517
518 pub fn with_group_commit_max_wal_bytes(mut self, max_wal_bytes: u64) -> Self {
519 self.group_commit.max_wal_bytes = max_wal_bytes.max(1);
520 self
521 }
522
523 pub fn with_cache_pages(mut self, pages: usize) -> Self {
524 self.cache_pages = pages.max(2);
525 self
526 }
527
528 pub fn with_snapshot_retention(mut self, limit: usize) -> Self {
529 self.snapshot_retention = limit.max(1);
530 self
531 }
532
533 pub fn with_export_retention(mut self, limit: usize) -> Self {
534 self.export_retention = limit.max(1);
535 self
536 }
537
538 pub fn with_metadata<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
539 self.metadata.insert(key.into(), value.into());
540 self
541 }
542
543 pub fn with_auto_index_id(mut self, enabled: bool) -> Self {
547 self.auto_index_id = enabled;
548 self
549 }
550
551 pub fn with_capability(mut self, capability: Capability) -> Self {
552 self.feature_gates = self.feature_gates.with(capability);
553 self
554 }
555
556 pub fn with_remote_backend(
562 mut self,
563 backend: Arc<dyn crate::storage::backend::RemoteBackend>,
564 key: impl Into<String>,
565 ) -> Self {
566 self.remote_backend = Some(backend);
567 self.remote_key = Some(key.into());
568 self
569 }
570
571 pub fn with_atomic_remote_backend(
577 mut self,
578 backend: Arc<dyn crate::storage::backend::AtomicRemoteBackend>,
579 ) -> Self {
580 self.remote_backend_atomic = Some(backend);
581 self
582 }
583
584 pub fn with_replication(mut self, config: ReplicationConfig) -> Self {
585 self.replication = config;
586 self
587 }
588
589 pub fn with_replica_loop_enabled(mut self, enabled: bool) -> Self {
590 self.replica_loop_enabled = enabled;
591 self
592 }
593
594 pub fn with_auth(mut self, config: AuthConfig) -> Self {
595 self.auth = config;
596 self
597 }
598
599 pub fn resolved_path(&self, fallback: impl AsRef<Path>) -> PathBuf {
600 self.data_path
601 .clone()
602 .unwrap_or_else(|| fallback.as_ref().to_path_buf())
603 }
604
605 pub fn remote_namespace_prefix(&self) -> String {
606 let Some(remote_key) = &self.remote_key else {
607 return String::new();
608 };
609 let normalized = remote_key.trim_matches('/');
610 if normalized.is_empty() {
611 return String::new();
612 }
613 match normalized.rsplit_once('/') {
614 Some((parent, _)) if !parent.is_empty() => format!("{parent}/"),
615 _ => String::new(),
616 }
617 }
618
619 pub fn default_backup_head_key(&self) -> String {
620 if let Some(value) = self.metadata.get("red.config.backup.head_key") {
621 return value.clone();
622 }
623 reddb_file::backup_head_key(&self.remote_namespace_prefix())
624 }
625
626 pub fn default_snapshot_prefix(&self) -> String {
627 if let Some(value) = self.metadata.get("red.config.backup.snapshot_prefix") {
628 return value.clone();
629 }
630 reddb_file::backup_snapshot_prefix(&self.remote_namespace_prefix())
631 }
632
633 pub fn default_wal_archive_prefix(&self) -> String {
634 if let Some(value) = self.metadata.get("red.config.wal.archive.prefix") {
635 return value.clone();
636 }
637 reddb_file::backup_wal_prefix(&self.remote_namespace_prefix())
638 }
639
640 pub fn has_capability(&self, capability: Capability) -> bool {
641 self.feature_gates.has(capability)
642 }
643
644 pub fn with_layout(mut self, layout: crate::storage::layout::StorageLayout) -> Self {
647 self.layout = layout;
648 self.layout_explicit = true;
649 self
650 }
651
652 pub fn with_layout_overrides(
655 mut self,
656 overrides: crate::storage::layout::LayoutOverrides,
657 ) -> Self {
658 self.layout_overrides = overrides;
659 self
660 }
661
662 pub fn with_memory_budget(mut self, bytes: u64) -> Self {
667 self.memory_budget_bytes = Some(bytes);
668 self
669 }
670
671 pub fn with_bounded_disk_residency(mut self, enabled: bool) -> Self {
674 self.bounded_disk_residency = enabled;
675 self
676 }
677
678 pub fn with_storage_profile(
679 mut self,
680 selection: crate::storage::profile::StorageProfileSelection,
681 ) -> Result<Self, String> {
682 self.storage_profile = selection.validate()?;
683 Ok(self)
684 }
685
686 pub fn resolve_tiered_layout(
690 &self,
691 ) -> Option<(PathBuf, crate::storage::layout::TieredLayoutPaths)> {
692 let data_path = self.data_path.clone()?;
693 let paths = crate::storage::layout::TieredLayoutPaths::new(
694 &data_path,
695 self.layout,
696 self.layout_overrides.clone(),
697 );
698 Some((data_path, paths))
699 }
700
701 pub fn apply_tier_defaults(&self) {
721 use crate::storage::layout::StorageLayout;
722
723 if !self.layout_explicit {
728 if let Some((_, paths)) = self.resolve_tiered_layout() {
729 tier_wiring::stash_layout_paths(paths);
730 }
731 return;
732 }
733
734 let layout = self.layout;
735 crate::physical::set_meta_json_sidecar_enabled(matches!(layout, StorageLayout::Max));
737
738 crate::physical::set_seqn_journal_enabled(matches!(layout, StorageLayout::Max));
742 crate::physical::set_seqn_journal_retention(match layout {
743 StorageLayout::Max => crate::physical::DEFAULT_METADATA_JOURNAL_RETENTION,
744 _ => crate::physical::OPT_IN_METADATA_JOURNAL_RETENTION,
745 });
746
747 crate::physical::set_shm_provisioning_enabled(matches!(
749 layout,
750 StorageLayout::Standard | StorageLayout::Performance | StorageLayout::Max
751 ));
752
753 crate::physical::set_fold_dwb_into_wal_enabled(matches!(layout, StorageLayout::Max));
757
758 if let Some((_, paths)) = self.resolve_tiered_layout() {
760 tier_wiring::stash_layout_paths(paths);
761 }
762 }
763}
764
765pub mod tier_wiring {
769 use std::sync::Mutex;
770
771 use crate::storage::layout::{LogDestination, TieredLayoutPaths};
772
773 static CURRENT_LAYOUT_PATHS: Mutex<Option<TieredLayoutPaths>> = Mutex::new(None);
774
775 pub fn stash_layout_paths(paths: TieredLayoutPaths) {
776 if let Ok(mut slot) = CURRENT_LAYOUT_PATHS.lock() {
777 *slot = Some(paths);
778 }
779 }
780
781 pub fn current_layout_paths() -> Option<TieredLayoutPaths> {
782 CURRENT_LAYOUT_PATHS
783 .lock()
784 .ok()
785 .and_then(|slot| slot.clone())
786 }
787
788 pub fn current_log_destinations() -> (LogDestination, LogDestination) {
792 match current_layout_paths() {
793 Some(p) => (p.audit_log_destination, p.slow_log_destination),
794 None => (LogDestination::Stderr, LogDestination::Stderr),
795 }
796 }
797}
798
799#[derive(Debug, Clone, Default)]
800pub struct CollectionStats {
801 pub entities: usize,
802 pub cross_refs: usize,
803 pub segments: usize,
804}
805
806#[derive(Debug, Clone)]
807pub struct CatalogSnapshot {
808 pub name: String,
809 pub total_entities: usize,
810 pub total_collections: usize,
811 pub stats_by_collection: BTreeMap<String, CollectionStats>,
812 pub updated_at: SystemTime,
813}
814
815impl Default for CatalogSnapshot {
816 fn default() -> Self {
817 Self {
818 name: String::new(),
819 total_entities: 0,
820 total_collections: 0,
821 stats_by_collection: BTreeMap::new(),
822 updated_at: UNIX_EPOCH,
823 }
824 }
825}
826
827#[derive(Debug, Clone)]
828pub struct SchemaManifest {
829 pub format_version: u32,
830 pub created_at_unix_ms: u128,
831 pub updated_at_unix_ms: u128,
832 pub options: RedDBOptions,
833 pub collection_count: usize,
834}
835
836impl SchemaManifest {
837 pub fn now(options: RedDBOptions, collection_count: usize) -> Self {
838 let now = SystemTime::now()
839 .duration_since(UNIX_EPOCH)
840 .unwrap_or_default()
841 .as_millis();
842 Self {
843 format_version: REDDB_FORMAT_VERSION,
844 created_at_unix_ms: now,
845 updated_at_unix_ms: now,
846 options,
847 collection_count,
848 }
849 }
850}
851
852pub use reddb_engine::storage::error::StorageIntegrityError;
853
854#[derive(Debug)]
855pub enum RedDBError {
856 InvalidConfig(String),
857 SchemaVersionMismatch {
858 expected: u32,
859 found: u32,
860 },
861 FeatureNotEnabled(String),
862 NotFound(String),
863 ReadOnly(String),
864 InvalidOperation(String),
865 Engine(String),
866 Catalog(String),
867 StorageIntegrity(StorageIntegrityError),
868 Query(String),
869 Validation {
870 message: String,
871 validation: crate::json::Value,
872 },
873 Io(io::Error),
874 VersionUnavailable,
875 QuotaExceeded(String),
881 MaterializationLimitExceeded {
890 executor: &'static str,
891 limit: usize,
892 current: usize,
893 },
894 Internal(String),
895}
896
897pub fn client_facing_message(err: &RedDBError) -> String {
903 match err {
904 RedDBError::Io(inner) => format!("io error: {:?}", inner.kind()),
905 RedDBError::Internal(_) => "internal error; see the server log".to_string(),
906 other => other.to_string(),
907 }
908}
909
910impl fmt::Display for RedDBError {
911 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912 match self {
913 Self::InvalidConfig(msg) => write!(f, "invalid config: {msg}"),
914 Self::SchemaVersionMismatch { expected, found } => {
915 write!(
916 f,
917 "schema version mismatch: expected {expected}, found {found}"
918 )
919 }
920 Self::FeatureNotEnabled(msg) => write!(f, "feature disabled: {msg}"),
921 Self::NotFound(msg) => write!(f, "not found: {msg}"),
922 Self::ReadOnly(msg) => write!(f, "read-only violation: {msg}"),
923 Self::InvalidOperation(msg) => write!(f, "INVALID_OPERATION: {msg}"),
924 Self::Engine(msg) => write!(f, "engine error: {msg}"),
925 Self::Catalog(msg) => write!(f, "catalog error: {msg}"),
926 Self::StorageIntegrity(err) => write!(f, "{err}"),
927 Self::Query(msg) => write!(f, "query error: {msg}"),
928 Self::Validation { message, .. } => write!(f, "validation error: {message}"),
929 Self::Io(err) => write!(f, "io error: {err}"),
930 Self::VersionUnavailable => write!(f, "version information unavailable"),
931 Self::QuotaExceeded(msg) => write!(f, "quota exceeded: {msg}"),
932 Self::MaterializationLimitExceeded {
933 executor,
934 limit,
935 current,
936 } => write!(
937 f,
938 "materialization limit exceeded: executor={executor} current={current} limit={limit}"
939 ),
940 Self::Internal(msg) => write!(f, "internal error: {msg}"),
941 }
942 }
943}
944
945impl std::error::Error for RedDBError {}
946
947impl From<io::Error> for RedDBError {
948 fn from(err: io::Error) -> Self {
949 Self::Io(err)
950 }
951}
952
953impl From<crate::storage::engine::DatabaseError> for RedDBError {
954 fn from(err: crate::storage::engine::DatabaseError) -> Self {
955 Self::Engine(err.to_string())
956 }
957}
958
959impl From<crate::storage::wal::TxError> for RedDBError {
960 fn from(err: crate::storage::wal::TxError) -> Self {
961 Self::Engine(err.to_string())
962 }
963}
964
965impl From<reddb_engine::catalog::enforcement::ContractError> for RedDBError {
966 fn from(error: reddb_engine::catalog::enforcement::ContractError) -> Self {
967 match error {
968 reddb_engine::catalog::enforcement::ContractError::Query(message) => {
969 Self::Query(message)
970 }
971 reddb_engine::catalog::enforcement::ContractError::InvalidOperation(message) => {
972 Self::InvalidOperation(message)
973 }
974 }
975 }
976}
977
978impl From<reddb_engine::catalog::schema::ContractExpressionError> for RedDBError {
979 fn from(error: reddb_engine::catalog::schema::ContractExpressionError) -> Self {
980 Self::Query(error.message)
981 }
982}
983
984impl From<crate::storage::StoreError> for RedDBError {
985 fn from(err: crate::storage::StoreError) -> Self {
986 match err {
987 crate::storage::StoreError::StorageIntegrity(err) => Self::StorageIntegrity(err),
988 other => Self::Catalog(other.to_string()),
989 }
990 }
991}
992
993impl From<crate::storage::unified::devx::DevXError> for RedDBError {
994 fn from(err: crate::storage::unified::devx::DevXError) -> Self {
995 match err {
996 crate::storage::unified::devx::DevXError::Validation(msg) => Self::InvalidConfig(msg),
997 crate::storage::unified::devx::DevXError::Storage(msg) => Self::Engine(msg),
998 crate::storage::unified::devx::DevXError::NotFound(msg) => Self::NotFound(msg),
999 }
1000 }
1001}
1002
1003pub trait CatalogService {
1004 fn list_collections(&self) -> Vec<String>;
1005 fn collection_stats(&self, collection: &str) -> Option<CollectionStats>;
1006 fn catalog_snapshot(&self) -> CatalogSnapshot;
1007}
1008
1009pub trait QueryPlanner {
1010 fn plan_cost(&self, query: &str) -> Option<f64>;
1011}
1012
1013pub trait DataOps {
1014 fn execute_query(&self, query: &str) -> RedDBResult<()>;
1015}
1016
1017pub mod prelude {
1018 pub use super::{
1019 Capability, CapabilitySet, CatalogService, CatalogSnapshot, CollectionStats, DataOps,
1020 QueryPlanner, RedDBError, RedDBOptions, RedDBResult, SchemaManifest, StorageMode,
1021 REDDB_FORMAT_VERSION, REDDB_PROTOCOL_VERSION,
1022 };
1023}
1024
1025#[cfg(test)]
1026mod client_facing_message_tests {
1027 use super::{client_facing_message, RedDBError};
1028
1029 #[test]
1030 fn client_facing_message_hides_io_and_internal_detail() {
1031 let io = RedDBError::Io(std::io::Error::new(
1032 std::io::ErrorKind::NotFound,
1033 "/var/lib/reddb/data.rdb: No such file",
1034 ));
1035 assert_eq!(client_facing_message(&io), "io error: NotFound");
1036 let internal = RedDBError::Internal("pager invariant broke at /srv/db.wal".to_string());
1037 assert!(!client_facing_message(&internal).contains("/srv"));
1038 let query = RedDBError::Query("unknown column `x`".to_string());
1039 assert_eq!(client_facing_message(&query), query.to_string());
1040 }
1041}