Skip to main content

reth_db_api/
database.rs

1use crate::{table::TableImporter, transaction::DbTx, DatabaseError};
2use std::{
3    fmt::Debug,
4    path::PathBuf,
5    sync::Arc,
6    time::{Duration, Instant},
7};
8use tracing::{error, warn};
9
10/// How often [`ReaderTxnTracker::wait_for_pre_commit_readers`] clears reader slots of dead
11/// processes.
12const READER_CHECK_INTERVAL: Duration = Duration::from_secs(1);
13
14/// How often [`ReaderTxnTracker::wait_for_pre_commit_readers`] warns while still waiting.
15const SLOW_READERS_WARN_INTERVAL: Duration = Duration::from_secs(10);
16
17/// Main Database trait that can open read-only and read-write transactions.
18///
19/// Sealed trait which cannot be implemented by 3rd parties, exposed only for consumption.
20pub trait Database: Send + Sync + Debug {
21    /// Read-Only database transaction
22    type TX: DbTx + Sync + 'static;
23    /// Read-Write database transaction
24    type TXMut: DbTx + TableImporter + Sync + 'static;
25
26    /// Create read only transaction.
27    #[track_caller]
28    fn tx(&self) -> Result<Self::TX, DatabaseError>;
29
30    /// Create read write transaction only possible if database is open with write access.
31    #[track_caller]
32    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError>;
33
34    /// Returns the path to the database directory.
35    fn path(&self) -> PathBuf;
36
37    /// Returns the transaction ID of the oldest active reader, if available.
38    ///
39    /// This is the committed txnid of the snapshot the reader is pinned to, not a unique per-reader
40    /// identifier, so multiple readers can report the same txnid.
41    ///
42    /// Used to check whether stale readers from a previous write transaction have completed.
43    /// Returns `None` if no readers are active or the backend does not support this query.
44    fn oldest_reader_txnid(&self) -> Option<u64>;
45
46    /// Returns the ID of the most recently committed transaction, if available.
47    fn last_txnid(&self) -> Option<u64>;
48
49    /// Clears reader slots left behind by processes that no longer exist, so they stop counting
50    /// towards [`Self::oldest_reader_txnid`].
51    ///
52    /// MDBX skips slots carrying this process's own PID, so a stale slot left by a dead process
53    /// whose PID was reused by this one is not cleared.
54    ///
55    /// Does nothing by default, for backends without such slots.
56    fn reader_check(&self) -> Result<(), DatabaseError> {
57        Ok(())
58    }
59
60    /// Takes a function and passes a read-only transaction into it, making sure it's closed in the
61    /// end of the execution.
62    fn view<T, F>(&self, f: F) -> Result<T, DatabaseError>
63    where
64        F: FnOnce(&mut Self::TX) -> T,
65    {
66        let mut tx = self.tx()?;
67
68        let res = f(&mut tx);
69        tx.commit()?;
70
71        Ok(res)
72    }
73
74    /// Takes a function and passes a write-read transaction into it, making sure it's committed in
75    /// the end of the execution.
76    fn update<T, F>(&self, f: F) -> Result<T, DatabaseError>
77    where
78        F: FnOnce(&Self::TXMut) -> T,
79    {
80        let tx = self.tx_mut()?;
81
82        let res = f(&tx);
83        tx.commit()?;
84
85        Ok(res)
86    }
87}
88
89impl<DB: Database> Database for Arc<DB> {
90    type TX = <DB as Database>::TX;
91    type TXMut = <DB as Database>::TXMut;
92
93    fn tx(&self) -> Result<Self::TX, DatabaseError> {
94        <DB as Database>::tx(self)
95    }
96
97    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
98        <DB as Database>::tx_mut(self)
99    }
100
101    fn path(&self) -> PathBuf {
102        <DB as Database>::path(self)
103    }
104
105    fn oldest_reader_txnid(&self) -> Option<u64> {
106        <DB as Database>::oldest_reader_txnid(self)
107    }
108
109    fn last_txnid(&self) -> Option<u64> {
110        <DB as Database>::last_txnid(self)
111    }
112
113    fn reader_check(&self) -> Result<(), DatabaseError> {
114        <DB as Database>::reader_check(self)
115    }
116}
117
118impl<DB: Database> Database for &DB {
119    type TX = <DB as Database>::TX;
120    type TXMut = <DB as Database>::TXMut;
121
122    fn tx(&self) -> Result<Self::TX, DatabaseError> {
123        <DB as Database>::tx(self)
124    }
125
126    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
127        <DB as Database>::tx_mut(self)
128    }
129
130    fn path(&self) -> PathBuf {
131        <DB as Database>::path(self)
132    }
133
134    fn oldest_reader_txnid(&self) -> Option<u64> {
135        <DB as Database>::oldest_reader_txnid(self)
136    }
137
138    fn last_txnid(&self) -> Option<u64> {
139        <DB as Database>::last_txnid(self)
140    }
141
142    fn reader_check(&self) -> Result<(), DatabaseError> {
143        <DB as Database>::reader_check(self)
144    }
145}
146
147/// Object-safe adapter for reader-txn tracking during unwind.
148pub trait ReaderTxnTracker: Send + Sync {
149    /// Waits until all readers older than the latest committed txnid have drained.
150    ///
151    /// Returns an error only if the environment stops answering queries, such as after a fatal
152    /// MDBX error, since then it can no longer tell whether old readers remain.
153    fn wait_for_pre_commit_readers(&self) -> Result<(), DatabaseError>;
154}
155
156impl<DB: Database> ReaderTxnTracker for DB {
157    /// There is intentionally no deadline: proceeding while a reader still sees the pre-commit
158    /// view would let it observe a mix of old MDBX state and later cross-store unwind steps.
159    /// Instead, slots of dead processes are periodically cleared and a slow wait is logged.
160    fn wait_for_pre_commit_readers(&self) -> Result<(), DatabaseError> {
161        // A committed txnid is never 0, so `None` here means the environment stopped answering.
162        let Some(committed_txnid) = Database::last_txnid(self) else {
163            return Database::reader_check(self)
164        };
165        let start = Instant::now();
166        let mut last_reader_check = start;
167        let mut last_warn = start;
168        loop {
169            let oldest_reader_txnid = Database::oldest_reader_txnid(self);
170            match oldest_reader_txnid {
171                Some(oldest) if oldest >= committed_txnid => return Ok(()),
172                // `None` means no readers only while the environment still answers queries. If
173                // it stopped answering, as after a fatal MDBX error, surface the reader check's
174                // error instead of releasing readers that may still see the pre-commit view.
175                None if Database::last_txnid(self).is_some() => return Ok(()),
176                None => Database::reader_check(self)?,
177                _ => {}
178            }
179            if last_reader_check.elapsed() >= READER_CHECK_INTERVAL {
180                if let Err(err) = Database::reader_check(self) {
181                    error!(target: "storage::db", %err, "Failed to clear stale database readers");
182                }
183                last_reader_check = Instant::now();
184                // Re-sample before warning, since the check may have cleared the oldest reader.
185                continue
186            }
187            if last_warn.elapsed() >= SLOW_READERS_WARN_INTERVAL {
188                warn!(
189                    target: "storage::db",
190                    ?oldest_reader_txnid,
191                    committed_txnid,
192                    elapsed = ?start.elapsed(),
193                    "Waiting for database readers older than the last commit to finish"
194                );
195                last_warn = Instant::now();
196            }
197            std::thread::sleep(Duration::from_millis(10));
198        }
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use crate::mock::TxMock;
206    use std::sync::{
207        atomic::{AtomicBool, Ordering},
208        mpsc,
209    };
210
211    /// Mimics a fatal MDBX environment: after the commit, every environment query fails.
212    #[derive(Debug, Default)]
213    struct FatalAfterCommitDb {
214        /// Whether the first `last_txnid` query still succeeds.
215        answers_first_query: bool,
216        queried: AtomicBool,
217    }
218
219    impl Database for FatalAfterCommitDb {
220        type TX = TxMock;
221        type TXMut = TxMock;
222
223        fn tx(&self) -> Result<Self::TX, DatabaseError> {
224            Ok(TxMock::default())
225        }
226
227        fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
228            Ok(TxMock::default())
229        }
230
231        fn path(&self) -> PathBuf {
232            PathBuf::default()
233        }
234
235        fn oldest_reader_txnid(&self) -> Option<u64> {
236            None
237        }
238
239        fn last_txnid(&self) -> Option<u64> {
240            (self.answers_first_query && !self.queried.swap(true, Ordering::SeqCst)).then_some(2)
241        }
242
243        fn reader_check(&self) -> Result<(), DatabaseError> {
244            Err(DatabaseError::Other("fatal".into()))
245        }
246    }
247
248    #[test]
249    fn wait_for_pre_commit_readers_fails_on_fatal_env() {
250        // The environment turns fatal either during the wait or before it starts.
251        for answers_first_query in [true, false] {
252            let db = FatalAfterCommitDb { answers_first_query, ..Default::default() };
253            let (done_tx, done_rx) = mpsc::channel();
254            std::thread::spawn(move || {
255                let _ = done_tx.send(db.wait_for_pre_commit_readers());
256            });
257            let result = done_rx
258                .recv_timeout(Duration::from_secs(5))
259                .expect("wait_for_pre_commit_readers hung on a fatal environment");
260            assert!(
261                matches!(&result, Err(DatabaseError::Other(msg)) if msg == "fatal"),
262                "answers_first_query={answers_first_query}: {result:?}"
263            );
264        }
265    }
266}