Skip to main content

grafeo_engine/database/
admin.rs

1//! Admin, introspection, and diagnostic operations for GrafeoDB.
2
3use std::path::Path;
4
5use grafeo_common::utils::error::Result;
6
7impl super::GrafeoDB {
8    // =========================================================================
9    // ADMIN API: Counts
10    // =========================================================================
11
12    /// Returns the number of nodes in the database.
13    #[must_use]
14    pub fn node_count(&self) -> usize {
15        self.lpg_store().node_count()
16    }
17
18    /// Returns the number of edges in the database.
19    #[must_use]
20    pub fn edge_count(&self) -> usize {
21        self.lpg_store().edge_count()
22    }
23
24    /// Returns the number of distinct labels in the database.
25    #[must_use]
26    pub fn label_count(&self) -> usize {
27        self.lpg_store().label_count()
28    }
29
30    /// Returns the number of distinct property keys in the database.
31    #[must_use]
32    pub fn property_key_count(&self) -> usize {
33        self.lpg_store().property_key_count()
34    }
35
36    /// Returns the number of distinct edge types in the database.
37    #[must_use]
38    pub fn edge_type_count(&self) -> usize {
39        self.lpg_store().edge_type_count()
40    }
41
42    // =========================================================================
43    // ADMIN API: Introspection
44    // =========================================================================
45
46    /// Returns true if this database is backed by a file (persistent).
47    ///
48    /// In-memory databases return false.
49    #[must_use]
50    pub fn is_persistent(&self) -> bool {
51        self.config.path.is_some()
52    }
53
54    /// Returns the database file path, if persistent.
55    ///
56    /// In-memory databases return None.
57    #[must_use]
58    pub fn path(&self) -> Option<&Path> {
59        self.config.path.as_deref()
60    }
61
62    /// Returns high-level database information.
63    ///
64    /// Includes node/edge counts, persistence status, and mode (LPG/RDF).
65    #[must_use]
66    pub fn info(&self) -> crate::admin::DatabaseInfo {
67        crate::admin::DatabaseInfo {
68            mode: crate::admin::DatabaseMode::Lpg,
69            node_count: self.lpg_store().node_count(),
70            edge_count: self.lpg_store().edge_count(),
71            is_persistent: self.is_persistent(),
72            path: self.config.path.clone(),
73            wal_enabled: self.config.wal_enabled,
74            version: env!("CARGO_PKG_VERSION").to_string(),
75            features: {
76                let mut f = vec!["gql".into()];
77                if cfg!(feature = "cypher") {
78                    f.push("cypher".into());
79                }
80                if cfg!(feature = "sparql") {
81                    f.push("sparql".into());
82                }
83                if cfg!(feature = "gremlin") {
84                    f.push("gremlin".into());
85                }
86                if cfg!(feature = "graphql") {
87                    f.push("graphql".into());
88                }
89                if cfg!(feature = "sql-pgq") {
90                    f.push("sql-pgq".into());
91                }
92                if cfg!(feature = "triple-store") {
93                    f.push("rdf".into());
94                }
95                if cfg!(feature = "algos") {
96                    f.push("algos".into());
97                }
98                if cfg!(feature = "vector-index") {
99                    f.push("vector-index".into());
100                }
101                if cfg!(feature = "text-index") {
102                    f.push("text-index".into());
103                }
104                if cfg!(feature = "hybrid-search") {
105                    f.push("hybrid-search".into());
106                }
107                if cfg!(feature = "cdc") {
108                    f.push("cdc".into());
109                }
110                f
111            },
112        }
113    }
114
115    /// Returns a hierarchical memory usage breakdown.
116    ///
117    /// Walks all internal structures (store, indexes, MVCC chains, caches,
118    /// string pools, buffer manager) and returns estimated heap bytes for each.
119    /// Safe to call concurrently with queries.
120    #[must_use]
121    pub fn memory_usage(&self) -> crate::memory_usage::MemoryUsage {
122        use crate::memory_usage::{BufferManagerMemory, CacheMemory, MemoryUsage};
123        use grafeo_common::memory::MemoryRegion;
124
125        let (store, indexes, mvcc, string_pool) = self.lpg_store().memory_breakdown();
126
127        let (parsed_bytes, optimized_bytes, cached_plan_count) =
128            self.query_cache.heap_memory_bytes();
129        let mut caches = CacheMemory {
130            parsed_plan_cache_bytes: parsed_bytes,
131            optimized_plan_cache_bytes: optimized_bytes,
132            cached_plan_count,
133            ..Default::default()
134        };
135        caches.compute_total();
136
137        let bm_stats = self.buffer_manager.stats();
138        let buffer_manager = BufferManagerMemory {
139            budget_bytes: bm_stats.budget,
140            allocated_bytes: bm_stats.total_allocated,
141            graph_storage_bytes: bm_stats.region_usage(MemoryRegion::GraphStorage),
142            index_buffers_bytes: bm_stats.region_usage(MemoryRegion::IndexBuffers),
143            execution_buffers_bytes: bm_stats.region_usage(MemoryRegion::ExecutionBuffers),
144            spill_staging_bytes: bm_stats.region_usage(MemoryRegion::SpillStaging),
145        };
146
147        let mut usage = MemoryUsage {
148            store,
149            indexes,
150            mvcc,
151            caches,
152            string_pool,
153            buffer_manager,
154            ..Default::default()
155        };
156        usage.compute_total();
157        usage
158    }
159
160    /// Returns detailed database statistics.
161    ///
162    /// Includes counts, memory usage, and index information.
163    #[must_use]
164    pub fn detailed_stats(&self) -> crate::admin::DatabaseStats {
165        #[cfg(feature = "wal")]
166        let disk_bytes = self.config.path.as_ref().and_then(|p| {
167            if p.exists() {
168                Self::calculate_disk_usage(p).ok()
169            } else {
170                None
171            }
172        });
173        #[cfg(not(feature = "wal"))]
174        let disk_bytes: Option<usize> = None;
175
176        crate::admin::DatabaseStats {
177            node_count: self.lpg_store().node_count(),
178            edge_count: self.lpg_store().edge_count(),
179            label_count: self.lpg_store().label_count(),
180            edge_type_count: self.lpg_store().edge_type_count(),
181            property_key_count: self.lpg_store().property_key_count(),
182            index_count: self.catalog.index_count(),
183            memory_bytes: self.buffer_manager.allocated(),
184            disk_bytes,
185        }
186    }
187
188    /// Calculates total disk usage for the database directory.
189    #[cfg(feature = "wal")]
190    fn calculate_disk_usage(path: &Path) -> Result<usize> {
191        let mut total = 0usize;
192        if path.is_dir() {
193            for entry in std::fs::read_dir(path)? {
194                let entry = entry?;
195                let metadata = entry.metadata()?;
196                if metadata.is_file() {
197                    total += metadata.len() as usize;
198                } else if metadata.is_dir() {
199                    total += Self::calculate_disk_usage(&entry.path())?;
200                }
201            }
202        }
203        Ok(total)
204    }
205
206    /// Returns schema information (labels, edge types, property keys).
207    ///
208    /// For LPG mode, returns label and edge type information.
209    /// For RDF mode, returns predicate and named graph information.
210    #[must_use]
211    pub fn schema(&self) -> crate::admin::SchemaInfo {
212        let labels = self
213            .lpg_store()
214            .all_labels()
215            .into_iter()
216            .map(|name| crate::admin::LabelInfo {
217                name: name.clone(),
218                count: self.lpg_store().nodes_with_label(&name).count(),
219            })
220            .collect();
221
222        let edge_types = self
223            .lpg_store()
224            .all_edge_types()
225            .into_iter()
226            .map(|name| crate::admin::EdgeTypeInfo {
227                name: name.clone(),
228                count: self.lpg_store().edges_with_type(&name).count(),
229            })
230            .collect();
231
232        let property_keys = self.lpg_store().all_property_keys();
233
234        crate::admin::SchemaInfo::Lpg(crate::admin::LpgSchemaInfo {
235            labels,
236            edge_types,
237            property_keys,
238        })
239    }
240
241    /// Returns detailed information about all indexes.
242    #[must_use]
243    pub fn list_indexes(&self) -> Vec<crate::admin::IndexInfo> {
244        self.catalog
245            .all_indexes()
246            .into_iter()
247            .map(|def| {
248                let label_name = self
249                    .catalog
250                    .get_label_name(def.label)
251                    .unwrap_or_else(|| "?".into());
252                let prop_name = self
253                    .catalog
254                    .get_property_key_name(def.property_key)
255                    .unwrap_or_else(|| "?".into());
256                crate::admin::IndexInfo {
257                    name: format!("idx_{}_{}", label_name, prop_name),
258                    index_type: format!("{:?}", def.index_type),
259                    target: format!("{}:{}", label_name, prop_name),
260                    unique: false,
261                    cardinality: None,
262                    size_bytes: None,
263                }
264            })
265            .collect()
266    }
267
268    /// Validates database integrity.
269    ///
270    /// Checks for:
271    /// - Dangling edge references (edges pointing to non-existent nodes)
272    /// - Internal index consistency
273    ///
274    /// Returns a list of errors and warnings. Empty errors = valid.
275    #[must_use]
276    pub fn validate(&self) -> crate::admin::ValidationResult {
277        let mut result = crate::admin::ValidationResult::default();
278
279        // Check for dangling edge references
280        for edge in self.lpg_store().all_edges() {
281            if self.lpg_store().get_node(edge.src).is_none() {
282                result.errors.push(crate::admin::ValidationError {
283                    code: "DANGLING_SRC".to_string(),
284                    message: format!(
285                        "Edge {} references non-existent source node {}",
286                        edge.id.0, edge.src.0
287                    ),
288                    context: Some(format!("edge:{}", edge.id.0)),
289                });
290            }
291            if self.lpg_store().get_node(edge.dst).is_none() {
292                result.errors.push(crate::admin::ValidationError {
293                    code: "DANGLING_DST".to_string(),
294                    message: format!(
295                        "Edge {} references non-existent destination node {}",
296                        edge.id.0, edge.dst.0
297                    ),
298                    context: Some(format!("edge:{}", edge.id.0)),
299                });
300            }
301        }
302
303        // Add warnings for potential issues
304        if self.lpg_store().node_count() > 0 && self.lpg_store().edge_count() == 0 {
305            result.warnings.push(crate::admin::ValidationWarning {
306                code: "NO_EDGES".to_string(),
307                message: "Database has nodes but no edges".to_string(),
308                context: None,
309            });
310        }
311
312        result
313    }
314
315    /// Returns WAL (Write-Ahead Log) status.
316    ///
317    /// Returns None if WAL is not enabled.
318    #[must_use]
319    pub fn wal_status(&self) -> crate::admin::WalStatus {
320        #[cfg(feature = "wal")]
321        if let Some(ref wal) = self.wal {
322            return crate::admin::WalStatus {
323                enabled: true,
324                path: self.config.path.as_ref().map(|p| p.join("wal")),
325                size_bytes: wal.size_bytes(),
326                record_count: wal.record_count() as usize,
327                last_checkpoint: wal.last_checkpoint_timestamp(),
328                current_epoch: self.lpg_store().current_epoch().as_u64(),
329            };
330        }
331
332        crate::admin::WalStatus {
333            enabled: false,
334            path: None,
335            size_bytes: 0,
336            record_count: 0,
337            last_checkpoint: None,
338            current_epoch: self.lpg_store().current_epoch().as_u64(),
339        }
340    }
341
342    /// Forces a WAL checkpoint.
343    ///
344    /// Flushes all pending WAL records to the main storage.
345    ///
346    /// # Errors
347    ///
348    /// Returns an error if the checkpoint fails.
349    pub fn wal_checkpoint(&self) -> Result<()> {
350        // Read-only databases have no WAL and the on-disk file is already a
351        // valid snapshot: nothing to checkpoint.
352        if self.read_only {
353            return Ok(());
354        }
355
356        #[cfg(feature = "wal")]
357        if let Some(ref wal) = self.wal {
358            let epoch = self.lpg_store().current_epoch();
359            let transaction_id = self
360                .transaction_manager
361                .last_assigned_transaction_id()
362                .unwrap_or_else(|| self.transaction_manager.begin());
363            wal.checkpoint(transaction_id, epoch)?;
364            wal.sync()?;
365        }
366
367        // Flush all sections to .grafeo file (explicit checkpoint)
368        #[cfg(feature = "grafeo-file")]
369        if let Some(ref fm) = self.file_manager {
370            let _ = self.checkpoint_to_file(fm, super::flush::FlushReason::Explicit)?;
371        }
372
373        Ok(())
374    }
375
376    // =========================================================================
377    // ADMIN API: Change Data Capture
378    // =========================================================================
379
380    /// Returns whether CDC is enabled by default for new sessions.
381    #[cfg(feature = "cdc")]
382    #[must_use]
383    pub fn is_cdc_enabled(&self) -> bool {
384        self.cdc_active()
385    }
386
387    /// Sets whether CDC is enabled by default for new sessions.
388    ///
389    /// Does not affect sessions that were already created.
390    #[cfg(feature = "cdc")]
391    pub fn set_cdc_enabled(&self, enabled: bool) {
392        self.cdc_enabled
393            .store(enabled, std::sync::atomic::Ordering::Relaxed);
394    }
395
396    /// Returns the full change history for an entity (node or edge).
397    ///
398    /// Events are ordered chronologically by epoch.
399    ///
400    /// # Errors
401    ///
402    /// Returns an error if the CDC feature is not enabled.
403    #[cfg(feature = "cdc")]
404    pub fn history(
405        &self,
406        entity_id: impl Into<crate::cdc::EntityId>,
407    ) -> Result<Vec<crate::cdc::ChangeEvent>> {
408        Ok(self.cdc_log.history(entity_id.into()))
409    }
410
411    /// Returns change events for an entity since the given epoch.
412    ///
413    /// # Errors
414    ///
415    /// Currently infallible, but returns `Result` for forward compatibility.
416    #[cfg(feature = "cdc")]
417    pub fn history_since(
418        &self,
419        entity_id: impl Into<crate::cdc::EntityId>,
420        since_epoch: grafeo_common::types::EpochId,
421    ) -> Result<Vec<crate::cdc::ChangeEvent>> {
422        Ok(self.cdc_log.history_since(entity_id.into(), since_epoch))
423    }
424
425    /// Returns all change events across all entities in an epoch range.
426    ///
427    /// # Errors
428    ///
429    /// Currently infallible, but returns `Result` for forward compatibility.
430    #[cfg(feature = "cdc")]
431    pub fn changes_between(
432        &self,
433        start_epoch: grafeo_common::types::EpochId,
434        end_epoch: grafeo_common::types::EpochId,
435    ) -> Result<Vec<crate::cdc::ChangeEvent>> {
436        Ok(self.cdc_log.changes_between(start_epoch, end_epoch))
437    }
438}