Skip to main content

reth_db/implementation/mdbx/
tx.rs

1//! Transaction wrapper for libmdbx-sys.
2
3use super::{cursor::Cursor, utils::*, TableDbis};
4use crate::{
5    metrics::{DatabaseEnvMetrics, Operation, TransactionMode, TransactionOutcome},
6    DatabaseError, Tables,
7};
8use reth_db_api::{
9    table::{Compress, DupSort, Encode, IntoVec, Table, TableImporter},
10    transaction::{DbTx, DbTxMut},
11};
12use reth_libmdbx::{ffi::MDBX_dbi, CommitLatency, Transaction, TransactionKind, WriteFlags, RW};
13use reth_primitives_traits::FastInstant as Instant;
14use reth_storage_errors::db::{DatabaseWriteError, DatabaseWriteOperation};
15use std::{
16    backtrace::Backtrace,
17    marker::PhantomData,
18    sync::{
19        atomic::{AtomicBool, Ordering},
20        Arc,
21    },
22    time::Duration,
23};
24use tracing::{debug, instrument, trace, warn};
25
26/// Duration after which we emit the log about long-lived database transactions.
27const LONG_TRANSACTION_DURATION: Duration = Duration::from_secs(60);
28
29/// Wrapper for the libmdbx transaction.
30#[derive(Debug)]
31pub struct Tx<K: TransactionKind> {
32    /// Libmdbx-sys transaction.
33    inner: Transaction<K>,
34
35    /// Cached MDBX DBIs for reuse.
36    dbis: Arc<TableDbis>,
37
38    /// Handler for metrics with its own [Drop] implementation for cases when the transaction isn't
39    /// closed by [`Tx::commit`] or [`Tx::abort`], but we still need to report it in the metrics.
40    ///
41    /// If [Some], then metrics are reported.
42    metrics_handler: Option<MetricsHandler<K>>,
43    /// Persistent read-ahead setting for gets and newly created cursors.
44    #[cfg(target_os = "linux")]
45    prefetch: AtomicBool,
46}
47
48impl<K: TransactionKind> Tx<K> {
49    /// Creates new `Tx` object with a `RO` or `RW` transaction and optionally enables metrics.
50    #[inline]
51    #[track_caller]
52    pub(crate) fn new(
53        inner: Transaction<K>,
54        dbis: Arc<TableDbis>,
55        env_metrics: Option<Arc<DatabaseEnvMetrics>>,
56    ) -> reth_libmdbx::Result<Self> {
57        let metrics_handler = env_metrics
58            .map(|env_metrics| {
59                let handler = MetricsHandler::<K>::new(inner.id()?, env_metrics);
60                handler.env_metrics.record_opened_transaction(handler.transaction_mode());
61                handler.log_transaction_opened();
62                Ok(handler)
63            })
64            .transpose()?;
65        Ok(Self {
66            inner,
67            dbis,
68            metrics_handler,
69            #[cfg(target_os = "linux")]
70            prefetch: AtomicBool::new(false),
71        })
72    }
73
74    /// Returns a reference to the inner libmdbx transaction.
75    pub const fn inner(&self) -> &Transaction<K> {
76        &self.inner
77    }
78
79    /// Gets this transaction ID.
80    pub fn id(&self) -> reth_libmdbx::Result<u64> {
81        self.metrics_handler.as_ref().map_or_else(|| self.inner.id(), |handler| Ok(handler.txn_id))
82    }
83
84    /// Gets a table database handle by name if it exists, otherwise, check the
85    /// database, opening the DB if it exists.
86    pub fn get_dbi_raw(&self, name: &str) -> Result<MDBX_dbi, DatabaseError> {
87        self.get_table_dbi(name.parse::<Tables>().ok(), name)
88    }
89
90    /// Gets a table database handle by name if it exists, otherwise, check the
91    /// database, opening the DB if it exists.
92    pub fn get_dbi<T: Table>(&self) -> Result<MDBX_dbi, DatabaseError> {
93        self.get_table_dbi(T::TABLE, T::NAME)
94    }
95
96    /// Gets the tracked database handle of a table, which is looked up by `table` if it is a
97    /// [`Tables`] entry and by `name` otherwise, opening the DB by name if it is not tracked.
98    fn get_table_dbi(&self, table: Option<Tables>, name: &str) -> Result<MDBX_dbi, DatabaseError> {
99        if let Some(dbi) = self.dbis.get(table, name) {
100            Ok(dbi)
101        } else {
102            self.inner
103                .open_db(Some(name))
104                .map(|db| db.dbi())
105                .map_err(|e| DatabaseError::Open(e.into()))
106        }
107    }
108
109    /// Create db Cursor
110    pub fn new_cursor<T: Table>(&self) -> Result<Cursor<K, T>, DatabaseError> {
111        let inner = self
112            .inner
113            .cursor_with_dbi(self.get_dbi::<T>()?)
114            .map_err(|e| DatabaseError::InitCursor(e.into()))?;
115
116        // Only write cursors record operation metrics. A read-only cursor skips the table's shared
117        // metrics handle, whose reference count every reading thread would otherwise bump.
118        Ok(Cursor::new_with_metrics(
119            inner,
120            self.metrics_handler
121                .as_ref()
122                .filter(|_| !K::IS_READ_ONLY)
123                .zip(T::TABLE)
124                .map(|(h, table)| h.env_metrics.table_operation_metrics(table)),
125            #[cfg(target_os = "linux")]
126            self.prefetch.load(Ordering::Relaxed),
127        ))
128    }
129
130    /// If `self.metrics_handler == Some(_)`, measure the time it takes to execute the closure and
131    /// record a metric with the provided transaction outcome.
132    ///
133    /// Otherwise, just execute the closure.
134    fn execute_with_close_transaction_metric<R>(
135        mut self,
136        outcome: TransactionOutcome,
137        f: impl FnOnce(Self) -> (R, Option<CommitLatency>),
138    ) -> R {
139        let run = |tx| {
140            let start = Instant::now();
141            let (result, commit_latency) = f(tx);
142            let total_duration = start.elapsed();
143
144            if outcome.is_commit() {
145                debug!(
146                    target: "storage::db::mdbx",
147                    ?total_duration,
148                    ?commit_latency,
149                    is_read_only = K::IS_READ_ONLY,
150                    "Commit"
151                );
152            }
153
154            (result, commit_latency, total_duration)
155        };
156
157        if let Some(mut metrics_handler) = self.metrics_handler.take() {
158            metrics_handler.close_recorded = true;
159            metrics_handler.log_backtrace_on_long_read_transaction();
160
161            let (result, commit_latency, close_duration) = run(self);
162            let open_duration = metrics_handler.start.elapsed();
163            metrics_handler.env_metrics.record_closed_transaction(
164                metrics_handler.transaction_mode(),
165                outcome,
166                open_duration,
167                Some(close_duration),
168                commit_latency,
169            );
170
171            result
172        } else {
173            run(self).0
174        }
175    }
176
177    /// If `self.metrics_handler == Some(_)`, measure the time it takes to execute the closure and
178    /// record a metric with the provided operation.
179    ///
180    /// Otherwise, just execute the closure.
181    fn execute_with_operation_metric<T: Table, R>(
182        &self,
183        operation: Operation,
184        value_size: Option<usize>,
185        f: impl FnOnce(&Transaction<K>) -> R,
186    ) -> R {
187        if let Some(metrics_handler) = &self.metrics_handler {
188            metrics_handler.log_backtrace_on_long_read_transaction();
189            metrics_handler
190                .env_metrics
191                .record_operation(T::TABLE, operation, value_size, || f(&self.inner))
192        } else {
193            f(&self.inner)
194        }
195    }
196}
197
198#[derive(Debug)]
199struct MetricsHandler<K: TransactionKind> {
200    /// Cached internal transaction ID provided by libmdbx.
201    txn_id: u64,
202    /// The time when transaction has started.
203    ///
204    /// This is a TSC-backed [`reth_primitives_traits::FastInstant`] rather than
205    /// [`std::time::Instant`] because
206    /// [`MetricsHandler::log_backtrace_on_long_read_transaction`] reads it on every database
207    /// operation.
208    start: Instant,
209    /// The time after which we emit the log about long-lived database transactions.
210    ///
211    /// Stored as a deadline so that the check on every database operation only compares two
212    /// timestamps instead of computing the open duration.
213    long_transaction_deadline: Instant,
214    /// If `true`, the metric about transaction closing has already been recorded and we don't need
215    /// to do anything on [`Drop::drop`].
216    close_recorded: bool,
217    /// If `true`, the backtrace of transaction will be recorded and logged.
218    /// See [`MetricsHandler::log_backtrace_on_long_read_transaction`].
219    record_backtrace: bool,
220    /// If `true`, the backtrace of transaction has already been recorded and logged.
221    /// See [`MetricsHandler::log_backtrace_on_long_read_transaction`].
222    backtrace_recorded: AtomicBool,
223    /// Shared database environment metrics.
224    env_metrics: Arc<DatabaseEnvMetrics>,
225    /// Backtrace of the location where the transaction has been opened. Reported only with debug
226    /// assertions outside DST, because capturing every transaction opening is expensive.
227    #[cfg(all(debug_assertions, not(feature = "fuzz")))]
228    open_backtrace: Backtrace,
229    _marker: PhantomData<K>,
230}
231
232impl<K: TransactionKind> MetricsHandler<K> {
233    fn new(txn_id: u64, env_metrics: Arc<DatabaseEnvMetrics>) -> Self {
234        let start = Instant::now();
235        Self {
236            txn_id,
237            start,
238            long_transaction_deadline: start + LONG_TRANSACTION_DURATION,
239            close_recorded: false,
240            record_backtrace: true,
241            backtrace_recorded: AtomicBool::new(false),
242            #[cfg(all(debug_assertions, not(feature = "fuzz")))]
243            open_backtrace: Backtrace::force_capture(),
244            env_metrics,
245            _marker: PhantomData,
246        }
247    }
248
249    const fn transaction_mode(&self) -> TransactionMode {
250        if K::IS_READ_ONLY {
251            TransactionMode::ReadOnly
252        } else {
253            TransactionMode::ReadWrite
254        }
255    }
256
257    /// Logs the caller location and ID of the transaction that was opened.
258    #[track_caller]
259    fn log_transaction_opened(&self) {
260        trace!(
261            target: "storage::db::mdbx",
262            caller = %core::panic::Location::caller(),
263            id = %self.txn_id,
264            mode = %self.transaction_mode().as_str(),
265            "Transaction opened",
266        );
267    }
268
269    /// Logs the backtrace of current call if the duration that the read transaction has been open
270    /// is more than [`LONG_TRANSACTION_DURATION`] and `record_backtrace == true`.
271    /// The backtrace is recorded and logged just once, guaranteed by `backtrace_recorded` atomic.
272    ///
273    /// NOTE: Backtrace is recorded using [`Backtrace::force_capture`], so `RUST_BACKTRACE` env var
274    /// is not needed.
275    fn log_backtrace_on_long_read_transaction(&self) {
276        if self.record_backtrace &&
277            !self.backtrace_recorded.load(Ordering::Relaxed) &&
278            self.transaction_mode().is_read_only()
279        {
280            let now = Instant::now();
281            if now >= self.long_transaction_deadline {
282                let open_duration = now - self.start;
283                self.backtrace_recorded.store(true, Ordering::Relaxed);
284                #[cfg(all(debug_assertions, not(feature = "fuzz")))]
285                let open_backtrace = format_args!("{}", self.open_backtrace);
286                #[cfg(not(all(debug_assertions, not(feature = "fuzz"))))]
287                let open_backtrace = tracing::field::Empty;
288                warn!(
289                    target: "storage::db::mdbx",
290                    ?open_duration,
291                    id=%self.txn_id,
292                    backtrace=%Backtrace::force_capture(),
293                    open_backtrace,
294                    "A database read transaction has been open for too long"
295                );
296            }
297        }
298    }
299}
300
301impl<K: TransactionKind> Drop for MetricsHandler<K> {
302    fn drop(&mut self) {
303        if !self.close_recorded {
304            self.log_backtrace_on_long_read_transaction();
305            self.env_metrics.record_closed_transaction(
306                self.transaction_mode(),
307                TransactionOutcome::Drop,
308                self.start.elapsed(),
309                None,
310                None,
311            );
312        }
313    }
314}
315
316impl TableImporter for Tx<RW> {}
317
318impl<K: TransactionKind> DbTx for Tx<K> {
319    type Cursor<T: Table> = Cursor<K, T>;
320    type DupCursor<T: DupSort> = Cursor<K, T>;
321
322    fn get<T: Table>(&self, key: T::Key) -> Result<Option<<T as Table>::Value>, DatabaseError> {
323        self.get_by_encoded_key::<T>(&key.encode())
324    }
325
326    fn get_by_encoded_key<T: Table>(
327        &self,
328        key: &<T::Key as Encode>::Encoded,
329    ) -> Result<Option<T::Value>, DatabaseError> {
330        self.execute_with_operation_metric::<T, _>(Operation::Get, None, |tx| {
331            let dbi = self.get_dbi::<T>()?;
332            #[cfg(target_os = "linux")]
333            let value = if self.prefetch.load(Ordering::Relaxed) {
334                tx.get::<super::value_prefetch::PrefetchValue<'_>>(dbi, key.as_ref())
335                    .map(|value| value.map(|value| value.0))
336            } else {
337                tx.get(dbi, key.as_ref())
338            };
339            #[cfg(not(target_os = "linux"))]
340            let value = tx.get(dbi, key.as_ref());
341            value.map_err(|e| DatabaseError::Read(e.into()))?.map(decode_one::<T>).transpose()
342        })
343    }
344
345    #[instrument(name = "Tx::commit", level = "debug", target = "providers::db", skip_all)]
346    fn commit(self) -> Result<(), DatabaseError> {
347        self.execute_with_close_transaction_metric(TransactionOutcome::Commit, |this| {
348            match this.inner.commit().map_err(|e| DatabaseError::Commit(e.into())) {
349                Ok(latency) => (Ok(()), Some(latency)),
350                Err(e) => (Err(e), None),
351            }
352        })
353    }
354
355    /// Syncs read-write commits to disk, since [`SyncMode::SafeNoSync`] commits are lost on a new
356    /// boot after power loss. Best effort under [`SyncMode::UtterlyNoSync`], where later commits
357    /// can overwrite the synced state.
358    ///
359    /// [`SyncMode::SafeNoSync`]: reth_libmdbx::SyncMode::SafeNoSync
360    /// [`SyncMode::UtterlyNoSync`]: reth_libmdbx::SyncMode::UtterlyNoSync
361    #[instrument(name = "Tx::commit_durable", level = "debug", target = "providers::db", skip_all)]
362    fn commit_durable(self) -> Result<(), DatabaseError> {
363        if K::IS_READ_ONLY {
364            return self.commit()
365        }
366        let env = self.inner.env().clone();
367        self.commit()?;
368        // With `MDBX_NOSTICKYTHREADS`, MDBX skips the writer lock when syncing while any write
369        // transaction is open, so hold one to keep other writers out.
370        let _write_lock = env.begin_rw_txn().map_err(|e| DatabaseError::InitTx(e.into()))?;
371        env.sync(true).map_err(|e| DatabaseError::Commit(e.into()))?;
372        Ok(())
373    }
374
375    fn abort(self) {
376        self.execute_with_close_transaction_metric(TransactionOutcome::Abort, |this| {
377            (drop(this.inner), None)
378        })
379    }
380
381    // Iterate over read only values in database.
382    fn cursor_read<T: Table>(&self) -> Result<Self::Cursor<T>, DatabaseError> {
383        self.new_cursor()
384    }
385
386    /// Iterate over read only values in database.
387    fn cursor_dup_read<T: DupSort>(&self) -> Result<Self::DupCursor<T>, DatabaseError> {
388        self.new_cursor()
389    }
390
391    /// Returns number of entries in the table using cheap DB stats invocation.
392    fn entries<T: Table>(&self) -> Result<usize, DatabaseError> {
393        Ok(self
394            .inner
395            .db_stat_with_dbi(self.get_dbi::<T>()?)
396            .map_err(|e| DatabaseError::Stats(e.into()))?
397            .entries())
398    }
399
400    /// Disables long-lived read transaction safety guarantees, such as backtrace recording and
401    /// timeout.
402    fn disable_long_read_transaction_safety(&mut self) {
403        if let Some(metrics_handler) = self.metrics_handler.as_mut() {
404            metrics_handler.record_backtrace = false;
405        }
406
407        self.inner.disable_timeout();
408    }
409
410    #[cfg(target_os = "linux")]
411    fn prefetch(&self, enabled: bool) -> &Self {
412        self.prefetch.store(enabled, Ordering::Relaxed);
413        self
414    }
415}
416
417#[derive(Clone, Copy)]
418enum PutKind {
419    /// Default kind that inserts a new key-value or overwrites an existed key.
420    Upsert,
421    /// Append the key-value to the end of the table -- fast path when the new
422    /// key is the highest so far, like the latest block number.
423    Append,
424}
425
426impl PutKind {
427    const fn into_operation_and_flags(self) -> (Operation, DatabaseWriteOperation, WriteFlags) {
428        match self {
429            Self::Upsert => {
430                (Operation::PutUpsert, DatabaseWriteOperation::PutUpsert, WriteFlags::UPSERT)
431            }
432            Self::Append => {
433                (Operation::PutAppend, DatabaseWriteOperation::PutAppend, WriteFlags::APPEND)
434            }
435        }
436    }
437}
438
439impl Tx<RW> {
440    /// The inner implementation mapping to `mdbx_put` that supports different
441    /// put kinds like upserting and appending.
442    fn put<T: Table>(
443        &self,
444        kind: PutKind,
445        key: T::Key,
446        value: T::Value,
447    ) -> Result<(), DatabaseError> {
448        let key = key.encode();
449        let value = value.compress();
450        let (operation, write_operation, flags) = kind.into_operation_and_flags();
451        self.execute_with_operation_metric::<T, _>(operation, Some(value.as_ref().len()), |tx| {
452            tx.put(self.get_dbi::<T>()?, key.as_ref(), value, flags).map_err(|e| {
453                DatabaseWriteError {
454                    info: e.into(),
455                    operation: write_operation,
456                    table_name: T::NAME,
457                    key: key.into_vec(),
458                }
459                .into()
460            })
461        })
462    }
463}
464
465impl DbTxMut for Tx<RW> {
466    type CursorMut<T: Table> = Cursor<RW, T>;
467    type DupCursorMut<T: DupSort> = Cursor<RW, T>;
468
469    fn put<T: Table>(&self, key: T::Key, value: T::Value) -> Result<(), DatabaseError> {
470        self.put::<T>(PutKind::Upsert, key, value)
471    }
472
473    fn append<T: Table>(&self, key: T::Key, value: T::Value) -> Result<(), DatabaseError> {
474        self.put::<T>(PutKind::Append, key, value)
475    }
476
477    fn delete<T: Table>(
478        &self,
479        key: T::Key,
480        value: Option<T::Value>,
481    ) -> Result<bool, DatabaseError> {
482        let mut data = None;
483
484        let value = value.map(Compress::compress);
485        if let Some(value) = &value {
486            data = Some(value.as_ref());
487        };
488
489        self.execute_with_operation_metric::<T, _>(Operation::Delete, None, |tx| {
490            tx.del(self.get_dbi::<T>()?, key.encode(), data)
491                .map_err(|e| DatabaseError::Delete(e.into()))
492        })
493    }
494
495    fn clear<T: Table>(&self) -> Result<(), DatabaseError> {
496        self.inner.clear_db(self.get_dbi::<T>()?).map_err(|e| DatabaseError::Delete(e.into()))?;
497
498        Ok(())
499    }
500
501    fn cursor_write<T: Table>(&self) -> Result<Self::CursorMut<T>, DatabaseError> {
502        self.new_cursor()
503    }
504
505    fn cursor_dup_write<T: DupSort>(&self) -> Result<Self::DupCursorMut<T>, DatabaseError> {
506        self.new_cursor()
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use crate::{mdbx::DatabaseArguments, tables, DatabaseEnv, DatabaseEnvKind};
513    use reth_db_api::{database::Database, models::ClientVersion, transaction::DbTx};
514    use reth_libmdbx::MaxReadTransactionDuration;
515    use reth_storage_errors::db::DatabaseError;
516    use std::{sync::atomic::Ordering, thread::sleep, time::Duration};
517    use tempfile::tempdir;
518
519    #[test]
520    fn long_read_transaction_safety_disabled() {
521        const MAX_DURATION: Duration = Duration::from_secs(1);
522
523        let dir = tempdir().unwrap();
524        let args = DatabaseArguments::new(ClientVersion::default())
525            .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Set(
526                MAX_DURATION,
527            )));
528        let db = DatabaseEnv::open(dir.path(), DatabaseEnvKind::RW, args)
529            .unwrap()
530            .with_metrics()
531            .with_disable_long_read_transaction_safety();
532
533        let mut tx = db.tx().unwrap();
534        let metrics_handler = tx.metrics_handler.as_mut().unwrap();
535        metrics_handler.long_transaction_deadline = metrics_handler.start + MAX_DURATION;
536        // Give the `TxnManager` some time to time out the transaction.
537        sleep(MAX_DURATION + Duration::from_millis(100));
538
539        // Transaction has not timed out.
540        assert!(matches!(
541            tx.get::<tables::Transactions>(0).unwrap_err(),
542            DatabaseError::Open(err) if err == reth_libmdbx::Error::NotFound.into()));
543        // Backtrace is not recorded.
544        assert!(!tx.metrics_handler.unwrap().backtrace_recorded.load(Ordering::Relaxed));
545    }
546
547    #[test]
548    fn long_read_transaction_safety_enabled() {
549        const MAX_DURATION: Duration = Duration::from_secs(1);
550
551        let dir = tempdir().unwrap();
552        let args = DatabaseArguments::new(ClientVersion::default())
553            .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Set(
554                MAX_DURATION,
555            )));
556        let db = DatabaseEnv::open(dir.path(), DatabaseEnvKind::RW, args).unwrap().with_metrics();
557
558        let mut tx = db.tx().unwrap();
559        let metrics_handler = tx.metrics_handler.as_mut().unwrap();
560        metrics_handler.long_transaction_deadline = metrics_handler.start + MAX_DURATION;
561        // Give the `TxnManager` some time to time out the transaction.
562        sleep(MAX_DURATION + Duration::from_millis(100));
563
564        // Transaction has timed out.
565        assert!(matches!(
566            tx.get::<tables::Transactions>(0).unwrap_err(),
567            DatabaseError::Open(err) if err == reth_libmdbx::Error::ReadTransactionTimeout.into()));
568        // Backtrace is recorded.
569        assert!(tx.metrics_handler.unwrap().backtrace_recorded.load(Ordering::Relaxed));
570    }
571}