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    /// Process-local database backed by the engine's resident store.
49    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    /// Fire-and-forget. Writers return as soon as the WAL record is
64    /// in the in-memory ring buffer — they do NOT wait for fsync.
65    /// The group-commit background thread still flushes on its
66    /// cadence, so committed-but-unflushed work is bounded by
67    /// `GroupCommitOptions::window_ms`. A crash inside the window
68    /// drops whatever wasn't flushed — matches PG's
69    /// `synchronous_commit=off` contract.
70    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            // Legacy / opt-out form. Every commit pays its own fsync.
86            "strict" => Some(Self::Strict),
87            // Group-commit sync path — the perf-parity default. Matches
88            // PostgreSQL's `synchronous_commit=on` behaviour: the
89            // writer waits for durability, but fsyncs are batched
90            // across concurrent writers so a burst of N commits pays
91            // ~O(1) fsyncs instead of O(N).
92            "sync"
93            | "wal_durable_grouped"
94            | "wal-durable-grouped"
95            | "grouped"
96            | "wal_grouped"
97            | "wal-grouped" => Some(Self::WalDurableGrouped),
98            // Fire-and-forget async: writers return as soon as the
99            // WAL buffer accepts the record; background flusher runs
100            // on its configured cadence.
101            "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    /// Structured row storage.
127    Table,
128    /// Graph nodes/edges.
129    Graph,
130    /// Vector collections and ANN search.
131    Vector,
132    /// Full-text / lexical search.
133    FullText,
134    /// Text/metadata security and enrichment modules.
135    Security,
136    /// Encryption at rest.
137    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    /// Maximum hypertable chunks the checkpoint path may seal into derived
194    /// columnar artifacts per checkpoint. `usize::MAX` means no practical cap.
195    pub checkpoint_columnar_emission_budget_chunks: usize,
196    /// Minimum rows a sealed in-scope chunk must carry before the derived
197    /// columnar projection is materialized.
198    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    /// Optional remote storage backend for snapshot transport.
206    pub remote_backend: Option<Arc<dyn crate::storage::backend::RemoteBackend>>,
207    /// Optional CAS-capable handle to the same backend, populated by
208    /// the factory when the configured backend implements
209    /// `AtomicRemoteBackend` (S3/local always; HTTP only when
210    /// `RED_HTTP_CONDITIONAL_WRITES=true`). `None` for backends that
211    /// do not provide compare-and-swap (Turso, D1, plain HTTP).
212    /// `LeaseStore` and any future CAS consumer pull from this field.
213    pub remote_backend_atomic: Option<Arc<dyn crate::storage::backend::AtomicRemoteBackend>>,
214    /// Remote object key used by the remote backend.
215    pub remote_key: Option<String>,
216    /// Exact immutable snapshot selected by the serverless publication head
217    /// for this boot. Internal orchestration sets it before opening the
218    /// runtime; ordinary callers should leave it as `None`.
219    #[doc(hidden)]
220    pub remote_bootstrap_key: Option<String>,
221    /// Replication configuration.
222    pub replication: ReplicationConfig,
223    /// Whether replica runtimes start the background replication loop.
224    pub replica_loop_enabled: bool,
225    /// Authentication & authorization configuration.
226    pub auth: AuthConfig,
227    /// Control Event Ledger configuration (issue #652). Read from
228    /// `REDDB_COMPLIANCE_MODE` at boot.
229    pub control_events: crate::runtime::control_events::ControlEventConfig,
230    /// Scoped data-plane query audit configuration. Disabled by
231    /// default; the regulated preset enables the stream without
232    /// adding catch-all rules.
233    pub query_audit: crate::runtime::query_audit::QueryAuditConfig,
234    /// Auto-create a HASH index on a user `id` column the first time a
235    /// row carrying that column is inserted into a collection. See
236    /// `UnifiedStoreConfig::auto_index_id`. Defaults to `true`; set to
237    /// `false` to opt out per workload (e.g. ingest pipelines that
238    /// don't need point-lookups by `id`).
239    pub auto_index_id: bool,
240    /// Tiered storage layout preset. Drives the defaults of the six
241    /// tier-flag toggles (`.meta.json` sidecar, seq-N catalog journal,
242    /// `-shm` provisioning, audit/slow log destinations,
243    /// `fold_dwb_into_wal`). Explicit per-feature setters still win over
244    /// the tier default. See `crate::storage::layout::StorageLayout`.
245    pub layout: crate::storage::layout::StorageLayout,
246    /// Per-feature overrides applied on top of the resolved layout preset.
247    pub layout_overrides: crate::storage::layout::LayoutOverrides,
248    /// Operator-facing storage/deploy profile contract. This records the
249    /// selected posture before the physical directory layout is expanded.
250    pub storage_profile: crate::storage::profile::StorageProfileSelection,
251    /// True only when the caller explicitly selected a layout via
252    /// `with_layout`. When false, `apply_tier_defaults` short-circuits so
253    /// pre-existing process-global toggles (set by tests / env hatches
254    /// before opening a runtime) are not clobbered by the implicit
255    /// `Standard` default. The new tier-driven behavior is opt-in.
256    pub layout_explicit: bool,
257    /// Explicit operator memory budget in bytes — the top tier of the ADR
258    /// 0073 §1 precedence chain. `None` defers to `REDDB_MEMORY_BUDGET`, the
259    /// deployment-profile default, the cgroup limit, and finally a fraction
260    /// of physical RAM. There is no "unlimited" value: `Some(0)` is rejected
261    /// at boot, exactly like an unparseable env var.
262    pub memory_budget_bytes: Option<u64>,
263    /// Opt into bounded resident segments and generation-bound disk indexes.
264    /// Currently supported only for standalone, single-file databases. Preparing
265    /// the file upgrades its writer format; retain an unconverted downgrade copy.
266    /// This is not a guarantee that every server workspace is memory-bounded.
267    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            // Perf-parity default — `WalDurableGrouped` matches
362            // PostgreSQL's `synchronous_commit=on` behaviour while
363            // amortising fsync cost across concurrent writers. The
364            // legacy `Strict` tier (per-commit fsync) stays available
365            // via `durability.mode = "strict"` / `REDDB_DURABILITY=strict`.
366            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    /// Open options for a database whose contents only live in process memory.
411    pub fn memory_only() -> Self {
412        Self {
413            mode: StorageMode::InMemory,
414            auto_checkpoint_pages: 0,
415            ..Default::default()
416        }
417    }
418
419    /// Legacy constructor for an ephemeral, tempfile-backed database.
420    pub fn in_memory() -> Self {
421        Self::temporary()
422    }
423
424    /// Ephemeral, tempfile-backed database.
425    ///
426    /// The underlying storage is a real persistent file placed under the system
427    /// temp directory with a unique name. Prefer [`RedDBOptions::persistent`] when the data should
428    /// outlive the process.
429    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        // Each ephemeral runtime gets its OWN directory, not just a unique
439        // filename in the shared temp dir. Sibling artifacts (the audit log,
440        // WAL, snapshots) are derived from this data path's PARENT, so a
441        // shared parent collapses every ephemeral runtime's `.audit.log`
442        // onto one file — which parallel test processes (nextest runs each
443        // test in its own process, frequently under one shared `TMPDIR`)
444        // then truncate/remove out from under one another. A per-instance
445        // directory keeps each runtime's siblings self-contained.
446        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        // `temporary()` eagerly creates a `reddb-ephemeral-*` dir and points
483        // `data_path` at it. Overriding the path abandons that dir — and the
484        // per-runtime cleanup keys off the FINAL `data_path`, so the orphan
485        // would leak in TMPDIR (caught by scripts/check-temp-residue.sh). Remove
486        // it now if the previous path was such an eagerly-created ephemeral dir.
487        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        // `0` is a legitimate setting — "no wait, fsync on every wakeup".
531        // See `DEFAULT_GROUP_COMMIT_WINDOW_MS` docs for the tradeoff.
532        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    /// Toggle the implicit HASH index on user `id` columns at first
567    /// insert (#112). Defaults to enabled — pass `false` to fall back
568    /// to the legacy "scan unless `CREATE INDEX` is issued" behaviour.
569    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    /// Attach a remote storage backend for snapshot transport.
580    ///
581    /// On open, the database snapshot is downloaded from the remote `key`
582    /// to the local data path. On flush, the local file is uploaded back
583    /// to the remote backend under the same key.
584    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    /// Attach a CAS-capable backend handle. Pass the same `Arc` as
595    /// `with_remote_backend` (factories should construct the backend
596    /// once and call both setters); this method exists so the type
597    /// system, not runtime config, decides whether `LeaseStore` is
598    /// reachable.
599    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    /// Select the active storage-layout preset. Drives tier defaults for
668    /// the six tier-flag toggles. Per-feature setters still win.
669    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    /// Override individual layout knobs (dedicated dirs + log routing) on
676    /// top of the active preset.
677    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    /// Declare the process memory budget explicitly (ADR 0073 §1, tier 1).
686    /// Wins over `REDDB_MEMORY_BUDGET`, the profile default, the cgroup limit
687    /// and physical-RAM detection. A zero budget is rejected when the runtime
688    /// opens, not silently swapped for a default.
689    pub fn with_memory_budget(mut self, bytes: u64) -> Self {
690        self.memory_budget_bytes = Some(bytes);
691        self
692    }
693
694    /// Select disk-backed residency explicitly, using the segment share of the
695    /// resolved memory budget. Opening an unsupported profile fails before I/O.
696    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    /// Resolve `(data_path, TieredLayoutPaths)` for this options bundle.
710    /// Returns `None` when `data_path` is unset (in-memory ephemeral
711    /// instances don't materialise a support tree).
712    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    /// Flip the process-global tier-flag toggles to match this options
725    /// bundle's layout, and stash the resolved [`TieredLayoutPaths`] for
726    /// status surfaces. Idempotent. Per-feature env escape hatches
727    /// (`REDDB_META_JSON_SIDECAR=...` and friends) still override what
728    /// this method sets — they are read inside the per-toggle getter, not
729    /// here.
730    ///
731    /// Tier defaults:
732    ///
733    /// | toggle                     | minimal | standard | performance | max |
734    /// |----------------------------|:-------:|:--------:|:-----------:|:---:|
735    /// | `.meta.json` sidecar       |   off   |    off   |     off     |  on |
736    /// | seq-N catalog journal      |   off   |    off   |     off     |  on |
737    /// | `-shm` provisioning        |   off   | **on**   |   **on**    |  on |
738    /// | `fold_dwb_into_wal`        |   off   |    off   |     off     |  on |
739    /// | audit/slow log destination | stderr  |  stderr  |  file       | file|
740    ///
741    /// Retention for the seq-N journal: 32 at `Max`, 4 when the operator
742    /// opts in on a lower tier via `REDDB_SEQN_JOURNAL=1`.
743    pub fn apply_tier_defaults(&self) {
744        use crate::storage::layout::StorageLayout;
745
746        // Opt-in: only flip the process-global toggles when the operator
747        // explicitly chose a layout via `with_layout`. Tests and env
748        // hatches that pre-set toggles before opening a runtime must not
749        // be silently overridden by the implicit `Standard` default.
750        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        // .meta.json sidecar — Max only.
759        crate::physical::set_meta_json_sidecar_enabled(matches!(layout, StorageLayout::Max));
760
761        // Seq-N catalog journal — Max only. Retention = 32 for Max,
762        // OPT_IN baseline (4) for lower tiers (the value is consulted
763        // when an env hatch flips the toggle on outside Max).
764        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        // `-shm` provisioning — anything ≥ Standard (gh-475 acceptance).
771        crate::physical::set_shm_provisioning_enabled(matches!(
772            layout,
773            StorageLayout::Standard | StorageLayout::Performance | StorageLayout::Max
774        ));
775
776        // Fold DWB into WAL — Max only (a single recovery substrate is the
777        // Max story). The pager manifest is folded into the `.rdb` on every
778        // tier since ADR 0038 §4 phase 1, so it has no toggle.
779        crate::physical::set_fold_dwb_into_wal_enabled(matches!(layout, StorageLayout::Max));
780
781        // Cache resolved layout paths for `red status` / diagnostics.
782        if let Some((_, paths)) = self.resolve_tiered_layout() {
783            tier_wiring::stash_layout_paths(paths);
784        }
785    }
786}
787
788/// Process-global cache of the most recently applied [`TieredLayoutPaths`].
789/// Read by `red status` to surface resolved log destinations. Written by
790/// `RedDBOptions::apply_tier_defaults` after each open.
791pub 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    /// `(audit_log, slow_log)` destinations resolved from the active
812    /// layout. Falls back to `(Stderr, Stderr)` when no layout has been
813    /// applied yet (e.g. ephemeral in-memory paths).
814    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    /// The local commit is durable, but the requested replica durability was
888    /// not confirmed. Retrying the mutation may execute it a second time.
889    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    /// Operator-pinned cap exceeded (PLAN.md Phase 4.1). The string
905    /// payload should follow the `quota_exceeded:<limit_name>:<current>:<max>`
906    /// shape so HTTP / wire surfaces can map to the right status
907    /// (507 for storage, 429 for rate, 504 for duration, 413 for
908    /// payload).
909    QuotaExceeded(String),
910    /// Issue #769 (PRD #759 / S10) — an aggregating executor
911    /// (`aggregation`, `sort`, `window`) exceeded
912    /// `stream.executor.max_materialized_rows` in its in-memory state.
913    /// Carries the executor that fired, the configured ceiling and the
914    /// live row count at the breach so the client can decide whether to
915    /// redesign the query, raise the limit, or pre-aggregate. Surfaces
916    /// as HTTP 507 with a structured `materialization_limit_exceeded`
917    /// envelope; NDJSON streams emit the same code mid-stream.
918    MaterializationLimitExceeded {
919        executor: &'static str,
920        limit: usize,
921        current: usize,
922    },
923    Internal(String),
924}
925
926/// The text a wire client may see for `err`.
927///
928/// `Io` and `Internal` carry OS messages, filesystem paths and storage
929/// invariants meant for the operator's log, not for a peer; every other
930/// variant is a statement-level message the caller needs verbatim.
931pub 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}