Skip to main content

reddb_server/
api.rs

1//! Public API layer for the RedDB crate.
2//!
3//! This module is the first layer to consume from applications:
4//! - stable options and contracts
5//! - capability declarations
6//! - typed errors and lightweight metadata snapshots
7//! - cross-layer traits for catalog/operations observability
8
9use 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;
24/// Default group-commit window.
25///
26/// `0` = "no wait" — the background flusher fsyncs as soon as any
27/// writer's pending commit arrives. Under single-writer workloads a
28/// non-zero window would be pure latency (no one to batch with),
29/// capping individual commit throughput at ~1000/s for window=1.
30/// Concurrent writers still batch naturally via the `Mutex<WalWriter>`
31/// contention path without needing an explicit timer.
32///
33/// Operators with many concurrent clients can raise this (e.g. 1-5ms)
34/// to amortise fsync cost across a bigger batch — at the cost of p99
35/// tail latency going up by the window size.
36pub 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    /// Durable, file-backed database with WAL + checkpointing.
46    #[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    /// Fire-and-forget. Writers return as soon as the WAL record is
62    /// in the in-memory ring buffer — they do NOT wait for fsync.
63    /// The group-commit background thread still flushes on its
64    /// cadence, so committed-but-unflushed work is bounded by
65    /// `GroupCommitOptions::window_ms`. A crash inside the window
66    /// drops whatever wasn't flushed — matches PG's
67    /// `synchronous_commit=off` contract.
68    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            // Legacy / opt-out form. Every commit pays its own fsync.
84            "strict" => Some(Self::Strict),
85            // Group-commit sync path — the perf-parity default. Matches
86            // PostgreSQL's `synchronous_commit=on` behaviour: the
87            // writer waits for durability, but fsyncs are batched
88            // across concurrent writers so a burst of N commits pays
89            // ~O(1) fsyncs instead of O(N).
90            "sync"
91            | "wal_durable_grouped"
92            | "wal-durable-grouped"
93            | "grouped"
94            | "wal_grouped"
95            | "wal-grouped" => Some(Self::WalDurableGrouped),
96            // Fire-and-forget async: writers return as soon as the
97            // WAL buffer accepts the record; background flusher runs
98            // on its configured cadence.
99            "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    /// Structured row storage.
125    Table,
126    /// Graph nodes/edges.
127    Graph,
128    /// Vector collections and ANN search.
129    Vector,
130    /// Full-text / lexical search.
131    FullText,
132    /// Text/metadata security and enrichment modules.
133    Security,
134    /// Encryption at rest.
135    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    /// Maximum hypertable chunks the checkpoint path may seal into derived
192    /// columnar artifacts per checkpoint. `usize::MAX` means no practical cap.
193    pub checkpoint_columnar_emission_budget_chunks: usize,
194    /// Minimum rows a sealed in-scope chunk must carry before the derived
195    /// columnar projection is materialized.
196    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    /// Optional remote storage backend for snapshot transport.
204    pub remote_backend: Option<Arc<dyn crate::storage::backend::RemoteBackend>>,
205    /// Optional CAS-capable handle to the same backend, populated by
206    /// the factory when the configured backend implements
207    /// `AtomicRemoteBackend` (S3/local always; HTTP only when
208    /// `RED_HTTP_CONDITIONAL_WRITES=true`). `None` for backends that
209    /// do not provide compare-and-swap (Turso, D1, plain HTTP).
210    /// `LeaseStore` and any future CAS consumer pull from this field.
211    pub remote_backend_atomic: Option<Arc<dyn crate::storage::backend::AtomicRemoteBackend>>,
212    /// Remote object key used by the remote backend.
213    pub remote_key: Option<String>,
214    /// Replication configuration.
215    pub replication: ReplicationConfig,
216    /// Whether replica runtimes start the background replication loop.
217    pub replica_loop_enabled: bool,
218    /// Authentication & authorization configuration.
219    pub auth: AuthConfig,
220    /// Control Event Ledger configuration (issue #652). Read from
221    /// `REDDB_COMPLIANCE_MODE` at boot.
222    pub control_events: crate::runtime::control_events::ControlEventConfig,
223    /// Scoped data-plane query audit configuration. Disabled by
224    /// default; the regulated preset enables the stream without
225    /// adding catch-all rules.
226    pub query_audit: crate::runtime::query_audit::QueryAuditConfig,
227    /// Auto-create a HASH index on a user `id` column the first time a
228    /// row carrying that column is inserted into a collection. See
229    /// `UnifiedStoreConfig::auto_index_id`. Defaults to `true`; set to
230    /// `false` to opt out per workload (e.g. ingest pipelines that
231    /// don't need point-lookups by `id`).
232    pub auto_index_id: bool,
233    /// Tiered storage layout preset. Drives the defaults of the six
234    /// tier-flag toggles (`.meta.json` sidecar, seq-N catalog journal,
235    /// `-shm` provisioning, audit/slow log destinations,
236    /// `fold_dwb_into_wal`). Explicit per-feature setters still win over
237    /// the tier default. See `crate::storage::layout::StorageLayout`.
238    pub layout: crate::storage::layout::StorageLayout,
239    /// Per-feature overrides applied on top of the resolved layout preset.
240    pub layout_overrides: crate::storage::layout::LayoutOverrides,
241    /// Operator-facing storage/deploy profile contract. This records the
242    /// selected posture before the physical directory layout is expanded.
243    pub storage_profile: crate::storage::profile::StorageProfileSelection,
244    /// True only when the caller explicitly selected a layout via
245    /// `with_layout`. When false, `apply_tier_defaults` short-circuits so
246    /// pre-existing process-global toggles (set by tests / env hatches
247    /// before opening a runtime) are not clobbered by the implicit
248    /// `Standard` default. The new tier-driven behavior is opt-in.
249    pub layout_explicit: bool,
250    /// Explicit operator memory budget in bytes — the top tier of the ADR
251    /// 0073 §1 precedence chain. `None` defers to `REDDB_MEMORY_BUDGET`, the
252    /// deployment-profile default, the cgroup limit, and finally a fraction
253    /// of physical RAM. There is no "unlimited" value: `Some(0)` is rejected
254    /// at boot, exactly like an unparseable env var.
255    pub memory_budget_bytes: Option<u64>,
256    /// Opt into bounded resident segments and generation-bound disk indexes.
257    /// Currently supported only for standalone, single-file databases. Preparing
258    /// the file upgrades its writer format; retain an unconverted downgrade copy.
259    /// This is not a guarantee that every server workspace is memory-bounded.
260    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            // Perf-parity default — `WalDurableGrouped` matches
353            // PostgreSQL's `synchronous_commit=on` behaviour while
354            // amortising fsync cost across concurrent writers. The
355            // legacy `Strict` tier (per-commit fsync) stays available
356            // via `durability.mode = "strict"` / `REDDB_DURABILITY=strict`.
357            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    /// Ephemeral, tempfile-backed database.
401    ///
402    /// The underlying storage is a real persistent file placed under the system
403    /// temp directory with a unique name — there is no longer a true in-memory
404    /// execution mode. Prefer [`RedDBOptions::persistent`] when the data should
405    /// outlive the process.
406    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        // Each ephemeral runtime gets its OWN directory, not just a unique
416        // filename in the shared temp dir. Sibling artifacts (the audit log,
417        // WAL, snapshots) are derived from this data path's PARENT, so a
418        // shared parent collapses every ephemeral runtime's `.audit.log`
419        // onto one file — which parallel test processes (nextest runs each
420        // test in its own process, frequently under one shared `TMPDIR`)
421        // then truncate/remove out from under one another. A per-instance
422        // directory keeps each runtime's siblings self-contained.
423        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        // `in_memory()` eagerly creates a `reddb-ephemeral-*` dir and points
460        // `data_path` at it. Overriding the path abandons that dir — and the
461        // per-runtime cleanup keys off the FINAL `data_path`, so the orphan
462        // would leak in TMPDIR (caught by scripts/check-temp-residue.sh). Remove
463        // it now if the previous path was such an eagerly-created ephemeral dir.
464        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        // `0` is a legitimate setting — "no wait, fsync on every wakeup".
508        // See `DEFAULT_GROUP_COMMIT_WINDOW_MS` docs for the tradeoff.
509        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    /// Toggle the implicit HASH index on user `id` columns at first
544    /// insert (#112). Defaults to enabled — pass `false` to fall back
545    /// to the legacy "scan unless `CREATE INDEX` is issued" behaviour.
546    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    /// Attach a remote storage backend for snapshot transport.
557    ///
558    /// On open, the database snapshot is downloaded from the remote `key`
559    /// to the local data path. On flush, the local file is uploaded back
560    /// to the remote backend under the same key.
561    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    /// Attach a CAS-capable backend handle. Pass the same `Arc` as
572    /// `with_remote_backend` (factories should construct the backend
573    /// once and call both setters); this method exists so the type
574    /// system, not runtime config, decides whether `LeaseStore` is
575    /// reachable.
576    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    /// Select the active storage-layout preset. Drives tier defaults for
645    /// the six tier-flag toggles. Per-feature setters still win.
646    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    /// Override individual layout knobs (dedicated dirs + log routing) on
653    /// top of the active preset.
654    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    /// Declare the process memory budget explicitly (ADR 0073 §1, tier 1).
663    /// Wins over `REDDB_MEMORY_BUDGET`, the profile default, the cgroup limit
664    /// and physical-RAM detection. A zero budget is rejected when the runtime
665    /// opens, not silently swapped for a default.
666    pub fn with_memory_budget(mut self, bytes: u64) -> Self {
667        self.memory_budget_bytes = Some(bytes);
668        self
669    }
670
671    /// Select disk-backed residency explicitly, using the segment share of the
672    /// resolved memory budget. Opening an unsupported profile fails before I/O.
673    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    /// Resolve `(data_path, TieredLayoutPaths)` for this options bundle.
687    /// Returns `None` when `data_path` is unset (in-memory ephemeral
688    /// instances don't materialise a support tree).
689    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    /// Flip the process-global tier-flag toggles to match this options
702    /// bundle's layout, and stash the resolved [`TieredLayoutPaths`] for
703    /// status surfaces. Idempotent. Per-feature env escape hatches
704    /// (`REDDB_META_JSON_SIDECAR=...` and friends) still override what
705    /// this method sets — they are read inside the per-toggle getter, not
706    /// here.
707    ///
708    /// Tier defaults:
709    ///
710    /// | toggle                     | minimal | standard | performance | max |
711    /// |----------------------------|:-------:|:--------:|:-----------:|:---:|
712    /// | `.meta.json` sidecar       |   off   |    off   |     off     |  on |
713    /// | seq-N catalog journal      |   off   |    off   |     off     |  on |
714    /// | `-shm` provisioning        |   off   | **on**   |   **on**    |  on |
715    /// | `fold_dwb_into_wal`        |   off   |    off   |     off     |  on |
716    /// | audit/slow log destination | stderr  |  stderr  |  file       | file|
717    ///
718    /// Retention for the seq-N journal: 32 at `Max`, 4 when the operator
719    /// opts in on a lower tier via `REDDB_SEQN_JOURNAL=1`.
720    pub fn apply_tier_defaults(&self) {
721        use crate::storage::layout::StorageLayout;
722
723        // Opt-in: only flip the process-global toggles when the operator
724        // explicitly chose a layout via `with_layout`. Tests and env
725        // hatches that pre-set toggles before opening a runtime must not
726        // be silently overridden by the implicit `Standard` default.
727        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        // .meta.json sidecar — Max only.
736        crate::physical::set_meta_json_sidecar_enabled(matches!(layout, StorageLayout::Max));
737
738        // Seq-N catalog journal — Max only. Retention = 32 for Max,
739        // OPT_IN baseline (4) for lower tiers (the value is consulted
740        // when an env hatch flips the toggle on outside Max).
741        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        // `-shm` provisioning — anything ≥ Standard (gh-475 acceptance).
748        crate::physical::set_shm_provisioning_enabled(matches!(
749            layout,
750            StorageLayout::Standard | StorageLayout::Performance | StorageLayout::Max
751        ));
752
753        // Fold DWB into WAL — Max only (a single recovery substrate is the
754        // Max story). The pager manifest is folded into the `.rdb` on every
755        // tier since ADR 0038 §4 phase 1, so it has no toggle.
756        crate::physical::set_fold_dwb_into_wal_enabled(matches!(layout, StorageLayout::Max));
757
758        // Cache resolved layout paths for `red status` / diagnostics.
759        if let Some((_, paths)) = self.resolve_tiered_layout() {
760            tier_wiring::stash_layout_paths(paths);
761        }
762    }
763}
764
765/// Process-global cache of the most recently applied [`TieredLayoutPaths`].
766/// Read by `red status` to surface resolved log destinations. Written by
767/// `RedDBOptions::apply_tier_defaults` after each open.
768pub 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    /// `(audit_log, slow_log)` destinations resolved from the active
789    /// layout. Falls back to `(Stderr, Stderr)` when no layout has been
790    /// applied yet (e.g. ephemeral in-memory paths).
791    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    /// Operator-pinned cap exceeded (PLAN.md Phase 4.1). The string
876    /// payload should follow the `quota_exceeded:<limit_name>:<current>:<max>`
877    /// shape so HTTP / wire surfaces can map to the right status
878    /// (507 for storage, 429 for rate, 504 for duration, 413 for
879    /// payload).
880    QuotaExceeded(String),
881    /// Issue #769 (PRD #759 / S10) — an aggregating executor
882    /// (`aggregation`, `sort`, `window`) exceeded
883    /// `stream.executor.max_materialized_rows` in its in-memory state.
884    /// Carries the executor that fired, the configured ceiling and the
885    /// live row count at the breach so the client can decide whether to
886    /// redesign the query, raise the limit, or pre-aggregate. Surfaces
887    /// as HTTP 507 with a structured `materialization_limit_exceeded`
888    /// envelope; NDJSON streams emit the same code mid-stream.
889    MaterializationLimitExceeded {
890        executor: &'static str,
891        limit: usize,
892        current: usize,
893    },
894    Internal(String),
895}
896
897/// The text a wire client may see for `err`.
898///
899/// `Io` and `Internal` carry OS messages, filesystem paths and storage
900/// invariants meant for the operator's log, not for a peer; every other
901/// variant is a statement-level message the caller needs verbatim.
902pub 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}