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 static files 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_static_files } =
105            config.into();
106        let db = open_db_read_only(db_dir, db_args)?;
107        let static_file_provider =
108            StaticFileProvider::read_only(static_files_dir, watch_static_files)?;
109        let rocksdb_provider =
110            RocksDBProvider::builder(&rocksdb_dir).with_default_tables().build()?;
111        ProviderFactory::new(db, chainspec, static_file_provider, rocksdb_provider, runtime)
112            .map_err(Into::into)
113    }
114}
115
116impl<N> Default for ProviderFactoryBuilder<N> {
117    fn default() -> Self {
118        Self { _types: Default::default() }
119    }
120}
121
122/// Settings for how to open the database, static files, and `RocksDB`.
123///
124/// The default derivation from a path assumes the path is the datadir:
125/// [`ReadOnlyConfig::from_datadir`]
126#[derive(Debug, Clone)]
127pub struct ReadOnlyConfig {
128    /// The path to the database directory.
129    pub db_dir: PathBuf,
130    /// How to open the database
131    pub db_args: DatabaseArguments,
132    /// The path to the static file dir
133    pub static_files_dir: PathBuf,
134    /// The path to the `RocksDB` directory
135    pub rocksdb_dir: PathBuf,
136    /// Whether the static files should be watched for changes.
137    pub watch_static_files: bool,
138}
139
140impl ReadOnlyConfig {
141    /// Derives the [`ReadOnlyConfig`] from the datadir.
142    ///
143    /// By default this assumes the following datadir layout:
144    ///
145    /// ```text
146    ///  -`datadir`
147    ///    |__db
148    ///    |__rocksdb
149    ///    |__static_files
150    /// ```
151    ///
152    /// By default this watches the static file directory for changes, see also
153    /// [`StaticFileProvider::read_only`]
154    pub fn from_datadir(datadir: impl AsRef<Path>) -> Self {
155        let datadir = datadir.as_ref();
156        Self {
157            db_dir: datadir.join("db"),
158            db_args: Default::default(),
159            static_files_dir: datadir.join("static_files"),
160            rocksdb_dir: datadir.join("rocksdb"),
161            watch_static_files: true,
162        }
163    }
164
165    /// Disables long-lived read transaction safety guarantees.
166    ///
167    /// Caution: Keeping database transaction open indefinitely can cause the free list to grow if
168    /// changes to the database are made.
169    pub const fn disable_long_read_transaction_safety(mut self) -> Self {
170        self.db_args.max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded));
171        self
172    }
173
174    /// Derives the [`ReadOnlyConfig`] from the database dir.
175    ///
176    /// By default this assumes the following datadir layout:
177    ///
178    /// ```text
179    ///    - db
180    ///    - rocksdb
181    ///    - static_files
182    /// ```
183    ///
184    /// By default this watches the static file directory for changes, see also
185    /// [`StaticFileProvider::read_only`]
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    ///
201    /// By default this watches the static file directory for changes, see also
202    /// [`StaticFileProvider::read_only`]
203    pub fn from_dirs(
204        db_dir: impl AsRef<Path>,
205        static_files_dir: impl AsRef<Path>,
206        rocksdb_dir: impl AsRef<Path>,
207    ) -> Self {
208        Self {
209            db_dir: db_dir.as_ref().into(),
210            db_args: Default::default(),
211            static_files_dir: static_files_dir.as_ref().into(),
212            rocksdb_dir: rocksdb_dir.as_ref().into(),
213            watch_static_files: true,
214        }
215    }
216
217    /// Configures the db arguments used when opening the database.
218    pub fn with_db_args(mut self, db_args: impl Into<DatabaseArguments>) -> Self {
219        self.db_args = db_args.into();
220        self
221    }
222
223    /// Configures the db directory.
224    pub fn with_db_dir(mut self, db_dir: impl Into<PathBuf>) -> Self {
225        self.db_dir = db_dir.into();
226        self
227    }
228
229    /// Configures the static file directory.
230    pub fn with_static_file_dir(mut self, static_file_dir: impl Into<PathBuf>) -> Self {
231        self.static_files_dir = static_file_dir.into();
232        self
233    }
234
235    /// Whether the static file directory should be watches for changes, see also
236    /// [`StaticFileProvider::read_only`]
237    pub const fn set_watch_static_files(&mut self, watch_static_files: bool) {
238        self.watch_static_files = watch_static_files;
239    }
240
241    /// Don't watch the static files for changes.
242    ///
243    /// This is only recommended if this is used without a running node instance that modifies
244    /// static files.
245    pub const fn no_watch(mut self) -> Self {
246        self.set_watch_static_files(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}