reth_provider/providers/database/builder.rs
1//! Helper builder entrypoint to instantiate a [`ProviderFactory`].
2
3use crate::{
4 providers::{NodeTypesForProvider, RocksDBProvider, StaticFileProvider},
5 ProviderFactory,
6};
7use reth_db::{
8 mdbx::{DatabaseArguments, MaxReadTransactionDuration},
9 open_db_read_only, DatabaseEnv,
10};
11use reth_node_types::NodeTypesWithDBAdapter;
12use reth_storage_overlay::OverlayManager;
13use std::{
14 marker::PhantomData,
15 path::{Path, PathBuf},
16 sync::Arc,
17};
18
19/// Helper type to create a [`ProviderFactory`].
20///
21/// See [`ProviderFactoryBuilder::open_read_only`] for usage examples.
22#[derive(Debug)]
23pub struct ProviderFactoryBuilder<N> {
24 _types: PhantomData<N>,
25}
26
27impl<N> ProviderFactoryBuilder<N> {
28 /// Maps the [`reth_node_types::NodeTypes`] of this builder.
29 pub fn types<T>(self) -> ProviderFactoryBuilder<T> {
30 ProviderFactoryBuilder::default()
31 }
32
33 /// Opens the database with the given chainspec and [`ReadOnlyConfig`].
34 ///
35 /// # Open a monitored instance
36 ///
37 /// This is recommended when the new read-only instance is used with an active node.
38 ///
39 /// ```no_run
40 /// use reth_chainspec::MAINNET;
41 /// use reth_provider::providers::{NodeTypesForProvider, ProviderFactoryBuilder};
42 ///
43 /// fn demo<N: NodeTypesForProvider<ChainSpec = reth_chainspec::ChainSpec>>(
44 /// runtime: reth_tasks::Runtime,
45 /// ) {
46 /// let provider_factory = ProviderFactoryBuilder::<N>::default()
47 /// .open_read_only(MAINNET.clone(), "datadir", runtime)
48 /// .unwrap();
49 /// }
50 /// ```
51 ///
52 /// # Open an unmonitored instance
53 ///
54 /// This is recommended when no changes to the database are expected (e.g. no active node)
55 ///
56 /// ```no_run
57 /// use reth_chainspec::MAINNET;
58 /// use reth_provider::providers::{NodeTypesForProvider, ProviderFactoryBuilder, ReadOnlyConfig};
59 ///
60 /// fn demo<N: NodeTypesForProvider<ChainSpec = reth_chainspec::ChainSpec>>(
61 /// runtime: reth_tasks::Runtime,
62 /// ) {
63 /// let provider_factory = ProviderFactoryBuilder::<N>::default()
64 /// .open_read_only(
65 /// MAINNET.clone(),
66 /// ReadOnlyConfig::from_datadir("datadir").no_watch(),
67 /// runtime,
68 /// )
69 /// .unwrap();
70 /// }
71 /// ```
72 ///
73 /// # Open an instance with disabled read-transaction timeout
74 ///
75 /// By default, read transactions are automatically terminated after a timeout to prevent
76 /// database free list growth. However, if the database is static (no writes occurring), this
77 /// safety mechanism can be disabled using
78 /// [`ReadOnlyConfig::disable_long_read_transaction_safety`].
79 ///
80 /// ```no_run
81 /// use reth_chainspec::MAINNET;
82 /// use reth_provider::providers::{NodeTypesForProvider, ProviderFactoryBuilder, ReadOnlyConfig};
83 ///
84 /// fn demo<N: NodeTypesForProvider<ChainSpec = reth_chainspec::ChainSpec>>(
85 /// runtime: reth_tasks::Runtime,
86 /// ) {
87 /// let provider_factory = ProviderFactoryBuilder::<N>::default()
88 /// .open_read_only(
89 /// MAINNET.clone(),
90 /// ReadOnlyConfig::from_datadir("datadir").disable_long_read_transaction_safety(),
91 /// runtime,
92 /// )
93 /// .unwrap();
94 /// }
95 /// ```
96 pub fn open_read_only(
97 self,
98 chainspec: Arc<N::ChainSpec>,
99 config: impl Into<ReadOnlyConfig>,
100 runtime: reth_tasks::Runtime,
101 ) -> eyre::Result<ProviderFactory<NodeTypesWithDBAdapter<N, DatabaseEnv>>>
102 where
103 N: NodeTypesForProvider,
104 {
105 let ReadOnlyConfig { db_dir, db_args, static_files_dir, rocksdb_dir, watch } =
106 config.into();
107 let db = open_db_read_only(db_dir, db_args)?;
108 let static_file_provider = StaticFileProvider::read_only(static_files_dir)?;
109 let rocksdb_provider = RocksDBProvider::builder(&rocksdb_dir)
110 .with_default_tables()
111 .with_read_only(true)
112 .build()?;
113 let factory = ProviderFactory::new(
114 db,
115 chainspec,
116 static_file_provider,
117 rocksdb_provider,
118 OverlayManager::default(),
119 runtime,
120 )?
121 .with_read_only_sync(watch);
122 Ok(factory)
123 }
124}
125
126impl<N> Default for ProviderFactoryBuilder<N> {
127 fn default() -> Self {
128 Self { _types: Default::default() }
129 }
130}
131
132/// Settings for how to open the database, static files, and `RocksDB`.
133///
134/// The default derivation from a path assumes the path is the datadir:
135/// [`ReadOnlyConfig::from_datadir`]
136#[derive(Debug, Clone)]
137pub struct ReadOnlyConfig {
138 /// The path to the database directory.
139 pub db_dir: PathBuf,
140 /// How to open the database
141 pub db_args: DatabaseArguments,
142 /// The path to the static file dir
143 pub static_files_dir: PathBuf,
144 /// The path to the `RocksDB` directory
145 pub rocksdb_dir: PathBuf,
146 /// Whether to watch the MDBX directory for changes and eagerly sync providers.
147 pub watch: bool,
148}
149
150impl ReadOnlyConfig {
151 /// Derives the [`ReadOnlyConfig`] from the datadir.
152 ///
153 /// By default this assumes the following datadir layout:
154 ///
155 /// ```text
156 /// -`datadir`
157 /// |__db
158 /// |__rocksdb
159 /// |__static_files
160 /// ```
161 ///
162 /// By default this watches the static files directory for changes, see also
163 /// [`ProviderFactory::with_read_only_sync`]
164 pub fn from_datadir(datadir: impl AsRef<Path>) -> Self {
165 let datadir = datadir.as_ref();
166 Self {
167 db_dir: datadir.join("db"),
168 db_args: Default::default(),
169 static_files_dir: datadir.join("static_files"),
170 rocksdb_dir: datadir.join("rocksdb"),
171 watch: true,
172 }
173 }
174
175 /// Disables long-lived read transaction safety guarantees.
176 ///
177 /// Caution: Keeping database transaction open indefinitely can cause the free list to grow if
178 /// changes to the database are made.
179 pub const fn disable_long_read_transaction_safety(mut self) -> Self {
180 self.db_args.max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded));
181 self
182 }
183
184 /// Derives the [`ReadOnlyConfig`] from the database dir.
185 ///
186 /// By default this assumes the following datadir layout:
187 ///
188 /// ```text
189 /// - db
190 /// - rocksdb
191 /// - static_files
192 /// ```
193 ///
194 /// # Panics
195 ///
196 /// If the path does not exist
197 pub fn from_db_dir(db_dir: impl AsRef<Path>) -> Self {
198 let db_dir = db_dir.as_ref();
199 let datadir = std::fs::canonicalize(db_dir).unwrap().parent().unwrap().to_path_buf();
200 let static_files_dir = datadir.join("static_files");
201 let rocksdb_dir = datadir.join("rocksdb");
202 Self::from_dirs(db_dir, static_files_dir, rocksdb_dir)
203 }
204
205 /// Creates the config for the given paths.
206 ///
207 /// By default this watches the static files directory for changes, see also
208 /// [`ProviderFactory::with_read_only_sync`]
209 pub fn from_dirs(
210 db_dir: impl AsRef<Path>,
211 static_files_dir: impl AsRef<Path>,
212 rocksdb_dir: impl AsRef<Path>,
213 ) -> Self {
214 Self {
215 db_dir: db_dir.as_ref().into(),
216 db_args: Default::default(),
217 static_files_dir: static_files_dir.as_ref().into(),
218 rocksdb_dir: rocksdb_dir.as_ref().into(),
219 watch: true,
220 }
221 }
222
223 /// Configures the db arguments used when opening the database.
224 pub fn with_db_args(mut self, db_args: impl Into<DatabaseArguments>) -> Self {
225 self.db_args = db_args.into();
226 self
227 }
228
229 /// Configures the db directory.
230 pub fn with_db_dir(mut self, db_dir: impl Into<PathBuf>) -> Self {
231 self.db_dir = db_dir.into();
232 self
233 }
234
235 /// Configures the static file directory.
236 pub fn with_static_file_dir(mut self, static_file_dir: impl Into<PathBuf>) -> Self {
237 self.static_files_dir = static_file_dir.into();
238 self
239 }
240
241 /// Don't watch the static files directory for changes.
242 ///
243 /// This is only recommended if this is used without a running node instance that modifies
244 /// the database.
245 pub const fn no_watch(mut self) -> Self {
246 self.watch = false;
247 self
248 }
249}
250
251impl<T> From<T> for ReadOnlyConfig
252where
253 T: AsRef<Path>,
254{
255 fn from(value: T) -> Self {
256 Self::from_datadir(value.as_ref())
257 }
258}