Skip to main content

reth_storage_api/
database_provider.rs

1use alloc::vec::Vec;
2use core::ops::{Bound, RangeBounds};
3use reth_db_api::{
4    common::KeyValue,
5    cursor::DbCursorRO,
6    database::Database,
7    table::Table,
8    transaction::{DbTx, DbTxMut},
9    DatabaseError,
10};
11use reth_prune_types::PruneModes;
12use reth_storage_errors::provider::ProviderResult;
13
14/// Provides shared access to a database transaction.
15#[auto_impl::auto_impl(&)]
16pub trait DbTxProvider {
17    /// Underlying database transaction held by the provider.
18    type Tx: DbTx + 'static;
19
20    /// Returns the underlying database transaction.
21    fn tx(&self) -> &Self::Tx;
22}
23
24/// Database provider.
25pub trait DBProvider: DbTxProvider + Sized {
26    /// Returns a reference to the underlying transaction.
27    fn tx_ref(&self) -> &Self::Tx {
28        self.tx()
29    }
30
31    /// Returns a mutable reference to the underlying transaction.
32    fn tx_mut(&mut self) -> &mut Self::Tx;
33
34    /// Consumes the provider and returns the underlying transaction.
35    fn into_tx(self) -> Self::Tx;
36
37    /// Disables long-lived read transaction safety guarantees for leaks prevention and
38    /// observability improvements.
39    ///
40    /// CAUTION: In most of the cases, you want the safety guarantees for long read transactions
41    /// enabled. Use this only if you're sure that no write transaction is open in parallel, meaning
42    /// that Reth as a node is offline and not progressing.
43    fn disable_long_read_transaction_safety(mut self) -> Self {
44        self.tx_mut().disable_long_read_transaction_safety();
45        self
46    }
47
48    /// Commit database transaction
49    fn commit(self) -> ProviderResult<()>;
50
51    /// Returns a reference to prune modes.
52    fn prune_modes_ref(&self) -> &PruneModes;
53
54    /// Return full table as Vec
55    fn table<T: Table>(&self) -> Result<Vec<KeyValue<T>>, DatabaseError>
56    where
57        T::Key: Default + Ord,
58    {
59        self.tx_ref()
60            .cursor_read::<T>()?
61            .walk(Some(T::Key::default()))?
62            .collect::<Result<Vec<_>, DatabaseError>>()
63    }
64
65    /// Return a list of entries from the table, based on the given range.
66    #[inline]
67    fn get<T: Table>(
68        &self,
69        range: impl RangeBounds<T::Key>,
70    ) -> Result<Vec<KeyValue<T>>, DatabaseError> {
71        self.tx_ref().cursor_read::<T>()?.walk_range(range)?.collect::<Result<Vec<_>, _>>()
72    }
73
74    /// Iterates over read only values in the given table and collects them into a vector.
75    ///
76    /// Early-returns if the range is empty, without opening a cursor transaction.
77    fn cursor_read_collect<T: Table<Key = u64>>(
78        &self,
79        range: impl RangeBounds<T::Key>,
80    ) -> ProviderResult<Vec<T::Value>> {
81        let capacity = match range_size_hint(&range) {
82            Some(0) | None => return Ok(Vec::new()),
83            Some(capacity) => capacity,
84        };
85        let mut cursor = self.tx_ref().cursor_read::<T>()?;
86        let mut items = Vec::with_capacity(capacity);
87        for entry in cursor.walk_range(range)? {
88            items.push(entry?.1);
89        }
90        Ok(items)
91    }
92
93    /// Remove list of entries from the table. Returns the number of entries removed.
94    #[inline]
95    fn remove<T: Table>(&self, range: impl RangeBounds<T::Key>) -> Result<usize, DatabaseError>
96    where
97        Self::Tx: DbTxMut,
98    {
99        let mut entries = 0;
100        let mut cursor_write = self.tx_ref().cursor_write::<T>()?;
101        let mut walker = cursor_write.walk_range(range)?;
102        while walker.next().transpose()?.is_some() {
103            walker.delete_current()?;
104            entries += 1;
105        }
106        Ok(entries)
107    }
108
109    /// Return a list of entries from the table, and remove them, based on the given range.
110    #[inline]
111    fn take<T: Table>(
112        &self,
113        range: impl RangeBounds<T::Key>,
114    ) -> Result<Vec<KeyValue<T>>, DatabaseError>
115    where
116        Self::Tx: DbTxMut,
117    {
118        let mut cursor_write = self.tx_ref().cursor_write::<T>()?;
119        let mut walker = cursor_write.walk_range(range)?;
120        let mut items = Vec::new();
121        while let Some(i) = walker.next().transpose()? {
122            walker.delete_current()?;
123            items.push(i)
124        }
125        Ok(items)
126    }
127}
128
129/// Database provider factory.
130#[auto_impl::auto_impl(&, Arc)]
131pub trait DatabaseProviderFactory: Send + Sync {
132    /// Database this factory produces providers for.
133    type DB: Database;
134
135    /// Provider type returned by the factory.
136    type Provider: DBProvider<Tx = <Self::DB as Database>::TX>;
137
138    /// Read-write provider type returned by the factory.
139    type ProviderRW: DBProvider<Tx = <Self::DB as Database>::TXMut>;
140
141    /// Create new read-only database provider.
142    fn database_provider_ro(&self) -> ProviderResult<Self::Provider>;
143
144    /// Create new read-write database provider.
145    fn database_provider_rw(&self) -> ProviderResult<Self::ProviderRW>;
146}
147
148/// A trait which can be used to describe any factory-like type which returns a read-only provider.
149pub trait DatabaseProviderROFactory {
150    /// Provider type returned by this factory.
151    ///
152    /// This type is intentionally left unconstrained; constraints can be added as-needed when this
153    /// is used.
154    type Provider;
155
156    /// Creates and returns a Provider.
157    fn database_provider_ro(&self) -> ProviderResult<Self::Provider>;
158}
159
160impl<T> DatabaseProviderROFactory for T
161where
162    T: DatabaseProviderFactory,
163{
164    type Provider = T::Provider;
165
166    fn database_provider_ro(&self) -> ProviderResult<Self::Provider> {
167        <T as DatabaseProviderFactory>::database_provider_ro(self)
168    }
169}
170
171/// Returns the length of the range if the range has a bounded end.
172pub fn range_size_hint(range: &impl RangeBounds<u64>) -> Option<usize> {
173    let start = match range.start_bound().cloned() {
174        Bound::Included(start) => start,
175        Bound::Excluded(start) => start.checked_add(1)?,
176        Bound::Unbounded => 0,
177    };
178    let end = match range.end_bound().cloned() {
179        Bound::Included(end) => end.saturating_add(1),
180        Bound::Excluded(end) => end,
181        Bound::Unbounded => return None,
182    };
183    end.checked_sub(start).map(|x| x as _)
184}