1#![allow(deprecated)]
6
7use std::path::{Path, PathBuf};
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use crate::api::{
11 CatalogService, CatalogSnapshot, CollectionStats, RedDBError, RedDBOptions, RedDBResult,
12 StorageMode, StorageMode::Persistent,
13};
14use crate::health::{storage_file_health, HealthProvider, HealthReport};
15use crate::index::IndexCatalog;
16use crate::physical::PhysicalLayout;
17use crate::storage;
18use crate::storage::wal::CheckpointResult;
19
20#[derive(Debug, Clone, Copy)]
21pub struct EngineStats {
22 pub page_count: u32,
23 pub cache_hits: u64,
24 pub cache_misses: u64,
25 pub file_size_bytes: Option<u64>,
26 pub path_exists: bool,
27}
28
29#[derive(Debug, Clone)]
30pub struct EngineInfo {
31 pub path: Option<PathBuf>,
32 pub started_at_unix_ms: u128,
33 pub read_only: bool,
34 pub mode: StorageMode,
35 pub layout: PhysicalLayout,
36 pub options: RedDBOptions,
37}
38
39#[deprecated(
40 since = "1.23.2",
41 note = "RedDBEngine::execute_query is a SILENT NO-OP — it returns Ok(()) without executing any query. Use RedDBRuntime (in-process) or RedDBServer (serving) instead. Removed at the next major."
42)]
43pub struct RedDBEngine {
44 options: RedDBOptions,
45 layout: PhysicalLayout,
46 db: Option<storage::engine::Database>,
47 indices: IndexCatalog,
48 started_at_unix_ms: u128,
49}
50
51impl RedDBEngine {
52 pub fn open<P: AsRef<Path>>(path: P) -> RedDBResult<Self> {
53 Self::with_options(RedDBOptions::persistent(path.as_ref()))
54 }
55
56 pub fn with_options(options: RedDBOptions) -> RedDBResult<Self> {
57 if options.mode == StorageMode::InMemory {
58 return Err(RedDBError::InvalidConfig(
59 "use RedDBRuntime for a database in memory".into(),
60 ));
61 }
62 let started_at_unix_ms = SystemTime::now()
63 .duration_since(UNIX_EPOCH)
64 .unwrap_or_default()
65 .as_millis();
66 let layout = PhysicalLayout::from_options(&options);
67
68 let indices = IndexCatalog::register_default_vector_graph(
69 options.has_capability(crate::api::Capability::Table),
70 options.has_capability(crate::api::Capability::Graph),
71 );
72
73 let db = {
74 let path = options.resolved_path(reddb_file::default_database_path());
75 let config = storage::engine::DatabaseConfig {
76 read_only: options.read_only,
77 create: options.create_if_missing,
78 verify_checksums: options.verify_checksums,
79 auto_checkpoint_threshold: options.auto_checkpoint_pages,
80 ..Default::default()
81 };
82 Some(storage::engine::Database::open_with_config(path, config)?)
83 };
84
85 Ok(Self {
86 options,
87 layout,
88 db,
89 indices,
90 started_at_unix_ms,
91 })
92 }
93
94 pub fn options(&self) -> &RedDBOptions {
95 &self.options
96 }
97
98 pub fn layout(&self) -> &PhysicalLayout {
99 &self.layout
100 }
101
102 pub fn mode(&self) -> StorageMode {
103 self.options.mode
104 }
105
106 pub fn path(&self) -> Option<&Path> {
107 self.db.as_ref().map(|db| db.path())
108 }
109
110 pub fn begin_transaction(&self) -> RedDBResult<storage::wal::Transaction> {
111 let db = self
112 .db
113 .as_ref()
114 .ok_or_else(|| RedDBError::InvalidConfig("in-memory mode".to_string()))?;
115 Ok(db.begin()?)
116 }
117
118 pub fn sync(&self) -> RedDBResult<()> {
119 if let Some(db) = &self.db {
120 db.sync()?;
121 }
122 Ok(())
123 }
124
125 pub fn checkpoint(&self) -> RedDBResult<Option<CheckpointResult>> {
126 match &self.db {
127 Some(db) => db.checkpoint().map(Some).map_err(RedDBError::from),
128 None => Ok(None),
129 }
130 }
131
132 pub fn checkpoint_if_needed(&self) -> RedDBResult<Option<CheckpointResult>> {
133 match &self.db {
134 Some(db) => db.maybe_auto_checkpoint().map_err(RedDBError::from),
135 None => Ok(None),
136 }
137 }
138
139 pub fn stats(&self) -> EngineStats {
140 let mut stats = EngineStats {
141 page_count: 0,
142 cache_hits: 0,
143 cache_misses: 0,
144 file_size_bytes: None,
145 path_exists: false,
146 };
147
148 if let Some(db) = &self.db {
149 stats.page_count = db.page_count();
150 if let Ok(file_size) = db.file_size() {
151 stats.file_size_bytes = Some(file_size);
152 }
153 let cache = db.cache_stats();
154 stats.cache_hits = cache.hits;
155 stats.cache_misses = cache.misses;
156 stats.path_exists = db.path().exists();
157 }
158
159 stats
160 }
161
162 pub fn indices(&self) -> &IndexCatalog {
163 &self.indices
164 }
165
166 pub fn close(self) -> RedDBResult<()> {
167 if let Some(db) = self.db {
168 db.close().map_err(RedDBError::from)?;
169 }
170 Ok(())
171 }
172
173 pub fn info(&self) -> EngineInfo {
174 EngineInfo {
175 path: self.path().map(Path::to_path_buf),
176 started_at_unix_ms: self.started_at_unix_ms,
177 read_only: self.options.read_only,
178 mode: self.options.mode,
179 layout: self.layout.clone(),
180 options: self.options.clone(),
181 }
182 }
183
184 fn fallback_snapshot(&self) -> CatalogSnapshot {
185 CatalogSnapshot {
186 name: "reddb_engine".into(),
187 total_entities: 0,
188 total_collections: 0,
189 stats_by_collection: std::collections::BTreeMap::new(),
190 updated_at: SystemTime::UNIX_EPOCH,
191 }
192 }
193}
194
195impl CatalogService for RedDBEngine {
196 fn list_collections(&self) -> Vec<String> {
197 Vec::new()
198 }
199
200 fn collection_stats(&self, _: &str) -> Option<CollectionStats> {
201 None
202 }
203
204 fn catalog_snapshot(&self) -> CatalogSnapshot {
205 self.fallback_snapshot()
206 }
207}
208
209impl HealthProvider for RedDBEngine {
210 fn health(&self) -> HealthReport {
211 let path = self.path();
212 let mut report = match path {
213 Some(path) => storage_file_health(path),
214 None => HealthReport::healthy().with_diagnostic("mode", "in-memory"),
215 };
216 report = report.with_diagnostic("engine-started-at", self.started_at_unix_ms.to_string());
217 report = report.with_diagnostic("read-only", self.options.read_only.to_string());
218 report.with_diagnostic("persistent", self.layout.is_persistent().to_string())
219 }
220}
221
222impl crate::api::DataOps for RedDBEngine {
223 fn execute_query(&self, _query: &str) -> RedDBResult<()> {
224 Ok(())
225 }
226}
227
228impl crate::api::QueryPlanner for RedDBEngine {
229 fn plan_cost(&self, query: &str) -> Option<f64> {
230 if query.trim().is_empty() {
231 None
232 } else {
233 Some(query.len() as f64 * 0.25)
234 }
235 }
236}