reth_db/
lib.rs

1//! MDBX implementation for reth's database abstraction layer.
2//!
3//! This crate is an implementation of [`reth-db-api`] for MDBX, as well as a few other common
4//! database types.
5//!
6//! # Overview
7//!
8//! An overview of the current data model of reth can be found in the [`mod@tables`] module.
9
10#![doc(
11    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
12    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
13    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
14)]
15#![cfg_attr(not(test), warn(unused_crate_dependencies))]
16#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
17
18mod implementation;
19pub mod lockfile;
20#[cfg(feature = "mdbx")]
21mod metrics;
22pub mod static_file;
23#[cfg(feature = "mdbx")]
24mod utils;
25pub mod version;
26
27#[cfg(feature = "mdbx")]
28pub mod mdbx;
29
30pub use reth_storage_errors::db::{DatabaseError, DatabaseWriteOperation};
31#[cfg(feature = "mdbx")]
32pub use utils::is_database_empty;
33
34#[cfg(feature = "mdbx")]
35pub use mdbx::{create_db, init_db, open_db, open_db_read_only, DatabaseEnv, DatabaseEnvKind};
36
37pub use models::ClientVersion;
38pub use reth_db_api::*;
39
40/// Collection of database test utilities
41#[cfg(any(test, feature = "test-utils"))]
42pub mod test_utils {
43    use super::*;
44    use crate::mdbx::DatabaseArguments;
45    use parking_lot::RwLock;
46    use reth_db_api::{
47        database::Database, database_metrics::DatabaseMetrics, models::ClientVersion,
48    };
49    use reth_fs_util;
50    use reth_libmdbx::MaxReadTransactionDuration;
51    use std::{
52        fmt::Formatter,
53        path::{Path, PathBuf},
54        sync::Arc,
55    };
56    use tempfile::TempDir;
57
58    /// Error during database open
59    pub const ERROR_DB_OPEN: &str = "could not open the database file";
60    /// Error during database creation
61    pub const ERROR_DB_CREATION: &str = "could not create the database file";
62    /// Error during database creation
63    pub const ERROR_STATIC_FILES_CREATION: &str = "could not create the static file path";
64    /// Error during table creation
65    pub const ERROR_TABLE_CREATION: &str = "could not create tables in the database";
66    /// Error during tempdir creation
67    pub const ERROR_TEMPDIR: &str = "could not create a temporary directory";
68
69    /// A database will delete the db dir when dropped.
70    pub struct TempDatabase<DB> {
71        db: Option<DB>,
72        path: PathBuf,
73        /// Executed right before a database transaction is created.
74        pre_tx_hook: RwLock<Box<dyn Fn() + Send + Sync>>,
75        /// Executed right after a database transaction is created.
76        post_tx_hook: RwLock<Box<dyn Fn() + Send + Sync>>,
77    }
78
79    impl<DB: std::fmt::Debug> std::fmt::Debug for TempDatabase<DB> {
80        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
81            f.debug_struct("TempDatabase").field("db", &self.db).field("path", &self.path).finish()
82        }
83    }
84
85    impl<DB> Drop for TempDatabase<DB> {
86        fn drop(&mut self) {
87            if let Some(db) = self.db.take() {
88                drop(db);
89                let _ = reth_fs_util::remove_dir_all(&self.path);
90            }
91        }
92    }
93
94    impl<DB> TempDatabase<DB> {
95        /// Create new [`TempDatabase`] instance.
96        pub fn new(db: DB, path: PathBuf) -> Self {
97            Self {
98                db: Some(db),
99                path,
100                pre_tx_hook: RwLock::new(Box::new(|| ())),
101                post_tx_hook: RwLock::new(Box::new(|| ())),
102            }
103        }
104
105        /// Returns the reference to inner db.
106        pub fn db(&self) -> &DB {
107            self.db.as_ref().unwrap()
108        }
109
110        /// Returns the path to the database.
111        pub fn path(&self) -> &Path {
112            &self.path
113        }
114
115        /// Convert temp database into inner.
116        pub fn into_inner_db(mut self) -> DB {
117            self.db.take().unwrap() // take out db to avoid clean path in drop fn
118        }
119
120        /// Sets [`TempDatabase`] new pre transaction creation hook.
121        pub fn set_pre_transaction_hook(&self, hook: Box<dyn Fn() + Send + Sync>) {
122            let mut db_hook = self.pre_tx_hook.write();
123            *db_hook = hook;
124        }
125
126        /// Sets [`TempDatabase`] new post transaction creation hook.
127        pub fn set_post_transaction_hook(&self, hook: Box<dyn Fn() + Send + Sync>) {
128            let mut db_hook = self.post_tx_hook.write();
129            *db_hook = hook;
130        }
131    }
132
133    impl<DB: Database> Database for TempDatabase<DB> {
134        type TX = <DB as Database>::TX;
135        type TXMut = <DB as Database>::TXMut;
136        fn tx(&self) -> Result<Self::TX, DatabaseError> {
137            self.pre_tx_hook.read()();
138            let tx = self.db().tx()?;
139            self.post_tx_hook.read()();
140            Ok(tx)
141        }
142
143        fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
144            self.db().tx_mut()
145        }
146    }
147
148    impl<DB: DatabaseMetrics> DatabaseMetrics for TempDatabase<DB> {
149        fn report_metrics(&self) {
150            self.db().report_metrics()
151        }
152    }
153
154    /// Create `static_files` path for testing
155    #[track_caller]
156    pub fn create_test_static_files_dir() -> (TempDir, PathBuf) {
157        let temp_dir = TempDir::with_prefix("reth-test-static-").expect(ERROR_TEMPDIR);
158        let path = temp_dir.path().to_path_buf();
159        (temp_dir, path)
160    }
161
162    /// Get a temporary directory path to use for the database
163    pub fn tempdir_path() -> PathBuf {
164        let builder = tempfile::Builder::new().prefix("reth-test-").rand_bytes(8).tempdir();
165        builder.expect(ERROR_TEMPDIR).into_path()
166    }
167
168    /// Create read/write database for testing
169    #[track_caller]
170    pub fn create_test_rw_db() -> Arc<TempDatabase<DatabaseEnv>> {
171        let path = tempdir_path();
172        let emsg = format!("{ERROR_DB_CREATION}: {path:?}");
173
174        let db = init_db(
175            &path,
176            DatabaseArguments::new(ClientVersion::default())
177                .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded)),
178        )
179        .expect(&emsg);
180
181        Arc::new(TempDatabase::new(db, path))
182    }
183
184    /// Create read/write database for testing
185    #[track_caller]
186    pub fn create_test_rw_db_with_path<P: AsRef<Path>>(path: P) -> Arc<TempDatabase<DatabaseEnv>> {
187        let path = path.as_ref().to_path_buf();
188        let db = init_db(
189            path.as_path(),
190            DatabaseArguments::new(ClientVersion::default())
191                .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded)),
192        )
193        .expect(ERROR_DB_CREATION);
194        Arc::new(TempDatabase::new(db, path))
195    }
196
197    /// Create read only database for testing
198    #[track_caller]
199    pub fn create_test_ro_db() -> Arc<TempDatabase<DatabaseEnv>> {
200        let args = DatabaseArguments::new(ClientVersion::default())
201            .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded));
202
203        let path = tempdir_path();
204        {
205            init_db(path.as_path(), args.clone()).expect(ERROR_DB_CREATION);
206        }
207        let db = open_db_read_only(path.as_path(), args).expect(ERROR_DB_OPEN);
208        Arc::new(TempDatabase::new(db, path))
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use crate::{
215        init_db,
216        mdbx::DatabaseArguments,
217        open_db, tables,
218        version::{db_version_file_path, DatabaseVersionError},
219    };
220    use assert_matches::assert_matches;
221    use reth_db_api::{
222        cursor::DbCursorRO, database::Database, models::ClientVersion, transaction::DbTx,
223    };
224    use reth_libmdbx::MaxReadTransactionDuration;
225    use std::time::Duration;
226    use tempfile::tempdir;
227
228    #[test]
229    fn db_version() {
230        let path = tempdir().unwrap();
231
232        let args = DatabaseArguments::new(ClientVersion::default())
233            .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded));
234
235        // Database is empty
236        {
237            let db = init_db(&path, args.clone());
238            assert_matches!(db, Ok(_));
239        }
240
241        // Database is not empty, current version is the same as in the file
242        {
243            let db = init_db(&path, args.clone());
244            assert_matches!(db, Ok(_));
245        }
246
247        // Database is not empty, version file is malformed
248        {
249            reth_fs_util::write(path.path().join(db_version_file_path(&path)), "invalid-version")
250                .unwrap();
251            let db = init_db(&path, args.clone());
252            assert!(db.is_err());
253            assert_matches!(
254                db.unwrap_err().downcast_ref::<DatabaseVersionError>(),
255                Some(DatabaseVersionError::MalformedFile)
256            )
257        }
258
259        // Database is not empty, version file contains not matching version
260        {
261            reth_fs_util::write(path.path().join(db_version_file_path(&path)), "0").unwrap();
262            let db = init_db(&path, args);
263            assert!(db.is_err());
264            assert_matches!(
265                db.unwrap_err().downcast_ref::<DatabaseVersionError>(),
266                Some(DatabaseVersionError::VersionMismatch { version: 0 })
267            )
268        }
269    }
270
271    #[test]
272    fn db_client_version() {
273        let path = tempdir().unwrap();
274
275        // Empty client version is not recorded
276        {
277            let db = init_db(&path, DatabaseArguments::new(ClientVersion::default())).unwrap();
278            let tx = db.tx().unwrap();
279            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
280            assert_matches!(cursor.first(), Ok(None));
281        }
282
283        // Client version is recorded
284        let first_version = ClientVersion { version: String::from("v1"), ..Default::default() };
285        {
286            let db = init_db(&path, DatabaseArguments::new(first_version.clone())).unwrap();
287            let tx = db.tx().unwrap();
288            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
289            assert_eq!(
290                cursor
291                    .walk_range(..)
292                    .unwrap()
293                    .map(|x| x.map(|(_, v)| v))
294                    .collect::<Result<Vec<_>, _>>()
295                    .unwrap(),
296                vec![first_version.clone()]
297            );
298        }
299
300        // Same client version is not duplicated.
301        {
302            let db = init_db(&path, DatabaseArguments::new(first_version.clone())).unwrap();
303            let tx = db.tx().unwrap();
304            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
305            assert_eq!(
306                cursor
307                    .walk_range(..)
308                    .unwrap()
309                    .map(|x| x.map(|(_, v)| v))
310                    .collect::<Result<Vec<_>, _>>()
311                    .unwrap(),
312                vec![first_version.clone()]
313            );
314        }
315
316        // Different client version is recorded
317        std::thread::sleep(Duration::from_secs(1));
318        let second_version = ClientVersion { version: String::from("v2"), ..Default::default() };
319        {
320            let db = init_db(&path, DatabaseArguments::new(second_version.clone())).unwrap();
321            let tx = db.tx().unwrap();
322            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
323            assert_eq!(
324                cursor
325                    .walk_range(..)
326                    .unwrap()
327                    .map(|x| x.map(|(_, v)| v))
328                    .collect::<Result<Vec<_>, _>>()
329                    .unwrap(),
330                vec![first_version.clone(), second_version.clone()]
331            );
332        }
333
334        // Different client version is recorded on db open.
335        std::thread::sleep(Duration::from_secs(1));
336        let third_version = ClientVersion { version: String::from("v3"), ..Default::default() };
337        {
338            let db = open_db(path.path(), DatabaseArguments::new(third_version.clone())).unwrap();
339            let tx = db.tx().unwrap();
340            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
341            assert_eq!(
342                cursor
343                    .walk_range(..)
344                    .unwrap()
345                    .map(|x| x.map(|(_, v)| v))
346                    .collect::<Result<Vec<_>, _>>()
347                    .unwrap(),
348                vec![first_version, second_version, third_version]
349            );
350        }
351    }
352}