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 InMemory,
50}
51
52impl StorageMode {
53 pub const fn is_persistent(self) -> bool {
54 matches!(self, Self::Persistent)
55 }
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
59pub enum DurabilityMode {
60 #[default]
61 Strict,
62 WalDurableGrouped,
63 Async,
71}
72
73impl DurabilityMode {
74 pub const fn as_str(self) -> &'static str {
75 match self {
76 Self::Strict => "strict",
77 Self::WalDurableGrouped => "wal_durable_grouped",
78 Self::Async => "async",
79 }
80 }
81
82 pub fn from_str(value: &str) -> Option<Self> {
83 let normalized = value.trim().to_ascii_lowercase();
84 match normalized.as_str() {
85 "strict" => Some(Self::Strict),
87 "sync"
93 | "wal_durable_grouped"
94 | "wal-durable-grouped"
95 | "grouped"
96 | "wal_grouped"
97 | "wal-grouped" => Some(Self::WalDurableGrouped),
98 "async" | "fire_and_forget" | "fire-and-forget" => Some(Self::Async),
102 _ => None,
103 }
104 }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub struct GroupCommitOptions {
109 pub window_ms: u64,
110 pub max_statements: usize,
111 pub max_wal_bytes: u64,
112}
113
114impl Default for GroupCommitOptions {
115 fn default() -> Self {
116 Self {
117 window_ms: DEFAULT_GROUP_COMMIT_WINDOW_MS,
118 max_statements: DEFAULT_GROUP_COMMIT_MAX_STATEMENTS,
119 max_wal_bytes: DEFAULT_GROUP_COMMIT_MAX_WAL_BYTES,
120 }
121 }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
125pub enum Capability {
126 Table,
128 Graph,
130 Vector,
132 FullText,
134 Security,
136 Encryption,
138}
139
140impl Capability {
141 pub const fn as_str(self) -> &'static str {
142 match self {
143 Self::Table => "table",
144 Self::Graph => "graph",
145 Self::Vector => "vector",
146 Self::FullText => "fulltext",
147 Self::Security => "security",
148 Self::Encryption => "encryption",
149 }
150 }
151}
152
153#[derive(Debug, Clone, Default)]
154pub struct CapabilitySet {
155 items: BTreeSet<Capability>,
156}
157
158impl CapabilitySet {
159 pub fn new() -> Self {
160 Self::default()
161 }
162
163 pub fn with(mut self, capability: Capability) -> Self {
164 self.items.insert(capability);
165 self
166 }
167
168 pub fn with_all(mut self, capabilities: &[Capability]) -> Self {
169 capabilities.iter().copied().for_each(|capability| {
170 self.items.insert(capability);
171 });
172 self
173 }
174
175 pub fn has(&self, capability: Capability) -> bool {
176 self.items.contains(&capability)
177 }
178
179 pub fn as_slice(&self) -> Vec<Capability> {
180 self.items.iter().copied().collect()
181 }
182}
183
184pub struct RedDBOptions {
185 pub mode: StorageMode,
186 pub data_path: Option<PathBuf>,
187 pub read_only: bool,
188 pub create_if_missing: bool,
189 pub verify_checksums: bool,
190 pub durability_mode: DurabilityMode,
191 pub group_commit: GroupCommitOptions,
192 pub auto_checkpoint_pages: u32,
193 pub checkpoint_columnar_emission_budget_chunks: usize,
196 pub columnar_projection_size_floor_rows: usize,
199 pub cache_pages: usize,
200 pub snapshot_retention: usize,
201 pub export_retention: usize,
202 pub feature_gates: CapabilitySet,
203 pub force_create: bool,
204 pub metadata: BTreeMap<String, String>,
205 pub remote_backend: Option<Arc<dyn crate::storage::backend::RemoteBackend>>,
207 pub remote_backend_atomic: Option<Arc<dyn crate::storage::backend::AtomicRemoteBackend>>,
214 pub remote_key: Option<String>,
216 #[doc(hidden)]
220 pub remote_bootstrap_key: Option<String>,
221 pub replication: ReplicationConfig,
223 pub replica_loop_enabled: bool,
225 pub auth: AuthConfig,
227 pub control_events: crate::runtime::control_events::ControlEventConfig,
230 pub query_audit: crate::runtime::query_audit::QueryAuditConfig,
234 pub auto_index_id: bool,
240 pub layout: crate::storage::layout::StorageLayout,
246 pub layout_overrides: crate::storage::layout::LayoutOverrides,
248 pub storage_profile: crate::storage::profile::StorageProfileSelection,
251 pub layout_explicit: bool,
257 pub memory_budget_bytes: Option<u64>,
263 pub bounded_disk_residency: bool,
268}
269
270impl fmt::Debug for RedDBOptions {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 let backend_name = self.remote_backend.as_ref().map(|b| b.name().to_string());
273 f.debug_struct("RedDBOptions")
274 .field("mode", &self.mode)
275 .field("data_path", &self.data_path)
276 .field("read_only", &self.read_only)
277 .field("create_if_missing", &self.create_if_missing)
278 .field("verify_checksums", &self.verify_checksums)
279 .field("durability_mode", &self.durability_mode)
280 .field("group_commit", &self.group_commit)
281 .field("auto_checkpoint_pages", &self.auto_checkpoint_pages)
282 .field(
283 "checkpoint_columnar_emission_budget_chunks",
284 &self.checkpoint_columnar_emission_budget_chunks,
285 )
286 .field(
287 "columnar_projection_size_floor_rows",
288 &self.columnar_projection_size_floor_rows,
289 )
290 .field("cache_pages", &self.cache_pages)
291 .field("snapshot_retention", &self.snapshot_retention)
292 .field("export_retention", &self.export_retention)
293 .field("feature_gates", &self.feature_gates)
294 .field("force_create", &self.force_create)
295 .field("metadata", &self.metadata)
296 .field("remote_backend", &backend_name)
297 .field("remote_key", &self.remote_key)
298 .field("remote_bootstrap_key", &self.remote_bootstrap_key)
299 .field("replication", &self.replication)
300 .field("replica_loop_enabled", &self.replica_loop_enabled)
301 .field("auth", &self.auth)
302 .field("control_events", &self.control_events)
303 .field("query_audit", &self.query_audit)
304 .field("layout", &self.layout)
305 .field("layout_overrides", &self.layout_overrides)
306 .field("storage_profile", &self.storage_profile)
307 .field("memory_budget_bytes", &self.memory_budget_bytes)
308 .field("bounded_disk_residency", &self.bounded_disk_residency)
309 .finish()
310 }
311}
312
313impl Clone for RedDBOptions {
314 fn clone(&self) -> Self {
315 Self {
316 mode: self.mode,
317 data_path: self.data_path.clone(),
318 read_only: self.read_only,
319 create_if_missing: self.create_if_missing,
320 verify_checksums: self.verify_checksums,
321 durability_mode: self.durability_mode,
322 group_commit: self.group_commit,
323 auto_checkpoint_pages: self.auto_checkpoint_pages,
324 checkpoint_columnar_emission_budget_chunks: self
325 .checkpoint_columnar_emission_budget_chunks,
326 columnar_projection_size_floor_rows: self.columnar_projection_size_floor_rows,
327 cache_pages: self.cache_pages,
328 snapshot_retention: self.snapshot_retention,
329 export_retention: self.export_retention,
330 feature_gates: self.feature_gates.clone(),
331 force_create: self.force_create,
332 metadata: self.metadata.clone(),
333 remote_backend: self.remote_backend.clone(),
334 remote_backend_atomic: self.remote_backend_atomic.clone(),
335 remote_key: self.remote_key.clone(),
336 remote_bootstrap_key: self.remote_bootstrap_key.clone(),
337 replication: self.replication.clone(),
338 replica_loop_enabled: self.replica_loop_enabled,
339 auth: self.auth.clone(),
340 control_events: self.control_events,
341 query_audit: self.query_audit.clone(),
342 auto_index_id: self.auto_index_id,
343 layout: self.layout,
344 layout_overrides: self.layout_overrides.clone(),
345 storage_profile: self.storage_profile,
346 layout_explicit: self.layout_explicit,
347 memory_budget_bytes: self.memory_budget_bytes,
348 bounded_disk_residency: self.bounded_disk_residency,
349 }
350 }
351}
352
353impl Default for RedDBOptions {
354 fn default() -> Self {
355 Self {
356 mode: StorageMode::Persistent,
357 data_path: None,
358 read_only: false,
359 create_if_missing: true,
360 verify_checksums: true,
361 durability_mode: DurabilityMode::WalDurableGrouped,
367 group_commit: GroupCommitOptions::default(),
368 auto_checkpoint_pages: 1000,
369 checkpoint_columnar_emission_budget_chunks: usize::MAX,
370 columnar_projection_size_floor_rows: 4,
371 cache_pages: 10_000,
372 snapshot_retention: DEFAULT_SNAPSHOT_RETENTION,
373 export_retention: DEFAULT_EXPORT_RETENTION,
374 feature_gates: CapabilitySet::new()
375 .with(Capability::Table)
376 .with(Capability::Graph)
377 .with(Capability::Vector),
378 force_create: true,
379 metadata: BTreeMap::new(),
380 remote_backend: None,
381 remote_backend_atomic: None,
382 remote_key: None,
383 remote_bootstrap_key: None,
384 replication: ReplicationConfig::standalone(),
385 replica_loop_enabled: true,
386 auth: AuthConfig::default(),
387 control_events: crate::runtime::control_events::ControlEventConfig::default(),
388 query_audit: crate::runtime::query_audit::QueryAuditConfig::default(),
389 auto_index_id: true,
390 layout: crate::storage::layout::StorageLayout::default(),
391 layout_overrides: crate::storage::layout::LayoutOverrides::default(),
392 storage_profile: crate::storage::profile::StorageProfileSelection::embedded_single_file(
393 ),
394 layout_explicit: false,
395 memory_budget_bytes: None,
396 bounded_disk_residency: false,
397 }
398 }
399}
400
401impl RedDBOptions {
402 pub fn persistent<P: Into<PathBuf>>(path: P) -> Self {
403 Self {
404 mode: StorageMode::Persistent,
405 data_path: Some(path.into()),
406 ..Default::default()
407 }
408 }
409
410 pub fn memory_only() -> Self {
412 Self {
413 mode: StorageMode::InMemory,
414 auto_checkpoint_pages: 0,
415 ..Default::default()
416 }
417 }
418
419 pub fn in_memory() -> Self {
421 Self::temporary()
422 }
423
424 pub fn temporary() -> Self {
430 static NEXT_EPHEMERAL_ID: std::sync::atomic::AtomicU64 =
431 std::sync::atomic::AtomicU64::new(0);
432
433 let now_nanos = std::time::SystemTime::now()
434 .duration_since(std::time::UNIX_EPOCH)
435 .map(|duration| duration.as_nanos())
436 .unwrap_or(0);
437 let unique = NEXT_EPHEMERAL_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
438 let dir = std::env::temp_dir().join(format!(
447 "reddb-ephemeral-{}-{}-{}",
448 std::process::id(),
449 now_nanos,
450 unique
451 ));
452 let _ = std::fs::create_dir_all(&dir);
453 let path = dir.join("db.rdb");
454 let _ = std::fs::remove_file(&path);
455 let mut metadata = BTreeMap::new();
456 metadata.insert(
457 EPHEMERAL_RUNTIME_METADATA_KEY.to_string(),
458 "true".to_string(),
459 );
460 Self {
461 mode: StorageMode::Persistent,
462 data_path: Some(path),
463 auto_checkpoint_pages: 0,
464 checkpoint_columnar_emission_budget_chunks: usize::MAX,
465 columnar_projection_size_floor_rows: 4,
466 cache_pages: 2_000,
467 snapshot_retention: DEFAULT_SNAPSHOT_RETENTION,
468 export_retention: DEFAULT_EXPORT_RETENTION,
469 read_only: false,
470 force_create: true,
471 metadata,
472 ..Default::default()
473 }
474 }
475
476 pub fn with_mode(mut self, mode: StorageMode) -> Self {
477 self.mode = mode;
478 self
479 }
480
481 pub fn with_data_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
482 if let Some(old) = self.data_path.take() {
488 let tmp = std::env::temp_dir();
489 if let Some(parent) = old.parent() {
490 let orphaned = parent
491 .file_name()
492 .and_then(|name| name.to_str())
493 .is_some_and(|name| name.starts_with("reddb-ephemeral-"))
494 && parent.parent() == Some(tmp.as_path());
495 if orphaned {
496 let _ = std::fs::remove_dir_all(parent);
497 }
498 }
499 }
500 self.data_path = Some(path.into());
501 self
502 }
503
504 pub fn with_read_only(mut self, read_only: bool) -> Self {
505 self.read_only = read_only;
506 self
507 }
508
509 pub fn with_auto_checkpoint(mut self, pages: u32) -> Self {
510 self.auto_checkpoint_pages = pages;
511 self
512 }
513
514 pub fn with_checkpoint_columnar_emission_budget_chunks(mut self, chunks: usize) -> Self {
515 self.checkpoint_columnar_emission_budget_chunks = chunks;
516 self
517 }
518
519 pub fn with_columnar_projection_size_floor_rows(mut self, rows: usize) -> Self {
520 self.columnar_projection_size_floor_rows = rows;
521 self
522 }
523
524 pub fn with_durability_mode(mut self, mode: DurabilityMode) -> Self {
525 self.durability_mode = mode;
526 self
527 }
528
529 pub fn with_group_commit_window_ms(mut self, window_ms: u64) -> Self {
530 self.group_commit.window_ms = window_ms;
533 self
534 }
535
536 pub fn with_group_commit_max_statements(mut self, max_statements: usize) -> Self {
537 self.group_commit.max_statements = max_statements.max(1);
538 self
539 }
540
541 pub fn with_group_commit_max_wal_bytes(mut self, max_wal_bytes: u64) -> Self {
542 self.group_commit.max_wal_bytes = max_wal_bytes.max(1);
543 self
544 }
545
546 pub fn with_cache_pages(mut self, pages: usize) -> Self {
547 self.cache_pages = pages.max(2);
548 self
549 }
550
551 pub fn with_snapshot_retention(mut self, limit: usize) -> Self {
552 self.snapshot_retention = limit.max(1);
553 self
554 }
555
556 pub fn with_export_retention(mut self, limit: usize) -> Self {
557 self.export_retention = limit.max(1);
558 self
559 }
560
561 pub fn with_metadata<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
562 self.metadata.insert(key.into(), value.into());
563 self
564 }
565
566 pub fn with_auto_index_id(mut self, enabled: bool) -> Self {
570 self.auto_index_id = enabled;
571 self
572 }
573
574 pub fn with_capability(mut self, capability: Capability) -> Self {
575 self.feature_gates = self.feature_gates.with(capability);
576 self
577 }
578
579 pub fn with_remote_backend(
585 mut self,
586 backend: Arc<dyn crate::storage::backend::RemoteBackend>,
587 key: impl Into<String>,
588 ) -> Self {
589 self.remote_backend = Some(backend);
590 self.remote_key = Some(key.into());
591 self
592 }
593
594 pub fn with_atomic_remote_backend(
600 mut self,
601 backend: Arc<dyn crate::storage::backend::AtomicRemoteBackend>,
602 ) -> Self {
603 self.remote_backend_atomic = Some(backend);
604 self
605 }
606
607 pub fn with_replication(mut self, config: ReplicationConfig) -> Self {
608 self.replication = config;
609 self
610 }
611
612 pub fn with_replica_loop_enabled(mut self, enabled: bool) -> Self {
613 self.replica_loop_enabled = enabled;
614 self
615 }
616
617 pub fn with_auth(mut self, config: AuthConfig) -> Self {
618 self.auth = config;
619 self
620 }
621
622 pub fn resolved_path(&self, fallback: impl AsRef<Path>) -> PathBuf {
623 self.data_path
624 .clone()
625 .unwrap_or_else(|| fallback.as_ref().to_path_buf())
626 }
627
628 pub fn remote_namespace_prefix(&self) -> String {
629 let Some(remote_key) = &self.remote_key else {
630 return String::new();
631 };
632 let normalized = remote_key.trim_matches('/');
633 if normalized.is_empty() {
634 return String::new();
635 }
636 match normalized.rsplit_once('/') {
637 Some((parent, _)) if !parent.is_empty() => format!("{parent}/"),
638 _ => String::new(),
639 }
640 }
641
642 pub fn default_backup_head_key(&self) -> String {
643 if let Some(value) = self.metadata.get("red.config.backup.head_key") {
644 return value.clone();
645 }
646 reddb_file::backup_head_key(&self.remote_namespace_prefix())
647 }
648
649 pub fn default_snapshot_prefix(&self) -> String {
650 if let Some(value) = self.metadata.get("red.config.backup.snapshot_prefix") {
651 return value.clone();
652 }
653 reddb_file::backup_snapshot_prefix(&self.remote_namespace_prefix())
654 }
655
656 pub fn default_wal_archive_prefix(&self) -> String {
657 if let Some(value) = self.metadata.get("red.config.wal.archive.prefix") {
658 return value.clone();
659 }
660 reddb_file::backup_wal_prefix(&self.remote_namespace_prefix())
661 }
662
663 pub fn has_capability(&self, capability: Capability) -> bool {
664 self.feature_gates.has(capability)
665 }
666
667 pub fn with_layout(mut self, layout: crate::storage::layout::StorageLayout) -> Self {
670 self.layout = layout;
671 self.layout_explicit = true;
672 self
673 }
674
675 pub fn with_layout_overrides(
678 mut self,
679 overrides: crate::storage::layout::LayoutOverrides,
680 ) -> Self {
681 self.layout_overrides = overrides;
682 self
683 }
684
685 pub fn with_memory_budget(mut self, bytes: u64) -> Self {
690 self.memory_budget_bytes = Some(bytes);
691 self
692 }
693
694 pub fn with_bounded_disk_residency(mut self, enabled: bool) -> Self {
697 self.bounded_disk_residency = enabled;
698 self
699 }
700
701 pub fn with_storage_profile(
702 mut self,
703 selection: crate::storage::profile::StorageProfileSelection,
704 ) -> Result<Self, String> {
705 self.storage_profile = selection.validate()?;
706 Ok(self)
707 }
708
709 pub fn resolve_tiered_layout(
713 &self,
714 ) -> Option<(PathBuf, crate::storage::layout::TieredLayoutPaths)> {
715 let data_path = self.data_path.clone()?;
716 let paths = crate::storage::layout::TieredLayoutPaths::new(
717 &data_path,
718 self.layout,
719 self.layout_overrides.clone(),
720 );
721 Some((data_path, paths))
722 }
723
724 pub fn apply_tier_defaults(&self) {
744 use crate::storage::layout::StorageLayout;
745
746 if !self.layout_explicit {
751 if let Some((_, paths)) = self.resolve_tiered_layout() {
752 tier_wiring::stash_layout_paths(paths);
753 }
754 return;
755 }
756
757 let layout = self.layout;
758 crate::physical::set_meta_json_sidecar_enabled(matches!(layout, StorageLayout::Max));
760
761 crate::physical::set_seqn_journal_enabled(matches!(layout, StorageLayout::Max));
765 crate::physical::set_seqn_journal_retention(match layout {
766 StorageLayout::Max => crate::physical::DEFAULT_METADATA_JOURNAL_RETENTION,
767 _ => crate::physical::OPT_IN_METADATA_JOURNAL_RETENTION,
768 });
769
770 crate::physical::set_shm_provisioning_enabled(matches!(
772 layout,
773 StorageLayout::Standard | StorageLayout::Performance | StorageLayout::Max
774 ));
775
776 crate::physical::set_fold_dwb_into_wal_enabled(matches!(layout, StorageLayout::Max));
780
781 if let Some((_, paths)) = self.resolve_tiered_layout() {
783 tier_wiring::stash_layout_paths(paths);
784 }
785 }
786}
787
788pub mod tier_wiring {
792 use std::sync::Mutex;
793
794 use crate::storage::layout::{LogDestination, TieredLayoutPaths};
795
796 static CURRENT_LAYOUT_PATHS: Mutex<Option<TieredLayoutPaths>> = Mutex::new(None);
797
798 pub fn stash_layout_paths(paths: TieredLayoutPaths) {
799 if let Ok(mut slot) = CURRENT_LAYOUT_PATHS.lock() {
800 *slot = Some(paths);
801 }
802 }
803
804 pub fn current_layout_paths() -> Option<TieredLayoutPaths> {
805 CURRENT_LAYOUT_PATHS
806 .lock()
807 .ok()
808 .and_then(|slot| slot.clone())
809 }
810
811 pub fn current_log_destinations() -> (LogDestination, LogDestination) {
815 match current_layout_paths() {
816 Some(p) => (p.audit_log_destination, p.slow_log_destination),
817 None => (LogDestination::Stderr, LogDestination::Stderr),
818 }
819 }
820}
821
822#[derive(Debug, Clone, Default)]
823pub struct CollectionStats {
824 pub entities: usize,
825 pub cross_refs: usize,
826 pub segments: usize,
827}
828
829#[derive(Debug, Clone)]
830pub struct CatalogSnapshot {
831 pub name: String,
832 pub total_entities: usize,
833 pub total_collections: usize,
834 pub stats_by_collection: BTreeMap<String, CollectionStats>,
835 pub updated_at: SystemTime,
836}
837
838impl Default for CatalogSnapshot {
839 fn default() -> Self {
840 Self {
841 name: String::new(),
842 total_entities: 0,
843 total_collections: 0,
844 stats_by_collection: BTreeMap::new(),
845 updated_at: UNIX_EPOCH,
846 }
847 }
848}
849
850#[derive(Debug, Clone)]
851pub struct SchemaManifest {
852 pub format_version: u32,
853 pub created_at_unix_ms: u128,
854 pub updated_at_unix_ms: u128,
855 pub options: RedDBOptions,
856 pub collection_count: usize,
857}
858
859impl SchemaManifest {
860 pub fn now(options: RedDBOptions, collection_count: usize) -> Self {
861 let now = SystemTime::now()
862 .duration_since(UNIX_EPOCH)
863 .unwrap_or_default()
864 .as_millis();
865 Self {
866 format_version: REDDB_FORMAT_VERSION,
867 created_at_unix_ms: now,
868 updated_at_unix_ms: now,
869 options,
870 collection_count,
871 }
872 }
873}
874
875pub use reddb_engine::storage::error::StorageIntegrityError;
876
877#[derive(Debug)]
878pub enum RedDBError {
879 InvalidConfig(String),
880 SchemaVersionMismatch {
881 expected: u32,
882 found: u32,
883 },
884 FeatureNotEnabled(String),
885 NotFound(String),
886 ReadOnly(String),
887 CommitUncertain {
890 lsn: u64,
891 detail: String,
892 },
893 InvalidOperation(String),
894 Engine(String),
895 Catalog(String),
896 StorageIntegrity(StorageIntegrityError),
897 Query(String),
898 Validation {
899 message: String,
900 validation: crate::json::Value,
901 },
902 Io(io::Error),
903 VersionUnavailable,
904 QuotaExceeded(String),
910 MaterializationLimitExceeded {
919 executor: &'static str,
920 limit: usize,
921 current: usize,
922 },
923 Internal(String),
924}
925
926pub fn client_facing_message(err: &RedDBError) -> String {
932 match err {
933 RedDBError::Io(inner) => format!("io error: {:?}", inner.kind()),
934 RedDBError::Internal(_) => "internal error; see the server log".to_string(),
935 other => other.to_string(),
936 }
937}
938
939impl fmt::Display for RedDBError {
940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
941 match self {
942 Self::InvalidConfig(msg) => write!(f, "invalid config: {msg}"),
943 Self::SchemaVersionMismatch { expected, found } => {
944 write!(
945 f,
946 "schema version mismatch: expected {expected}, found {found}"
947 )
948 }
949 Self::FeatureNotEnabled(msg) => write!(f, "feature disabled: {msg}"),
950 Self::NotFound(msg) => write!(f, "not found: {msg}"),
951 Self::ReadOnly(msg) => write!(f, "read-only violation: {msg}"),
952 Self::CommitUncertain { lsn, detail } => write!(f,
953 "commit_uncertain: commit policy timed out at lsn {lsn}: {detail}; local commit is durable; replica durability is unconfirmed"),
954 Self::InvalidOperation(msg) => write!(f, "INVALID_OPERATION: {msg}"),
955 Self::Engine(msg) => write!(f, "engine error: {msg}"),
956 Self::Catalog(msg) => write!(f, "catalog error: {msg}"),
957 Self::StorageIntegrity(err) => write!(f, "{err}"),
958 Self::Query(msg) => write!(f, "query error: {msg}"),
959 Self::Validation { message, .. } => write!(f, "validation error: {message}"),
960 Self::Io(err) => write!(f, "io error: {err}"),
961 Self::VersionUnavailable => write!(f, "version information unavailable"),
962 Self::QuotaExceeded(msg) => write!(f, "quota exceeded: {msg}"),
963 Self::MaterializationLimitExceeded {
964 executor,
965 limit,
966 current,
967 } => write!(
968 f,
969 "materialization limit exceeded: executor={executor} current={current} limit={limit}"
970 ),
971 Self::Internal(msg) => write!(f, "internal error: {msg}"),
972 }
973 }
974}
975
976impl std::error::Error for RedDBError {}
977
978impl From<io::Error> for RedDBError {
979 fn from(err: io::Error) -> Self {
980 Self::Io(err)
981 }
982}
983
984impl From<crate::storage::engine::DatabaseError> for RedDBError {
985 fn from(err: crate::storage::engine::DatabaseError) -> Self {
986 Self::Engine(err.to_string())
987 }
988}
989
990impl From<crate::storage::wal::TxError> for RedDBError {
991 fn from(err: crate::storage::wal::TxError) -> Self {
992 Self::Engine(err.to_string())
993 }
994}
995
996impl From<reddb_engine::catalog::enforcement::ContractError> for RedDBError {
997 fn from(error: reddb_engine::catalog::enforcement::ContractError) -> Self {
998 match error {
999 reddb_engine::catalog::enforcement::ContractError::Query(message) => {
1000 Self::Query(message)
1001 }
1002 reddb_engine::catalog::enforcement::ContractError::InvalidOperation(message) => {
1003 Self::InvalidOperation(message)
1004 }
1005 }
1006 }
1007}
1008
1009impl From<reddb_engine::catalog::schema::ContractExpressionError> for RedDBError {
1010 fn from(error: reddb_engine::catalog::schema::ContractExpressionError) -> Self {
1011 Self::Query(error.message)
1012 }
1013}
1014
1015impl From<crate::storage::StoreError> for RedDBError {
1016 fn from(err: crate::storage::StoreError) -> Self {
1017 match err {
1018 crate::storage::StoreError::StorageIntegrity(err) => Self::StorageIntegrity(err),
1019 other => Self::Catalog(other.to_string()),
1020 }
1021 }
1022}
1023
1024impl From<crate::storage::unified::devx::DevXError> for RedDBError {
1025 fn from(err: crate::storage::unified::devx::DevXError) -> Self {
1026 match err {
1027 crate::storage::unified::devx::DevXError::Validation(msg) => Self::InvalidConfig(msg),
1028 crate::storage::unified::devx::DevXError::Storage(msg) => Self::Engine(msg),
1029 crate::storage::unified::devx::DevXError::NotFound(msg) => Self::NotFound(msg),
1030 }
1031 }
1032}
1033
1034pub trait CatalogService {
1035 fn list_collections(&self) -> Vec<String>;
1036 fn collection_stats(&self, collection: &str) -> Option<CollectionStats>;
1037 fn catalog_snapshot(&self) -> CatalogSnapshot;
1038}
1039
1040pub trait QueryPlanner {
1041 fn plan_cost(&self, query: &str) -> Option<f64>;
1042}
1043
1044pub trait DataOps {
1045 fn execute_query(&self, query: &str) -> RedDBResult<()>;
1046}
1047
1048pub mod prelude {
1049 pub use super::{
1050 Capability, CapabilitySet, CatalogService, CatalogSnapshot, CollectionStats, DataOps,
1051 QueryPlanner, RedDBError, RedDBOptions, RedDBResult, SchemaManifest, StorageMode,
1052 REDDB_FORMAT_VERSION, REDDB_PROTOCOL_VERSION,
1053 };
1054}
1055
1056#[cfg(test)]
1057mod client_facing_message_tests {
1058 use super::{client_facing_message, RedDBError};
1059
1060 #[test]
1061 fn client_facing_message_hides_io_and_internal_detail() {
1062 let io = RedDBError::Io(std::io::Error::new(
1063 std::io::ErrorKind::NotFound,
1064 "/var/lib/reddb/data.rdb: No such file",
1065 ));
1066 assert_eq!(client_facing_message(&io), "io error: NotFound");
1067 let internal = RedDBError::Internal("pager invariant broke at /srv/db.wal".to_string());
1068 assert!(!client_facing_message(&internal).contains("/srv"));
1069 let query = RedDBError::Query("unknown column `x`".to_string());
1070 assert_eq!(client_facing_message(&query), query.to_string());
1071 }
1072}