Skip to main content

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