Skip to main content

ethrex_storage/api/
mod.rs

1//! # Storage Backend API
2//!
3//! This module provides a thin, minimal interface for storage backends:
4//!
5//! - Thin: Minimal set of operations that databases must provide
6//! - Simple: Avoids type-system complexity and focuses on core functionality
7//!
8//! Rather than implementing business logic in each database backend, this API
9//! provides low-level primitives that higher-level code can build upon.
10//! This eliminates code duplication and makes adding new database backends trivial.
11//!
12//! The API differentiates between three types of database access:
13//!
14//! - Read views ([`StorageReadView`]): read-only views of the database,
15//!   with no atomicity guarantees between operations.
16//! - Write batches ([`StorageWriteBatch`]): write batch functionality, with
17//!   atomicity guarantees at commit time.
18//! - Locked views ([`StorageLockedView`]): read-only views of a point in time (snapshots), right now it's
19//!   only used during snap-sync.
20
21use crate::error::StoreError;
22use std::{fmt::Debug, path::Path, sync::Arc};
23
24pub mod tables;
25
26/// Type alias for the result of a prefix iterator.
27pub type PrefixResult = Result<(Box<[u8]>, Box<[u8]>), StoreError>;
28
29/// Per-column-family on-disk statistics, for DB observability.
30#[derive(Debug, Clone, Default)]
31pub struct CfStats {
32    pub name: String,
33    /// Live SST bytes on disk for this CF.
34    pub live_sst_bytes: u64,
35    /// Total SST bytes incl. not-yet-compacted/obsolete (for space amplification).
36    pub total_sst_bytes: u64,
37    /// Estimated live (logical) data size.
38    pub live_data_bytes: u64,
39    /// Estimated number of keys.
40    pub num_keys: u64,
41    /// Live SST file count.
42    pub num_files: u64,
43    /// Live blob file bytes (only ACCOUNT_CODES uses blobs).
44    pub blob_bytes: u64,
45    /// Estimated pending compaction bytes (write-debt indicator).
46    pub pending_compaction_bytes: u64,
47    /// Current memtable bytes for this CF.
48    pub memtable_bytes: u64,
49}
50
51/// Snapshot of RocksDB observability stats: per-CF sizes plus DB-wide block-cache
52/// counters. Read from RocksDB properties (+ statistics, when enabled).
53#[derive(Debug, Clone, Default)]
54pub struct RocksDbStats {
55    pub cfs: Vec<CfStats>,
56    pub block_cache_usage_bytes: u64,
57    pub block_cache_capacity_bytes: u64,
58    pub block_cache_pinned_bytes: u64,
59    pub running_compactions: u64,
60    /// Cumulative block-cache hits (0 unless RocksDB statistics are enabled).
61    pub block_cache_hits: u64,
62    /// Cumulative block-cache misses (0 unless RocksDB statistics are enabled).
63    pub block_cache_misses: u64,
64}
65
66/// This trait provides a minimal set of operations required from a database backend.
67/// Implementations should focus on providing efficient access to the underlying storage
68/// without implementing business logic.
69pub trait StorageBackend: Debug + Send + Sync {
70    /// Removes all data from the specified table.
71    fn clear_table(&self, table: &'static str) -> Result<(), StoreError>;
72
73    /// Opens a new read view.
74    fn begin_read(&self) -> Result<Arc<dyn StorageReadView>, StoreError>;
75
76    /// Opens a read view pinned to the database as it is now: writes committed
77    /// after it opens are not visible through it. For reads that must not see a
78    /// commit land partway through, such as checking that a state root is held
79    /// and then reading that state. Backends whose `begin_read` already reads a
80    /// snapshot keep this default.
81    fn begin_snapshot_read(&self) -> Result<Arc<dyn StorageReadView>, StoreError> {
82        self.begin_read()
83    }
84
85    /// Creates a new write batch.
86    fn begin_write(&self) -> Result<Box<dyn StorageWriteBatch + 'static>, StoreError>;
87
88    /// Creates a locked snapshot for a specific table.
89    ///
90    /// This provides a persistent read-only view of a single table, optimized
91    /// for batch read operations. The snapshot remains valid until dropped.
92    fn begin_locked(
93        &self,
94        table_name: &'static str,
95    ) -> Result<Box<dyn StorageLockedView + 'static>, StoreError>;
96
97    // TODO: remove this and provide historic data via diff-layers
98    /// Creates a checkpoint of the current database state at the specified path.
99    fn create_checkpoint(&self, path: &Path) -> Result<(), StoreError>;
100
101    /// Durably persists all buffered writes to disk, so a subsequent process
102    /// start needs no crash recovery. Called on graceful shutdown. Defaults to a
103    /// no-op for backends that are already durable or purely in-memory.
104    fn flush(&self) -> Result<(), StoreError> {
105        Ok(())
106    }
107
108    /// Returns per-column-family and DB-wide RocksDB observability stats, or
109    /// `None` for backends that don't expose them (e.g. in-memory).
110    fn db_stats(&self) -> Option<RocksDbStats> {
111        None
112    }
113}
114
115/// Read-only transaction interface.
116/// Provides methods to read data from the database
117pub trait StorageReadView: Send + Sync {
118    /// Retrieves a value by key from the specified table.
119    fn get(&self, table: &'static str, key: &[u8]) -> Result<Option<Vec<u8>>, StoreError>;
120
121    /// Retrieves multiple values by key from the specified table.
122    /// Returns results in the same order as the input keys.
123    /// Backends that support batched reads (e.g. RocksDB `multi_get_cf`)
124    /// should override this for better throughput. Callers should not
125    /// assume `multi_get` is asymptotically faster than `get`; on backends
126    /// without a batched read primitive (e.g. the in-memory backend) the
127    /// default impl below is equivalent to N independent `get` calls.
128    fn multi_get(
129        &self,
130        table: &'static str,
131        keys: &[&[u8]],
132    ) -> Vec<Result<Option<Vec<u8>>, StoreError>> {
133        keys.iter().map(|k| self.get(table, k)).collect()
134    }
135
136    /// Returns the key-value pairs of `table` from the first key not less than `prefix`
137    /// onward, in key order. The iterator does not stop where keys stop starting with
138    /// `prefix`: the RocksDB backend configures no prefix extractor, so this is a plain
139    /// seek. Callers stop once keys leave the range they want, and may seek into the
140    /// middle of a prefix.
141    fn prefix_iterator(
142        &self,
143        table: &'static str,
144        prefix: &[u8],
145    ) -> Result<Box<dyn Iterator<Item = PrefixResult> + '_>, StoreError>;
146
147    /// Returns the lowest key in `table` by lexicographic order, or `None` if the table is
148    /// empty. Backends that support forward iteration (e.g. RocksDB `IteratorMode::Start`)
149    /// should implement this in O(1).
150    fn first_key(&self, table: &'static str) -> Result<Option<Vec<u8>>, StoreError>;
151
152    /// Returns the highest key in `table` by lexicographic order, or `None` if the table is
153    /// empty. Backends that support reverse iteration (e.g. RocksDB `IteratorMode::End`) should
154    /// implement this in O(1).
155    fn last_key(&self, table: &'static str) -> Result<Option<Vec<u8>>, StoreError>;
156}
157
158/// Write transaction interface.
159///
160/// Note that this does not provide read access, since we don't currently use that functionality.
161///
162/// Changes are not persisted until [`commit()`](StorageWriteBatch::commit) is called.
163pub trait StorageWriteBatch: Send {
164    /// Stores a key-value pair in the specified table.
165    fn put(&mut self, table: &'static str, key: &[u8], value: &[u8]) -> Result<(), StoreError> {
166        self.put_batch(table, vec![(key.to_vec(), value.to_vec())])
167    }
168
169    /// Stores multiple key-value pairs in the specified table within the transaction.
170    fn put_batch(
171        &mut self,
172        table: &'static str,
173        batch: Vec<(Vec<u8>, Vec<u8>)>,
174    ) -> Result<(), StoreError>;
175
176    /// Removes a key-value pair from the specified table.
177    fn delete(&mut self, table: &'static str, key: &[u8]) -> Result<(), StoreError>;
178
179    /// Removes every key in `[start, end)` from the specified table.
180    ///
181    /// Half-open range; `end` is exclusive. Equivalent to enumerating each key
182    /// in the range and calling [`delete`], but backends with native range-delete
183    /// support (e.g. RocksDB's `delete_range_cf`) can implement it more efficiently.
184    ///
185    /// Lexicographic byte order is used for the range bounds — callers using
186    /// numeric keys must encode them in a representation whose lex order matches
187    /// numeric order (e.g. `u64::to_be_bytes()`).
188    fn delete_range(
189        &mut self,
190        table: &'static str,
191        start: &[u8],
192        end: &[u8],
193    ) -> Result<(), StoreError>;
194
195    /// Appends a merge operand for the given key in the specified table.
196    ///
197    /// The actual combine step is deferred — backends with a registered merge
198    /// operator (RocksDB) apply it at read or compaction time; backends without
199    /// (InMemory) dispatch by table and apply inline.
200    ///
201    /// Currently used for `TRANSACTION_LOCATIONS`. Calling on a table without
202    /// a registered merge function is an error.
203    fn merge(&mut self, table: &'static str, key: &[u8], operand: &[u8]) -> Result<(), StoreError>;
204
205    /// Commits all changes made in this transaction.
206    fn commit(&mut self) -> Result<(), StoreError>;
207}
208
209/// Locked snapshot interface for batch read operations.
210/// Provides read-only access to a specific table with a persistent snapshot.
211/// This is optimized for scenarios where many reads are performed on the same
212/// table, such as trie traversal operations.
213/// This is currently only used in snapsync stage.
214// TODO: Check if we can remove this trait and use [`StorageReadView`] instead.
215pub trait StorageLockedView: Send + Sync {
216    /// Retrieves a value by key from the locked table.
217    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, StoreError>;
218}