1#![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))]
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#[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 pub const ERROR_DB_OPEN: &str = "could not open the database file";
60 pub const ERROR_DB_CREATION: &str = "could not create the database file";
62 pub const ERROR_STATIC_FILES_CREATION: &str = "could not create the static file path";
64 pub const ERROR_TABLE_CREATION: &str = "could not create tables in the database";
66 pub const ERROR_TEMPDIR: &str = "could not create a temporary directory";
68
69 pub struct TempDatabase<DB> {
71 db: Option<DB>,
72 path: PathBuf,
73 pre_tx_hook: RwLock<Box<dyn Fn() + Send + Sync>>,
75 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 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 pub const fn db(&self) -> &DB {
107 self.db.as_ref().unwrap()
108 }
109
110 pub fn path(&self) -> &Path {
112 &self.path
113 }
114
115 pub fn into_inner_db(mut self) -> DB {
117 self.db.take().unwrap() }
119
120 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 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 #[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 pub fn tempdir_path() -> PathBuf {
164 let builder = tempfile::Builder::new().prefix("reth-test-").rand_bytes(8).tempdir();
165 builder.expect(ERROR_TEMPDIR).keep()
166 }
167
168 #[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 #[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 emsg = format!("{ERROR_DB_CREATION}: {path:?}");
189 let db = init_db(
190 path.as_path(),
191 DatabaseArguments::new(ClientVersion::default())
192 .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded)),
193 )
194 .expect(&emsg);
195 Arc::new(TempDatabase::new(db, path))
196 }
197
198 #[track_caller]
200 pub fn create_test_ro_db() -> Arc<TempDatabase<DatabaseEnv>> {
201 let args = DatabaseArguments::new(ClientVersion::default())
202 .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded));
203
204 let path = tempdir_path();
205 let emsg = format!("{ERROR_DB_CREATION}: {path:?}");
206 {
207 init_db(path.as_path(), args.clone()).expect(&emsg);
208 }
209 let db = open_db_read_only(path.as_path(), args).expect(ERROR_DB_OPEN);
210 Arc::new(TempDatabase::new(db, path))
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use crate::{
217 init_db,
218 mdbx::DatabaseArguments,
219 open_db, tables,
220 version::{db_version_file_path, DatabaseVersionError},
221 };
222 use assert_matches::assert_matches;
223 use reth_db_api::{
224 cursor::DbCursorRO, database::Database, models::ClientVersion, transaction::DbTx,
225 };
226 use reth_libmdbx::MaxReadTransactionDuration;
227 use std::time::Duration;
228 use tempfile::tempdir;
229
230 #[test]
231 fn db_version() {
232 let path = tempdir().unwrap();
233
234 let args = DatabaseArguments::new(ClientVersion::default())
235 .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded));
236
237 {
239 let db = init_db(&path, args.clone());
240 assert_matches!(db, Ok(_));
241 }
242
243 {
245 let db = init_db(&path, args.clone());
246 assert_matches!(db, Ok(_));
247 }
248
249 {
251 reth_fs_util::write(path.path().join(db_version_file_path(&path)), "invalid-version")
252 .unwrap();
253 let db = init_db(&path, args.clone());
254 assert!(db.is_err());
255 assert_matches!(
256 db.unwrap_err().downcast_ref::<DatabaseVersionError>(),
257 Some(DatabaseVersionError::MalformedFile)
258 )
259 }
260
261 {
263 reth_fs_util::write(path.path().join(db_version_file_path(&path)), "0").unwrap();
264 let db = init_db(&path, args);
265 assert!(db.is_err());
266 assert_matches!(
267 db.unwrap_err().downcast_ref::<DatabaseVersionError>(),
268 Some(DatabaseVersionError::VersionMismatch { version: 0 })
269 )
270 }
271 }
272
273 #[test]
274 fn db_client_version() {
275 let path = tempdir().unwrap();
276
277 {
279 let db = init_db(&path, DatabaseArguments::new(ClientVersion::default())).unwrap();
280 let tx = db.tx().unwrap();
281 let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
282 assert_matches!(cursor.first(), Ok(None));
283 }
284
285 let first_version = ClientVersion { version: String::from("v1"), ..Default::default() };
287 {
288 let db = init_db(&path, DatabaseArguments::new(first_version.clone())).unwrap();
289 let tx = db.tx().unwrap();
290 let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
291 assert_eq!(
292 cursor
293 .walk_range(..)
294 .unwrap()
295 .map(|x| x.map(|(_, v)| v))
296 .collect::<Result<Vec<_>, _>>()
297 .unwrap(),
298 vec![first_version.clone()]
299 );
300 }
301
302 {
304 let db = init_db(&path, DatabaseArguments::new(first_version.clone())).unwrap();
305 let tx = db.tx().unwrap();
306 let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
307 assert_eq!(
308 cursor
309 .walk_range(..)
310 .unwrap()
311 .map(|x| x.map(|(_, v)| v))
312 .collect::<Result<Vec<_>, _>>()
313 .unwrap(),
314 vec![first_version.clone()]
315 );
316 }
317
318 std::thread::sleep(Duration::from_secs(1));
320 let second_version = ClientVersion { version: String::from("v2"), ..Default::default() };
321 {
322 let db = init_db(&path, DatabaseArguments::new(second_version.clone())).unwrap();
323 let tx = db.tx().unwrap();
324 let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
325 assert_eq!(
326 cursor
327 .walk_range(..)
328 .unwrap()
329 .map(|x| x.map(|(_, v)| v))
330 .collect::<Result<Vec<_>, _>>()
331 .unwrap(),
332 vec![first_version.clone(), second_version.clone()]
333 );
334 }
335
336 std::thread::sleep(Duration::from_secs(1));
338 let third_version = ClientVersion { version: String::from("v3"), ..Default::default() };
339 {
340 let db = open_db(path.path(), DatabaseArguments::new(third_version.clone())).unwrap();
341 let tx = db.tx().unwrap();
342 let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
343 assert_eq!(
344 cursor
345 .walk_range(..)
346 .unwrap()
347 .map(|x| x.map(|(_, v)| v))
348 .collect::<Result<Vec<_>, _>>()
349 .unwrap(),
350 vec![first_version, second_version, third_version]
351 );
352 }
353 }
354}