Skip to main content

typed_store/rocks/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3pub mod errors;
4mod options;
5mod rocks_util;
6pub(crate) mod safe_iter;
7
8use crate::memstore::{InMemoryBatch, InMemoryDB};
9use crate::rocks::errors::typed_store_err_from_bcs_err;
10use crate::rocks::errors::typed_store_err_from_rocks_err;
11pub use crate::rocks::options::{
12    DBMapTableConfigMap, DBOptions, ReadWriteOptions, default_db_options, read_size_from_env,
13};
14use crate::rocks::safe_iter::{SafeIter, SafeRevIter};
15#[cfg(tidehunter)]
16use crate::tidehunter_util::{
17    apply_range_bounds, transform_th_iterator, transform_th_key, typed_store_error_from_th_error,
18};
19use crate::util::{
20    be_fix_int_ser, be_fix_int_ser_into, ensure_database_type, iterator_bounds,
21    iterator_bounds_with_range,
22};
23use crate::{DbIterator, StorageType, TypedStoreError};
24use crate::{
25    metrics::{DBMetrics, RocksDBPerfContext, SamplingInterval},
26    traits::{Map, TableSummary},
27};
28use backoff::backoff::Backoff;
29use fastcrypto::hash::{Digest, HashFunction};
30use mysten_common::debug_fatal;
31use mysten_metrics::RegistryID;
32use prometheus::{Histogram, HistogramTimer};
33use rocksdb::properties::num_files_at_level;
34use rocksdb::{
35    AsColumnFamilyRef, ColumnFamilyDescriptor, Error, MultiThreaded, ReadOptions, WriteBatch,
36    properties,
37};
38use rocksdb::{DBPinnableSlice, LiveFile, checkpoint::Checkpoint};
39use serde::{Serialize, de::DeserializeOwned};
40use std::ops::{Bound, Deref};
41use std::{
42    borrow::Borrow,
43    marker::PhantomData,
44    ops::RangeBounds,
45    path::{Path, PathBuf},
46    sync::{Arc, OnceLock},
47    time::Duration,
48};
49use std::{collections::HashSet, ffi::CStr};
50use sui_macros::{fail_point, nondeterministic};
51#[cfg(tidehunter)]
52use tidehunter::{db::Db as TideHunterDb, key_shape::KeySpace};
53use tokio::sync::oneshot;
54use tracing::{debug, error, instrument, warn};
55
56// TODO: remove this after Rust rocksdb has the TOTAL_BLOB_FILES_SIZE property built-in.
57// From https://github.com/facebook/rocksdb/blob/bd80433c73691031ba7baa65c16c63a83aef201a/include/rocksdb/db.h#L1169
58const ROCKSDB_PROPERTY_TOTAL_BLOB_FILES_SIZE: &CStr =
59    unsafe { CStr::from_bytes_with_nul_unchecked("rocksdb.total-blob-file-size\0".as_bytes()) };
60
61static WRITE_SYNC_ENABLED: OnceLock<bool> = OnceLock::new();
62
63fn write_sync_enabled() -> bool {
64    *WRITE_SYNC_ENABLED
65        .get_or_init(|| std::env::var("SUI_DB_SYNC_TO_DISK").is_ok_and(|v| v == "1" || v == "true"))
66}
67
68/// Initialize the write sync setting from config.
69/// Must be called before any database writes occur.
70pub fn init_write_sync(enabled: Option<bool>) {
71    if let Some(value) = enabled {
72        let _ = WRITE_SYNC_ENABLED.set(value);
73    }
74}
75
76#[cfg(test)]
77mod tests;
78
79#[derive(Debug)]
80pub struct RocksDB {
81    pub underlying: rocksdb::DBWithThreadMode<MultiThreaded>,
82}
83
84impl Drop for RocksDB {
85    fn drop(&mut self) {
86        self.underlying.cancel_all_background_work(/* wait */ true);
87    }
88}
89
90#[derive(Clone)]
91pub enum ColumnFamily {
92    Rocks(String),
93    InMemory(String),
94    #[cfg(tidehunter)]
95    TideHunter((KeySpace, Option<Vec<u8>>)),
96}
97
98impl std::fmt::Debug for ColumnFamily {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        match self {
101            ColumnFamily::Rocks(name) => write!(f, "RocksDB cf: {}", name),
102            ColumnFamily::InMemory(name) => write!(f, "InMemory cf: {}", name),
103            #[cfg(tidehunter)]
104            ColumnFamily::TideHunter(_) => write!(f, "TideHunter column family"),
105        }
106    }
107}
108
109impl ColumnFamily {
110    fn rocks_cf<'a>(&self, rocks_db: &'a RocksDB) -> Arc<rocksdb::BoundColumnFamily<'a>> {
111        match &self {
112            ColumnFamily::Rocks(name) => rocks_db
113                .underlying
114                .cf_handle(name)
115                .expect("Map-keying column family should have been checked at DB creation"),
116            _ => unreachable!("invariant is checked by the caller"),
117        }
118    }
119}
120
121pub enum Storage {
122    Rocks(RocksDB),
123    InMemory(InMemoryDB),
124    #[cfg(tidehunter)]
125    TideHunter(Arc<TideHunterDb>),
126}
127
128impl std::fmt::Debug for Storage {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        match self {
131            Storage::Rocks(db) => write!(f, "RocksDB Storage {:?}", db),
132            Storage::InMemory(db) => write!(f, "InMemoryDB Storage {:?}", db),
133            #[cfg(tidehunter)]
134            Storage::TideHunter(_) => write!(f, "TideHunterDB Storage"),
135        }
136    }
137}
138
139#[derive(Debug)]
140pub struct Database {
141    storage: Storage,
142    metric_conf: MetricConf,
143    registry_id: Option<RegistryID>,
144}
145
146impl Drop for Database {
147    fn drop(&mut self) {
148        let metrics = DBMetrics::get();
149        metrics.decrement_num_active_dbs(&self.metric_conf.db_name);
150        if let Some(registry_id) = self.registry_id {
151            metrics.registry_serivce.remove(registry_id);
152        }
153    }
154}
155
156enum GetResult<'a> {
157    Rocks(DBPinnableSlice<'a>),
158    InMemory(Vec<u8>),
159    #[cfg(tidehunter)]
160    TideHunter(tidehunter::minibytes::Bytes),
161}
162
163impl Deref for GetResult<'_> {
164    type Target = [u8];
165    fn deref(&self) -> &[u8] {
166        match self {
167            GetResult::Rocks(d) => d.deref(),
168            GetResult::InMemory(d) => d.deref(),
169            #[cfg(tidehunter)]
170            GetResult::TideHunter(d) => d.deref(),
171        }
172    }
173}
174
175impl Database {
176    pub fn new(storage: Storage, metric_conf: MetricConf, registry_id: Option<RegistryID>) -> Self {
177        DBMetrics::get().increment_num_active_dbs(&metric_conf.db_name);
178        Self {
179            storage,
180            metric_conf,
181            registry_id,
182        }
183    }
184
185    /// Flush all memtables to SST files on disk.
186    pub fn flush(&self) -> Result<(), TypedStoreError> {
187        match &self.storage {
188            Storage::Rocks(rocks_db) => rocks_db.underlying.flush().map_err(|e| {
189                TypedStoreError::RocksDBError(format!("Failed to flush database: {}", e))
190            }),
191            Storage::InMemory(_) => {
192                // InMemory databases don't need flushing
193                Ok(())
194            }
195            #[cfg(tidehunter)]
196            Storage::TideHunter(_) => {
197                // TideHunter doesn't support an explicit flush.
198                Ok(())
199            }
200        }
201    }
202
203    fn get<K: AsRef<[u8]>>(
204        &self,
205        cf: &ColumnFamily,
206        key: K,
207        readopts: &ReadOptions,
208    ) -> Result<Option<GetResult<'_>>, TypedStoreError> {
209        match (&self.storage, cf) {
210            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => Ok(db
211                .underlying
212                .get_pinned_cf_opt(&cf.rocks_cf(db), key, readopts)
213                .map_err(typed_store_err_from_rocks_err)?
214                .map(GetResult::Rocks)),
215            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => {
216                Ok(db.get(cf_name, key).map(GetResult::InMemory))
217            }
218            #[cfg(tidehunter)]
219            (Storage::TideHunter(db), ColumnFamily::TideHunter((ks, prefix))) => Ok(db
220                .get(*ks, &transform_th_key(key.as_ref(), prefix))
221                .map_err(typed_store_error_from_th_error)?
222                .map(GetResult::TideHunter)),
223
224            _ => Err(TypedStoreError::RocksDBError(
225                "typed store invariant violation".to_string(),
226            )),
227        }
228    }
229
230    /// Returns whether `key` exists, without materializing the value. On tidehunter
231    /// this uses the native `exists` (an index/bloom presence check), which avoids
232    /// the value-record read that `get` performs and is therefore much cheaper.
233    fn contains(
234        &self,
235        cf: &ColumnFamily,
236        key: &[u8],
237        readopts: &ReadOptions,
238    ) -> Result<bool, TypedStoreError> {
239        match (&self.storage, cf) {
240            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => {
241                let rocks_cf = cf.rocks_cf(db);
242                // `key_may_exist_cf_opt` can return false positives but never false
243                // negatives, so it short-circuits the common absent case before the
244                // real point lookup.
245                Ok(db.underlying.key_may_exist_cf_opt(&rocks_cf, key, readopts)
246                    && db
247                        .underlying
248                        .get_pinned_cf_opt(&rocks_cf, key, readopts)
249                        .map_err(typed_store_err_from_rocks_err)?
250                        .is_some())
251            }
252            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => {
253                Ok(db.get(cf_name, key).is_some())
254            }
255            #[cfg(tidehunter)]
256            (Storage::TideHunter(db), ColumnFamily::TideHunter((ks, prefix))) => db
257                .exists(*ks, &transform_th_key(key, prefix))
258                .map_err(typed_store_error_from_th_error),
259            _ => Err(TypedStoreError::RocksDBError(
260                "typed store invariant violation".to_string(),
261            )),
262        }
263    }
264
265    /// Multi-key variant of [`Self::contains`]. On tidehunter each key uses the
266    /// native `exists` presence check, avoiding the value-record reads that
267    /// `multi_get` performs. Other backends answer via `multi_get`.
268    fn multi_contains<I, K>(
269        &self,
270        cf: &ColumnFamily,
271        keys: I,
272        readopts: &ReadOptions,
273    ) -> Result<Vec<bool>, TypedStoreError>
274    where
275        I: IntoIterator<Item = K>,
276        K: AsRef<[u8]>,
277    {
278        match (&self.storage, cf) {
279            #[cfg(tidehunter)]
280            (Storage::TideHunter(db), ColumnFamily::TideHunter((ks, prefix))) => keys
281                .into_iter()
282                .map(|k| {
283                    db.exists(*ks, &transform_th_key(k.as_ref(), prefix))
284                        .map_err(typed_store_error_from_th_error)
285                })
286                .collect(),
287            _ => self
288                .multi_get(cf, keys, readopts)
289                .into_iter()
290                .map(|r| r.map(|v| v.is_some()))
291                .collect(),
292        }
293    }
294
295    fn multi_get<I, K>(
296        &self,
297        cf: &ColumnFamily,
298        keys: I,
299        readopts: &ReadOptions,
300    ) -> Vec<Result<Option<GetResult<'_>>, TypedStoreError>>
301    where
302        I: IntoIterator<Item = K>,
303        K: AsRef<[u8]>,
304    {
305        match (&self.storage, cf) {
306            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => {
307                let keys_vec: Vec<K> = keys.into_iter().collect();
308                let res = db.underlying.batched_multi_get_cf_opt(
309                    &cf.rocks_cf(db),
310                    keys_vec.iter(),
311                    /* sorted_input */ false,
312                    readopts,
313                );
314                res.into_iter()
315                    .map(|r| {
316                        r.map_err(typed_store_err_from_rocks_err)
317                            .map(|item| item.map(GetResult::Rocks))
318                    })
319                    .collect()
320            }
321            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => db
322                .multi_get(cf_name, keys)
323                .into_iter()
324                .map(|r| Ok(r.map(GetResult::InMemory)))
325                .collect(),
326            #[cfg(tidehunter)]
327            (Storage::TideHunter(db), ColumnFamily::TideHunter((ks, prefix))) => keys
328                .into_iter()
329                .map(|k| {
330                    db.get(*ks, &transform_th_key(k.as_ref(), prefix))
331                        .map_err(typed_store_error_from_th_error)
332                        .map(|item| item.map(|bytes| GetResult::TideHunter(bytes.into_owned())))
333                })
334                .collect(),
335            _ => unreachable!("typed store invariant violation"),
336        }
337    }
338
339    pub fn drop_cf(&self, name: &str) -> Result<(), rocksdb::Error> {
340        match &self.storage {
341            Storage::Rocks(db) => db.underlying.drop_cf(name),
342            Storage::InMemory(db) => {
343                db.drop_cf(name);
344                Ok(())
345            }
346            #[cfg(tidehunter)]
347            Storage::TideHunter(_) => {
348                unimplemented!("TideHunter: deletion of column family on a fly not implemented")
349            }
350        }
351    }
352
353    pub fn delete_file_in_range<K: AsRef<[u8]>>(
354        &self,
355        cf: &impl AsColumnFamilyRef,
356        from: K,
357        to: K,
358    ) -> Result<(), rocksdb::Error> {
359        match &self.storage {
360            Storage::Rocks(rocks) => rocks.underlying.delete_file_in_range_cf(cf, from, to),
361            _ => unimplemented!("delete_file_in_range is only supported for rocksdb backend"),
362        }
363    }
364
365    fn delete_cf<K: AsRef<[u8]>>(&self, cf: &ColumnFamily, key: K) -> Result<(), TypedStoreError> {
366        fail_point!("delete-cf-before");
367        let ret = match (&self.storage, cf) {
368            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => db
369                .underlying
370                .delete_cf(&cf.rocks_cf(db), key)
371                .map_err(typed_store_err_from_rocks_err),
372            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => {
373                db.delete(cf_name, key.as_ref());
374                Ok(())
375            }
376            #[cfg(tidehunter)]
377            (Storage::TideHunter(db), ColumnFamily::TideHunter((ks, prefix))) => db
378                .remove(*ks, transform_th_key(key.as_ref(), prefix))
379                .map_err(typed_store_error_from_th_error),
380            _ => Err(TypedStoreError::RocksDBError(
381                "typed store invariant violation".to_string(),
382            )),
383        };
384        fail_point!("delete-cf-after");
385        #[allow(clippy::let_and_return)]
386        ret
387    }
388
389    pub fn path_for_pruning(&self) -> &Path {
390        match &self.storage {
391            Storage::Rocks(rocks) => rocks.underlying.path(),
392            _ => unimplemented!("method is only supported for rocksdb backend"),
393        }
394    }
395
396    fn put_cf(
397        &self,
398        cf: &ColumnFamily,
399        key: Vec<u8>,
400        value: Vec<u8>,
401    ) -> Result<(), TypedStoreError> {
402        fail_point!("put-cf-before");
403        let ret = match (&self.storage, cf) {
404            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => db
405                .underlying
406                .put_cf(&cf.rocks_cf(db), key, value)
407                .map_err(typed_store_err_from_rocks_err),
408            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => {
409                db.put(cf_name, key, value);
410                Ok(())
411            }
412            #[cfg(tidehunter)]
413            (Storage::TideHunter(db), ColumnFamily::TideHunter((ks, prefix))) => db
414                .insert(*ks, transform_th_key(&key, prefix), value)
415                .map_err(typed_store_error_from_th_error),
416            _ => Err(TypedStoreError::RocksDBError(
417                "typed store invariant violation".to_string(),
418            )),
419        };
420        fail_point!("put-cf-after");
421        #[allow(clippy::let_and_return)]
422        ret
423    }
424
425    pub(crate) fn write_opt_internal(
426        &self,
427        batch: StorageWriteBatch,
428        write_options: &rocksdb::WriteOptions,
429    ) -> Result<(), TypedStoreError> {
430        fail_point!("batch-write-before");
431        let ret = match (&self.storage, batch) {
432            (Storage::Rocks(rocks), StorageWriteBatch::Rocks(batch)) => rocks
433                .underlying
434                .write_opt(batch, write_options)
435                .map_err(typed_store_err_from_rocks_err),
436            (Storage::InMemory(db), StorageWriteBatch::InMemory(batch)) => {
437                // InMemory doesn't support write options
438                db.write(batch);
439                Ok(())
440            }
441            #[cfg(tidehunter)]
442            (Storage::TideHunter(_db), StorageWriteBatch::TideHunter(batch)) => {
443                // TideHunter doesn't support write options
444                batch.commit().map_err(typed_store_error_from_th_error)
445            }
446            _ => Err(TypedStoreError::RocksDBError(
447                "using invalid batch type for the database".to_string(),
448            )),
449        };
450        fail_point!("batch-write-after");
451        #[allow(clippy::let_and_return)]
452        ret
453    }
454
455    #[cfg(tidehunter)]
456    pub fn start_relocation(&self) -> anyhow::Result<()> {
457        if let Storage::TideHunter(db) = &self.storage {
458            db.start_relocation()?;
459        }
460        Ok(())
461    }
462
463    #[cfg(tidehunter)]
464    pub fn force_rebuild_control_region(&self) -> anyhow::Result<()> {
465        if let Storage::TideHunter(db) = &self.storage {
466            db.force_rebuild_control_region()
467                .map_err(|e| anyhow::anyhow!("{:?}", e))?;
468        }
469        Ok(())
470    }
471
472    /// Wait for tidehunter background threads to finish.
473    ///
474    /// Consumes the `Arc<Database>`. Caller must ensure no other clones of this
475    /// `Arc<Database>` (e.g. via `DBMap::db`) are alive — otherwise the inner
476    /// `Arc<TideHunterDb>` strong count will not reach zero and the wait will
477    /// poll until it panics.
478    #[cfg(tidehunter)]
479    pub fn wait_for_tidehunter_background_threads(self: Arc<Self>) {
480        let strong = Arc::strong_count(&self);
481        if strong != 1 {
482            println!(
483                "WARNING: wait_for_tidehunter_background_threads called with Arc<Database> strong_count={} (expected 1); other clones will keep the inner tidehunter Db alive and the wait may panic on timeout",
484                strong,
485            );
486        }
487        let Storage::TideHunter(th_arc) = &self.storage else {
488            return;
489        };
490        let th_arc = th_arc.clone();
491        drop(self);
492        th_arc.wait_for_background_threads_to_finish();
493    }
494
495    #[cfg(tidehunter)]
496    pub fn drop_cells_in_range(
497        &self,
498        ks: KeySpace,
499        from_inclusive: &[u8],
500        to_inclusive: &[u8],
501    ) -> anyhow::Result<()> {
502        if let Storage::TideHunter(db) = &self.storage {
503            db.drop_cells_in_range(ks, from_inclusive, to_inclusive)
504                .map_err(|e| anyhow::anyhow!("{:?}", e))?;
505        } else {
506            panic!("drop_cells_in_range called on non-TideHunter storage");
507        }
508        Ok(())
509    }
510
511    pub fn compact_range_cf<K: AsRef<[u8]>>(
512        &self,
513        cf_name: &str,
514        start: Option<K>,
515        end: Option<K>,
516    ) {
517        if let Storage::Rocks(rocksdb) = &self.storage {
518            rocksdb
519                .underlying
520                .compact_range_cf(&rocks_cf(rocksdb, cf_name), start, end);
521        }
522    }
523
524    pub fn checkpoint(&self, path: &Path) -> Result<(), TypedStoreError> {
525        // TODO: implement for other storage types
526        if let Storage::Rocks(rocks) = &self.storage {
527            let checkpoint =
528                Checkpoint::new(&rocks.underlying).map_err(typed_store_err_from_rocks_err)?;
529            checkpoint
530                .create_checkpoint(path)
531                .map_err(|e| TypedStoreError::RocksDBError(e.to_string()))?;
532        }
533        Ok(())
534    }
535
536    pub fn get_sampling_interval(&self) -> SamplingInterval {
537        self.metric_conf.read_sample_interval.new_from_self()
538    }
539
540    pub fn multiget_sampling_interval(&self) -> SamplingInterval {
541        self.metric_conf.read_sample_interval.new_from_self()
542    }
543
544    pub fn write_sampling_interval(&self) -> SamplingInterval {
545        self.metric_conf.write_sample_interval.new_from_self()
546    }
547
548    pub fn iter_sampling_interval(&self) -> SamplingInterval {
549        self.metric_conf.iter_sample_interval.new_from_self()
550    }
551
552    fn db_name(&self) -> String {
553        let name = &self.metric_conf.db_name;
554        if name.is_empty() {
555            "default".to_string()
556        } else {
557            name.clone()
558        }
559    }
560
561    pub fn live_files(&self) -> Result<Vec<LiveFile>, Error> {
562        match &self.storage {
563            Storage::Rocks(rocks) => rocks.underlying.live_files(),
564            _ => Ok(vec![]),
565        }
566    }
567}
568
569fn rocks_cf<'a>(rocks_db: &'a RocksDB, cf_name: &str) -> Arc<rocksdb::BoundColumnFamily<'a>> {
570    rocks_db
571        .underlying
572        .cf_handle(cf_name)
573        .expect("Map-keying column family should have been checked at DB creation")
574}
575
576fn rocks_cf_from_db<'a>(
577    db: &'a Database,
578    cf_name: &str,
579) -> Result<Arc<rocksdb::BoundColumnFamily<'a>>, TypedStoreError> {
580    match &db.storage {
581        Storage::Rocks(rocksdb) => Ok(rocksdb
582            .underlying
583            .cf_handle(cf_name)
584            .expect("Map-keying column family should have been checked at DB creation")),
585        _ => Err(TypedStoreError::RocksDBError(
586            "using invalid batch type for the database".to_string(),
587        )),
588    }
589}
590
591#[derive(Debug, Default)]
592pub struct MetricConf {
593    pub db_name: String,
594    pub read_sample_interval: SamplingInterval,
595    pub write_sample_interval: SamplingInterval,
596    pub iter_sample_interval: SamplingInterval,
597    /// When true and the database is opened with the tidehunter backend, each
598    /// committed `WriteBatch` is written as a single lz4-compressed WAL entry.
599    pub enable_th_batch_compression: bool,
600}
601
602impl MetricConf {
603    pub fn new(db_name: &str) -> Self {
604        if db_name.is_empty() {
605            error!("A meaningful db name should be used for metrics reporting.")
606        }
607        Self {
608            db_name: db_name.to_string(),
609            read_sample_interval: SamplingInterval::default(),
610            write_sample_interval: SamplingInterval::default(),
611            iter_sample_interval: SamplingInterval::default(),
612            enable_th_batch_compression: false,
613        }
614    }
615
616    pub fn with_sampling(mut self, read_interval: SamplingInterval) -> Self {
617        self.read_sample_interval = read_interval;
618        self
619    }
620
621    pub fn with_th_batch_compression(mut self) -> Self {
622        self.enable_th_batch_compression = true;
623        self
624    }
625}
626const CF_METRICS_REPORT_PERIOD_SECS: u64 = 30;
627const METRICS_ERROR: i64 = -1;
628
629/// An interface to a rocksDB database, keyed by a columnfamily
630#[derive(Clone, Debug)]
631pub struct DBMap<K, V> {
632    pub db: Arc<Database>,
633    _phantom: PhantomData<fn(K) -> V>,
634    column_family: ColumnFamily,
635    // the column family under which the map is stored
636    cf: String,
637    pub opts: ReadWriteOptions,
638    db_metrics: Arc<DBMetrics>,
639    get_sample_interval: SamplingInterval,
640    multiget_sample_interval: SamplingInterval,
641    write_sample_interval: SamplingInterval,
642    iter_sample_interval: SamplingInterval,
643    _metrics_task_cancel_handle: Arc<oneshot::Sender<()>>,
644}
645
646unsafe impl<K: Send, V: Send> Send for DBMap<K, V> {}
647
648// The functions below do not depend on `DBMap`'s type parameters. They are kept out of its impl
649// so they are compiled once instead of once per table type.
650
651fn spawn_cf_metrics_task(
652    db: &Arc<Database>,
653    cf: &str,
654    db_metrics: &Arc<DBMetrics>,
655    is_deprecated: bool,
656) -> oneshot::Sender<()> {
657    let db_cloned = Arc::downgrade(db);
658    let db_metrics = db_metrics.clone();
659    let cf = cf.to_string();
660
661    let (sender, mut recv) = tokio::sync::oneshot::channel();
662    if !is_deprecated && matches!(db.storage, Storage::Rocks(_)) {
663        tokio::task::spawn(async move {
664            let mut interval =
665                tokio::time::interval(Duration::from_secs(CF_METRICS_REPORT_PERIOD_SECS));
666            loop {
667                tokio::select! {
668                    _ = interval.tick() => {
669                        if let Some(db) = db_cloned.upgrade() {
670                            let cf = cf.clone();
671                            let db_metrics = db_metrics.clone();
672                            if let Err(e) = tokio::task::spawn_blocking(move || {
673                                report_rocksdb_metrics(&db, &cf, &db_metrics);
674                            }).await {
675                                error!("Failed to log metrics with error: {}", e);
676                            }
677                        }
678                    }
679                    _ = &mut recv => break,
680                }
681            }
682            debug!("Returning the cf metric logging task for DBMap: {}", &cf);
683        });
684    }
685    sender
686}
687
688fn get_rocksdb_int_property(
689    rocksdb: &RocksDB,
690    cf: &impl AsColumnFamilyRef,
691    property_name: &std::ffi::CStr,
692) -> Result<i64, TypedStoreError> {
693    match rocksdb.underlying.property_int_value_cf(cf, property_name) {
694        Ok(Some(value)) => Ok(value.min(i64::MAX as u64).try_into().unwrap_or_default()),
695        Ok(None) => Ok(0),
696        Err(e) => Err(TypedStoreError::RocksDBError(e.into_string())),
697    }
698}
699
700fn report_rocksdb_metrics(database: &Arc<Database>, cf_name: &str, db_metrics: &Arc<DBMetrics>) {
701    let Storage::Rocks(rocksdb) = &database.storage else {
702        return;
703    };
704
705    let Some(cf) = rocksdb.underlying.cf_handle(cf_name) else {
706        tracing::warn!(
707            "unable to report metrics for cf {cf_name:?} in db {:?}",
708            database.db_name()
709        );
710        return;
711    };
712
713    db_metrics
714        .cf_metrics
715        .rocksdb_total_sst_files_size
716        .with_label_values(&[cf_name])
717        .set(
718            get_rocksdb_int_property(rocksdb, &cf, properties::TOTAL_SST_FILES_SIZE)
719                .unwrap_or(METRICS_ERROR),
720        );
721    db_metrics
722        .cf_metrics
723        .rocksdb_total_blob_files_size
724        .with_label_values(&[cf_name])
725        .set(
726            get_rocksdb_int_property(rocksdb, &cf, ROCKSDB_PROPERTY_TOTAL_BLOB_FILES_SIZE)
727                .unwrap_or(METRICS_ERROR),
728        );
729    // 7 is the default number of levels in RocksDB. If we ever change the number of levels using `set_num_levels`,
730    // we need to update here as well. Note that there isn't an API to query the DB to get the number of levels (yet).
731    let total_num_files: i64 = (0..=6)
732        .map(|level| {
733            get_rocksdb_int_property(rocksdb, &cf, &num_files_at_level(level))
734                .unwrap_or(METRICS_ERROR)
735        })
736        .sum();
737    db_metrics
738        .cf_metrics
739        .rocksdb_total_num_files
740        .with_label_values(&[cf_name])
741        .set(total_num_files);
742    db_metrics
743        .cf_metrics
744        .rocksdb_num_level0_files
745        .with_label_values(&[cf_name])
746        .set(
747            get_rocksdb_int_property(rocksdb, &cf, &num_files_at_level(0)).unwrap_or(METRICS_ERROR),
748        );
749    db_metrics
750        .cf_metrics
751        .rocksdb_current_size_active_mem_tables
752        .with_label_values(&[cf_name])
753        .set(
754            get_rocksdb_int_property(rocksdb, &cf, properties::CUR_SIZE_ACTIVE_MEM_TABLE)
755                .unwrap_or(METRICS_ERROR),
756        );
757    db_metrics
758        .cf_metrics
759        .rocksdb_size_all_mem_tables
760        .with_label_values(&[cf_name])
761        .set(
762            get_rocksdb_int_property(rocksdb, &cf, properties::SIZE_ALL_MEM_TABLES)
763                .unwrap_or(METRICS_ERROR),
764        );
765    db_metrics
766        .cf_metrics
767        .rocksdb_num_snapshots
768        .with_label_values(&[cf_name])
769        .set(
770            get_rocksdb_int_property(rocksdb, &cf, properties::NUM_SNAPSHOTS)
771                .unwrap_or(METRICS_ERROR),
772        );
773    db_metrics
774        .cf_metrics
775        .rocksdb_oldest_snapshot_time
776        .with_label_values(&[cf_name])
777        .set(
778            get_rocksdb_int_property(rocksdb, &cf, properties::OLDEST_SNAPSHOT_TIME)
779                .unwrap_or(METRICS_ERROR),
780        );
781    db_metrics
782        .cf_metrics
783        .rocksdb_actual_delayed_write_rate
784        .with_label_values(&[cf_name])
785        .set(
786            get_rocksdb_int_property(rocksdb, &cf, properties::ACTUAL_DELAYED_WRITE_RATE)
787                .unwrap_or(METRICS_ERROR),
788        );
789    db_metrics
790        .cf_metrics
791        .rocksdb_is_write_stopped
792        .with_label_values(&[cf_name])
793        .set(
794            get_rocksdb_int_property(rocksdb, &cf, properties::IS_WRITE_STOPPED)
795                .unwrap_or(METRICS_ERROR),
796        );
797    db_metrics
798        .cf_metrics
799        .rocksdb_block_cache_capacity
800        .with_label_values(&[cf_name])
801        .set(
802            get_rocksdb_int_property(rocksdb, &cf, properties::BLOCK_CACHE_CAPACITY)
803                .unwrap_or(METRICS_ERROR),
804        );
805    db_metrics
806        .cf_metrics
807        .rocksdb_block_cache_usage
808        .with_label_values(&[cf_name])
809        .set(
810            get_rocksdb_int_property(rocksdb, &cf, properties::BLOCK_CACHE_USAGE)
811                .unwrap_or(METRICS_ERROR),
812        );
813    db_metrics
814        .cf_metrics
815        .rocksdb_block_cache_pinned_usage
816        .with_label_values(&[cf_name])
817        .set(
818            get_rocksdb_int_property(rocksdb, &cf, properties::BLOCK_CACHE_PINNED_USAGE)
819                .unwrap_or(METRICS_ERROR),
820        );
821    db_metrics
822        .cf_metrics
823        .rocksdb_estimate_table_readers_mem
824        .with_label_values(&[cf_name])
825        .set(
826            get_rocksdb_int_property(rocksdb, &cf, properties::ESTIMATE_TABLE_READERS_MEM)
827                .unwrap_or(METRICS_ERROR),
828        );
829    db_metrics
830        .cf_metrics
831        .rocksdb_estimated_num_keys
832        .with_label_values(&[cf_name])
833        .set(
834            get_rocksdb_int_property(rocksdb, &cf, properties::ESTIMATE_NUM_KEYS)
835                .unwrap_or(METRICS_ERROR),
836        );
837    db_metrics
838        .cf_metrics
839        .rocksdb_num_immutable_mem_tables
840        .with_label_values(&[cf_name])
841        .set(
842            get_rocksdb_int_property(rocksdb, &cf, properties::NUM_IMMUTABLE_MEM_TABLE)
843                .unwrap_or(METRICS_ERROR),
844        );
845    db_metrics
846        .cf_metrics
847        .rocksdb_mem_table_flush_pending
848        .with_label_values(&[cf_name])
849        .set(
850            get_rocksdb_int_property(rocksdb, &cf, properties::MEM_TABLE_FLUSH_PENDING)
851                .unwrap_or(METRICS_ERROR),
852        );
853    db_metrics
854        .cf_metrics
855        .rocksdb_compaction_pending
856        .with_label_values(&[cf_name])
857        .set(
858            get_rocksdb_int_property(rocksdb, &cf, properties::COMPACTION_PENDING)
859                .unwrap_or(METRICS_ERROR),
860        );
861    db_metrics
862        .cf_metrics
863        .rocksdb_estimate_pending_compaction_bytes
864        .with_label_values(&[cf_name])
865        .set(
866            get_rocksdb_int_property(rocksdb, &cf, properties::ESTIMATE_PENDING_COMPACTION_BYTES)
867                .unwrap_or(METRICS_ERROR),
868        );
869    db_metrics
870        .cf_metrics
871        .rocksdb_num_running_compactions
872        .with_label_values(&[cf_name])
873        .set(
874            get_rocksdb_int_property(rocksdb, &cf, properties::NUM_RUNNING_COMPACTIONS)
875                .unwrap_or(METRICS_ERROR),
876        );
877    db_metrics
878        .cf_metrics
879        .rocksdb_num_running_flushes
880        .with_label_values(&[cf_name])
881        .set(
882            get_rocksdb_int_property(rocksdb, &cf, properties::NUM_RUNNING_FLUSHES)
883                .unwrap_or(METRICS_ERROR),
884        );
885    db_metrics
886        .cf_metrics
887        .rocksdb_estimate_oldest_key_time
888        .with_label_values(&[cf_name])
889        .set(
890            get_rocksdb_int_property(rocksdb, &cf, properties::ESTIMATE_OLDEST_KEY_TIME)
891                .unwrap_or(METRICS_ERROR),
892        );
893    db_metrics
894        .cf_metrics
895        .rocksdb_background_errors
896        .with_label_values(&[cf_name])
897        .set(
898            get_rocksdb_int_property(rocksdb, &cf, properties::BACKGROUND_ERRORS)
899                .unwrap_or(METRICS_ERROR),
900        );
901    db_metrics
902        .cf_metrics
903        .rocksdb_base_level
904        .with_label_values(&[cf_name])
905        .set(
906            get_rocksdb_int_property(rocksdb, &cf, properties::BASE_LEVEL).unwrap_or(METRICS_ERROR),
907        );
908}
909
910fn try_catch_up_with_primary(db: &Database) -> Result<(), TypedStoreError> {
911    if let Storage::Rocks(rocks) = &db.storage {
912        rocks
913            .underlying
914            .try_catch_up_with_primary()
915            .map_err(typed_store_err_from_rocks_err)?;
916    }
917    Ok(())
918}
919
920/// Reads the raw value for `key_buf`, recording read metrics.
921fn get_raw<'a>(
922    db: &'a Database,
923    column_family: &ColumnFamily,
924    cf: &str,
925    db_metrics: &DBMetrics,
926    get_sample_interval: &SamplingInterval,
927    opts: &ReadWriteOptions,
928    key_buf: &[u8],
929) -> Result<Option<GetResult<'a>>, TypedStoreError> {
930    let perf_ctx = if get_sample_interval.sample() {
931        Some(RocksDBPerfContext)
932    } else {
933        None
934    };
935    let res = db.get(column_family, key_buf, &opts.readopts())?;
936    db_metrics
937        .op_metrics
938        .rocksdb_get_bytes
939        .with_label_values(&[cf])
940        .observe(res.as_ref().map_or(0.0, |v| v.len() as f64));
941    if perf_ctx.is_some() {
942        db_metrics.read_perf_ctx_metrics.report_metrics(cf);
943    }
944    Ok(res)
945}
946
947#[cold]
948#[inline(never)]
949fn report_value_deserialization_error(
950    cf_name: &str,
951    key_buf: &[u8],
952    data: &[u8],
953    error: &TypedStoreError,
954) {
955    let key_hash = default_hash(key_buf);
956    let value_hash = default_hash(data);
957    debug_fatal!(
958        "Failed to deserialize value from DB table {:?}, key_hash: {:?}, value_hash: {:?}, error: {:?}",
959        cf_name,
960        key_hash,
961        value_hash,
962        error
963    );
964}
965
966impl DBMap<(), ()> {
967    // Constructing through the untyped map compiles the constructor once instead of once per
968    // table type.
969    fn new_untyped(
970        db: Arc<Database>,
971        opts: &ReadWriteOptions,
972        opt_cf: &str,
973        column_family: ColumnFamily,
974        is_deprecated: bool,
975    ) -> Self {
976        let db_metrics = DBMetrics::get();
977        let sender = spawn_cf_metrics_task(&db, opt_cf, db_metrics, is_deprecated);
978        DBMap {
979            db: db.clone(),
980            opts: opts.clone(),
981            _phantom: PhantomData,
982            column_family,
983            cf: opt_cf.to_string(),
984            db_metrics: db_metrics.clone(),
985            _metrics_task_cancel_handle: Arc::new(sender),
986            get_sample_interval: db.get_sampling_interval(),
987            multiget_sample_interval: db.multiget_sampling_interval(),
988            write_sample_interval: db.write_sampling_interval(),
989            iter_sample_interval: db.iter_sampling_interval(),
990        }
991    }
992
993    #[instrument(name = "reopen", level = "debug", skip(db), err)]
994    fn reopen_untyped(
995        db: &Arc<Database>,
996        opt_cf: Option<&str>,
997        rw_options: &ReadWriteOptions,
998        is_deprecated: bool,
999    ) -> Result<Self, TypedStoreError> {
1000        let cf_key = opt_cf
1001            .unwrap_or(rocksdb::DEFAULT_COLUMN_FAMILY_NAME)
1002            .to_owned();
1003        Ok(DBMap::new_untyped(
1004            db.clone(),
1005            rw_options,
1006            &cf_key,
1007            ColumnFamily::Rocks(cf_key.to_string()),
1008            is_deprecated,
1009        ))
1010    }
1011
1012    fn with_types<K, V>(self) -> DBMap<K, V> {
1013        let DBMap {
1014            db,
1015            _phantom,
1016            column_family,
1017            cf,
1018            opts,
1019            db_metrics,
1020            get_sample_interval,
1021            multiget_sample_interval,
1022            write_sample_interval,
1023            iter_sample_interval,
1024            _metrics_task_cancel_handle,
1025        } = self;
1026        DBMap {
1027            db,
1028            _phantom: PhantomData,
1029            column_family,
1030            cf,
1031            opts,
1032            db_metrics,
1033            get_sample_interval,
1034            multiget_sample_interval,
1035            write_sample_interval,
1036            iter_sample_interval,
1037            _metrics_task_cancel_handle,
1038        }
1039    }
1040}
1041
1042impl<K, V> DBMap<K, V> {
1043    /// Reopens an open database as a typed map operating under a specific column family.
1044    /// if no column family is passed, the default column family is used.
1045    pub fn reopen(
1046        db: &Arc<Database>,
1047        opt_cf: Option<&str>,
1048        rw_options: &ReadWriteOptions,
1049        is_deprecated: bool,
1050    ) -> Result<Self, TypedStoreError> {
1051        DBMap::reopen_untyped(db, opt_cf, rw_options, is_deprecated).map(DBMap::with_types)
1052    }
1053
1054    #[cfg(tidehunter)]
1055    pub fn reopen_th(
1056        db: Arc<Database>,
1057        cf_name: &str,
1058        ks: KeySpace,
1059        prefix: Option<Vec<u8>>,
1060    ) -> Self {
1061        DBMap::new_untyped(
1062            db,
1063            &ReadWriteOptions::default(),
1064            cf_name,
1065            ColumnFamily::TideHunter((ks, prefix.clone())),
1066            false,
1067        )
1068        .with_types()
1069    }
1070
1071    pub fn cf_name(&self) -> &str {
1072        &self.cf
1073    }
1074
1075    pub fn batch(&self) -> DBBatch {
1076        let batch = match &self.db.storage {
1077            Storage::Rocks(_) => StorageWriteBatch::Rocks(WriteBatch::default()),
1078            Storage::InMemory(_) => StorageWriteBatch::InMemory(InMemoryBatch::default()),
1079            #[cfg(tidehunter)]
1080            Storage::TideHunter(db) => StorageWriteBatch::TideHunter(db.write_batch()),
1081        };
1082        DBBatch::new(
1083            &self.db,
1084            batch,
1085            &self.db_metrics,
1086            &self.write_sample_interval,
1087        )
1088    }
1089
1090    pub fn flush(&self) -> Result<(), TypedStoreError> {
1091        self.db.flush()
1092    }
1093
1094    pub fn compact_range<J: Serialize>(&self, start: &J, end: &J) -> Result<(), TypedStoreError> {
1095        let from_buf = be_fix_int_ser(start);
1096        let to_buf = be_fix_int_ser(end);
1097        self.db
1098            .compact_range_cf(&self.cf, Some(from_buf), Some(to_buf));
1099        Ok(())
1100    }
1101
1102    pub fn compact_range_raw(
1103        &self,
1104        cf_name: &str,
1105        start: Vec<u8>,
1106        end: Vec<u8>,
1107    ) -> Result<(), TypedStoreError> {
1108        self.db.compact_range_cf(cf_name, Some(start), Some(end));
1109        Ok(())
1110    }
1111
1112    #[cfg(tidehunter)]
1113    pub fn drop_cells_in_range<J: Serialize>(
1114        &self,
1115        from_inclusive: &J,
1116        to_inclusive: &J,
1117    ) -> Result<(), TypedStoreError>
1118    where
1119        K: Serialize,
1120    {
1121        let from_buf = be_fix_int_ser(from_inclusive);
1122        let to_buf = be_fix_int_ser(to_inclusive);
1123        if let ColumnFamily::TideHunter((ks, _)) = &self.column_family {
1124            self.db
1125                .drop_cells_in_range(*ks, &from_buf, &to_buf)
1126                .map_err(|e| TypedStoreError::RocksDBError(e.to_string()))?;
1127        }
1128        Ok(())
1129    }
1130
1131    #[cfg(tidehunter)]
1132    pub fn drop_cells_in_range_raw(
1133        &self,
1134        from_inclusive: &[u8],
1135        to_inclusive: &[u8],
1136    ) -> Result<(), TypedStoreError> {
1137        if let ColumnFamily::TideHunter((ks, _)) = &self.column_family {
1138            self.db
1139                .drop_cells_in_range(*ks, from_inclusive, to_inclusive)
1140                .map_err(|e| TypedStoreError::RocksDBError(e.to_string()))?;
1141        }
1142        Ok(())
1143    }
1144
1145    /// Returns a vector of raw values corresponding to the keys provided.
1146    fn multi_get_pinned<J>(
1147        &self,
1148        keys: impl IntoIterator<Item = J>,
1149    ) -> Result<Vec<Option<GetResult<'_>>>, TypedStoreError>
1150    where
1151        J: Borrow<K>,
1152        K: Serialize,
1153    {
1154        let _timer = self
1155            .db_metrics
1156            .op_metrics
1157            .rocksdb_multiget_latency_seconds
1158            .with_label_values(&[&self.cf])
1159            .start_timer();
1160        let perf_ctx = if self.multiget_sample_interval.sample() {
1161            Some(RocksDBPerfContext)
1162        } else {
1163            None
1164        };
1165        let keys_bytes = keys.into_iter().map(|k| be_fix_int_ser(k.borrow()));
1166        let results: Result<Vec<_>, TypedStoreError> = self
1167            .db
1168            .multi_get(&self.column_family, keys_bytes, &self.opts.readopts())
1169            .into_iter()
1170            .collect();
1171        let entries = results?;
1172        let entry_size = entries
1173            .iter()
1174            .flatten()
1175            .map(|entry| entry.len())
1176            .sum::<usize>();
1177        self.db_metrics
1178            .op_metrics
1179            .rocksdb_multiget_bytes
1180            .with_label_values(&[&self.cf])
1181            .observe(entry_size as f64);
1182        if perf_ctx.is_some() {
1183            self.db_metrics
1184                .read_perf_ctx_metrics
1185                .report_metrics(&self.cf);
1186        }
1187        Ok(entries)
1188    }
1189
1190    pub fn checkpoint_db(&self, path: &Path) -> Result<(), TypedStoreError> {
1191        self.db.checkpoint(path)
1192    }
1193
1194    pub fn table_summary(&self) -> eyre::Result<TableSummary>
1195    where
1196        K: Serialize + DeserializeOwned,
1197        V: Serialize + DeserializeOwned,
1198    {
1199        let mut num_keys = 0;
1200        let mut key_bytes_total = 0;
1201        let mut value_bytes_total = 0;
1202        let mut key_hist = hdrhistogram::Histogram::<u64>::new_with_max(100000, 2).unwrap();
1203        let mut value_hist = hdrhistogram::Histogram::<u64>::new_with_max(100000, 2).unwrap();
1204        for item in self.safe_iter() {
1205            let (key, value) = item?;
1206            num_keys += 1;
1207            let key_len = be_fix_int_ser(key.borrow()).len();
1208            let value_len = bcs::to_bytes(value.borrow())?.len();
1209            key_bytes_total += key_len;
1210            value_bytes_total += value_len;
1211            key_hist.record(key_len as u64)?;
1212            value_hist.record(value_len as u64)?;
1213        }
1214        Ok(TableSummary {
1215            num_keys,
1216            key_bytes_total,
1217            value_bytes_total,
1218            key_hist,
1219            value_hist,
1220        })
1221    }
1222
1223    fn start_iter_timer(&self) -> HistogramTimer {
1224        self.db_metrics
1225            .op_metrics
1226            .rocksdb_iter_latency_seconds
1227            .with_label_values(&[&self.cf])
1228            .start_timer()
1229    }
1230
1231    // Creates metrics and context for tracking an iterator usage and performance.
1232    fn create_iter_context(
1233        &self,
1234    ) -> (
1235        Option<HistogramTimer>,
1236        Option<Histogram>,
1237        Option<Histogram>,
1238        Option<RocksDBPerfContext>,
1239    ) {
1240        let timer = self.start_iter_timer();
1241        let bytes_scanned = self
1242            .db_metrics
1243            .op_metrics
1244            .rocksdb_iter_bytes
1245            .with_label_values(&[&self.cf]);
1246        let keys_scanned = self
1247            .db_metrics
1248            .op_metrics
1249            .rocksdb_iter_keys
1250            .with_label_values(&[&self.cf]);
1251        let perf_ctx = if self.iter_sample_interval.sample() {
1252            Some(RocksDBPerfContext)
1253        } else {
1254            None
1255        };
1256        (
1257            Some(timer),
1258            Some(bytes_scanned),
1259            Some(keys_scanned),
1260            perf_ctx,
1261        )
1262    }
1263
1264    /// Creates a safe reversed iterator with optional bounds.
1265    /// Both upper bound and lower bound are included.
1266    #[allow(clippy::complexity)]
1267    pub fn reversed_safe_iter_with_bounds(
1268        &self,
1269        lower_bound: Option<K>,
1270        upper_bound: Option<K>,
1271    ) -> Result<DbIterator<'_, (K, V)>, TypedStoreError>
1272    where
1273        K: Serialize + DeserializeOwned,
1274        V: Serialize + DeserializeOwned,
1275    {
1276        let (it_lower_bound, it_upper_bound) = iterator_bounds_with_range::<K>((
1277            lower_bound
1278                .as_ref()
1279                .map(Bound::Included)
1280                .unwrap_or(Bound::Unbounded),
1281            upper_bound
1282                .as_ref()
1283                .map(Bound::Included)
1284                .unwrap_or(Bound::Unbounded),
1285        ));
1286        match &self.db.storage {
1287            Storage::Rocks(db) => {
1288                let readopts = rocks_util::apply_range_bounds(
1289                    self.opts.readopts(),
1290                    it_lower_bound,
1291                    it_upper_bound,
1292                );
1293                let upper_bound_key = upper_bound.as_ref().map(|k| be_fix_int_ser(&k));
1294                let db_iter = db
1295                    .underlying
1296                    .raw_iterator_cf_opt(&rocks_cf(db, &self.cf), readopts);
1297                let (_timer, bytes_scanned, keys_scanned, _perf_ctx) = self.create_iter_context();
1298                let iter = SafeIter::new(
1299                    self.cf.clone(),
1300                    db_iter,
1301                    _timer,
1302                    _perf_ctx,
1303                    bytes_scanned,
1304                    keys_scanned,
1305                    Some(self.db_metrics.clone()),
1306                );
1307                Ok(Box::new(SafeRevIter::new(iter, upper_bound_key)))
1308            }
1309            Storage::InMemory(db) => {
1310                Ok(db.iterator(&self.cf, it_lower_bound, it_upper_bound, true))
1311            }
1312            #[cfg(tidehunter)]
1313            Storage::TideHunter(db) => match &self.column_family {
1314                ColumnFamily::TideHunter((ks, prefix)) => {
1315                    let mut iter = db.iterator(*ks);
1316                    apply_range_bounds(&mut iter, it_lower_bound, it_upper_bound, prefix);
1317                    iter.reverse();
1318                    Ok(Box::new(transform_th_iterator(
1319                        iter,
1320                        prefix,
1321                        self.start_iter_timer(),
1322                    )))
1323                }
1324                _ => unreachable!("storage backend invariant violation"),
1325            },
1326        }
1327    }
1328
1329    /// Iterates the whole table as a consistent point-in-time snapshot.
1330    /// Equivalent to `snapshot_iterator_with_bounds(None, None, false)`.
1331    pub fn snapshot_iterator(&self) -> DbIterator<'_, (K, V)>
1332    where
1333        K: Serialize + DeserializeOwned,
1334        V: Serialize + DeserializeOwned,
1335    {
1336        self.snapshot_iterator_with_bounds(None, None, false)
1337    }
1338
1339    /// Iterates the table as a consistent point-in-time snapshot, optionally
1340    /// bounded and/or reversed.
1341    ///
1342    /// RocksDB and in-memory iterators are already snapshot-consistent from the
1343    /// moment they are created, so this delegates to the regular iterators. The
1344    /// tidehunter backend's live iterator is not stable under concurrent writes,
1345    /// so this opens a short-lived checkpoint and iterates that frontier instead;
1346    /// the returned iterator owns the checkpoint, pinning the snapshot for its
1347    /// lifetime.
1348    ///
1349    /// Bound semantics match the regular iterators: forward is `[lower, upper)`
1350    /// (upper exclusive), reverse is `[lower, upper]` (both inclusive).
1351    pub fn snapshot_iterator_with_bounds(
1352        &self,
1353        lower_bound: Option<K>,
1354        upper_bound: Option<K>,
1355        reverse: bool,
1356    ) -> DbIterator<'_, (K, V)>
1357    where
1358        K: Serialize + DeserializeOwned,
1359        V: Serialize + DeserializeOwned,
1360    {
1361        #[cfg(tidehunter)]
1362        if let Storage::TideHunter(db) = &self.db.storage {
1363            let ColumnFamily::TideHunter((ks, prefix)) = &self.column_family else {
1364                unreachable!("storage backend invariant violation");
1365            };
1366            // Mirror the bound computation of the regular iterators so the snapshot
1367            // observes the same key range: forward via `iterator_bounds` (upper
1368            // exclusive), reverse via an inclusive range.
1369            let (lower, upper) = if reverse {
1370                iterator_bounds_with_range::<K>((
1371                    lower_bound
1372                        .as_ref()
1373                        .map(Bound::Included)
1374                        .unwrap_or(Bound::Unbounded),
1375                    upper_bound
1376                        .as_ref()
1377                        .map(Bound::Included)
1378                        .unwrap_or(Bound::Unbounded),
1379                ))
1380            } else {
1381                iterator_bounds(lower_bound, upper_bound)
1382            };
1383            let mut iter = db.checkpoint().iterator(*ks);
1384            apply_range_bounds(&mut iter, lower, upper, prefix);
1385            if reverse {
1386                iter.reverse();
1387            }
1388            return Box::new(transform_th_iterator(iter, prefix, self.start_iter_timer()));
1389        }
1390        if reverse {
1391            // Infallible across all backends; only the `Result` shape differs.
1392            self.reversed_safe_iter_with_bounds(lower_bound, upper_bound)
1393                .expect("reversed iterator construction is infallible")
1394        } else {
1395            self.safe_iter_with_bounds(lower_bound, upper_bound)
1396        }
1397    }
1398}
1399
1400pub enum StorageWriteBatch {
1401    Rocks(rocksdb::WriteBatch),
1402    InMemory(InMemoryBatch),
1403    #[cfg(tidehunter)]
1404    TideHunter(tidehunter::batch::WriteBatch),
1405}
1406
1407/// Flat-buffer entry header. All byte data (cf_name, key, value) is stored
1408/// contiguously in `StagedBatch::data`; this header records offsets and lengths
1409/// so that slices can be produced without any per-entry allocation.
1410struct EntryHeader {
1411    /// Byte offset into `StagedBatch::data` where this entry's data begins.
1412    offset: usize,
1413    cf_name_len: usize,
1414    key_len: usize,
1415    is_put: bool,
1416}
1417
1418/// A write batch that stores serialized operations in a flat byte buffer without
1419/// requiring a database reference. Can be replayed into a real `DBBatch` via
1420/// `DBBatch::concat`.
1421/// TOOD: this can be deleted when we upgrade rust-rocksdb, which supports iterating
1422/// over write batches.
1423#[derive(Default)]
1424pub struct StagedBatch {
1425    data: Vec<u8>,
1426    entries: Vec<EntryHeader>,
1427}
1428
1429impl StagedBatch {
1430    pub fn new() -> Self {
1431        Self {
1432            data: Vec::with_capacity(1024),
1433            entries: Vec::with_capacity(16),
1434        }
1435    }
1436
1437    pub fn insert_batch<J: Borrow<K>, K: Serialize, U: Borrow<V>, V: Serialize>(
1438        &mut self,
1439        db: &DBMap<K, V>,
1440        new_vals: impl IntoIterator<Item = (J, U)>,
1441    ) -> Result<&mut Self, TypedStoreError> {
1442        let cf_name = db.cf_name();
1443        new_vals
1444            .into_iter()
1445            .try_for_each::<_, Result<_, TypedStoreError>>(|(k, v)| {
1446                let offset = self.data.len();
1447                self.data.extend_from_slice(cf_name.as_bytes());
1448                let key_len = be_fix_int_ser_into(&mut self.data, k.borrow());
1449                bcs::serialize_into(&mut self.data, v.borrow())
1450                    .map_err(typed_store_err_from_bcs_err)?;
1451                self.entries.push(EntryHeader {
1452                    offset,
1453                    cf_name_len: cf_name.len(),
1454                    key_len,
1455                    is_put: true,
1456                });
1457                Ok(())
1458            })?;
1459        Ok(self)
1460    }
1461
1462    pub fn delete_batch<J: Borrow<K>, K: Serialize, V>(
1463        &mut self,
1464        db: &DBMap<K, V>,
1465        purged_vals: impl IntoIterator<Item = J>,
1466    ) -> Result<(), TypedStoreError> {
1467        let cf_name = db.cf_name();
1468        purged_vals
1469            .into_iter()
1470            .try_for_each::<_, Result<_, TypedStoreError>>(|k| {
1471                let offset = self.data.len();
1472                self.data.extend_from_slice(cf_name.as_bytes());
1473                let key_len = be_fix_int_ser_into(&mut self.data, k.borrow());
1474                self.entries.push(EntryHeader {
1475                    offset,
1476                    cf_name_len: cf_name.len(),
1477                    key_len,
1478                    is_put: false,
1479                });
1480                Ok(())
1481            })?;
1482        Ok(())
1483    }
1484
1485    pub fn size_in_bytes(&self) -> usize {
1486        self.data.len()
1487    }
1488}
1489
1490/// Provides a mutable struct to form a collection of database write operations, and execute them.
1491///
1492/// Batching write and delete operations is faster than performing them one by one and ensures their atomicity,
1493///  ie. they are all written or none is.
1494/// This is also true of operations across column families in the same database.
1495///
1496/// Serializations / Deserialization, and naming of column families is performed by passing a DBMap<K,V>
1497/// with each operation.
1498///
1499/// ```
1500/// use typed_store::rocks::*;
1501/// use tempfile::tempdir;
1502/// use typed_store::Map;
1503/// use typed_store::metrics::DBMetrics;
1504/// use prometheus::Registry;
1505/// use core::fmt::Error;
1506/// use std::sync::Arc;
1507///
1508/// #[tokio::main]
1509/// async fn main() -> Result<(), Error> {
1510/// let rocks = open_cf_opts(tempfile::tempdir().unwrap(), None, MetricConf::default(), &[("First_CF", rocksdb::Options::default()), ("Second_CF", rocksdb::Options::default())]).unwrap();
1511///
1512/// let db_cf_1 = DBMap::reopen(&rocks, Some("First_CF"), &ReadWriteOptions::default(), false)
1513///     .expect("Failed to open storage");
1514/// let keys_vals_1 = (1..100).map(|i| (i, i.to_string()));
1515///
1516/// let db_cf_2 = DBMap::reopen(&rocks, Some("Second_CF"), &ReadWriteOptions::default(), false)
1517///     .expect("Failed to open storage");
1518/// let keys_vals_2 = (1000..1100).map(|i| (i, i.to_string()));
1519///
1520/// let mut batch = db_cf_1.batch();
1521/// batch
1522///     .insert_batch(&db_cf_1, keys_vals_1.clone())
1523///     .expect("Failed to batch insert")
1524///     .insert_batch(&db_cf_2, keys_vals_2.clone())
1525///     .expect("Failed to batch insert");
1526///
1527/// let _ = batch.write().expect("Failed to execute batch");
1528/// for (k, v) in keys_vals_1 {
1529///     let val = db_cf_1.get(&k).expect("Failed to get inserted key");
1530///     assert_eq!(Some(v), val);
1531/// }
1532///
1533/// for (k, v) in keys_vals_2 {
1534///     let val = db_cf_2.get(&k).expect("Failed to get inserted key");
1535///     assert_eq!(Some(v), val);
1536/// }
1537/// Ok(())
1538/// }
1539/// ```
1540///
1541pub struct DBBatch {
1542    database: Arc<Database>,
1543    batch: StorageWriteBatch,
1544    db_metrics: Arc<DBMetrics>,
1545    write_sample_interval: SamplingInterval,
1546}
1547
1548impl DBBatch {
1549    /// Create a new batch associated with a DB reference.
1550    ///
1551    /// Use `open_cf` to get the DB reference or an existing open database.
1552    pub fn new(
1553        dbref: &Arc<Database>,
1554        batch: StorageWriteBatch,
1555        db_metrics: &Arc<DBMetrics>,
1556        write_sample_interval: &SamplingInterval,
1557    ) -> Self {
1558        DBBatch {
1559            database: dbref.clone(),
1560            batch,
1561            db_metrics: db_metrics.clone(),
1562            write_sample_interval: write_sample_interval.clone(),
1563        }
1564    }
1565
1566    /// Consume the batch and write its operations to the database
1567    #[instrument(level = "trace", skip_all, err)]
1568    pub fn write(self) -> Result<(), TypedStoreError> {
1569        let mut write_options = rocksdb::WriteOptions::default();
1570
1571        if write_sync_enabled() {
1572            write_options.set_sync(true);
1573        }
1574
1575        self.write_opt(write_options)
1576    }
1577
1578    /// Consume the batch and write its operations to the database with custom write options
1579    #[instrument(level = "trace", skip_all, err)]
1580    pub fn write_opt(self, write_options: rocksdb::WriteOptions) -> Result<(), TypedStoreError> {
1581        let db_name = self.database.db_name();
1582        let timer = self
1583            .db_metrics
1584            .op_metrics
1585            .rocksdb_batch_commit_latency_seconds
1586            .with_label_values(&[&db_name])
1587            .start_timer();
1588        let batch_size = self.size_in_bytes();
1589
1590        let perf_ctx = if self.write_sample_interval.sample() {
1591            Some(RocksDBPerfContext)
1592        } else {
1593            None
1594        };
1595
1596        self.database
1597            .write_opt_internal(self.batch, &write_options)?;
1598
1599        self.db_metrics
1600            .op_metrics
1601            .rocksdb_batch_commit_bytes
1602            .with_label_values(&[&db_name])
1603            .observe(batch_size as f64);
1604
1605        if perf_ctx.is_some() {
1606            self.db_metrics
1607                .write_perf_ctx_metrics
1608                .report_metrics(&db_name);
1609        }
1610        let elapsed = timer.stop_and_record();
1611        if elapsed > 1.0 {
1612            warn!(?elapsed, ?db_name, "very slow batch write");
1613            self.db_metrics
1614                .op_metrics
1615                .rocksdb_very_slow_batch_writes_count
1616                .with_label_values(&[&db_name])
1617                .inc();
1618            self.db_metrics
1619                .op_metrics
1620                .rocksdb_very_slow_batch_writes_duration_ms
1621                .with_label_values(&[&db_name])
1622                .inc_by((elapsed * 1000.0) as u64);
1623        }
1624        Ok(())
1625    }
1626
1627    pub fn size_in_bytes(&self) -> usize {
1628        match self.batch {
1629            StorageWriteBatch::Rocks(ref b) => b.size_in_bytes(),
1630            StorageWriteBatch::InMemory(_) => 0,
1631            // TODO: implement size_in_bytes method
1632            #[cfg(tidehunter)]
1633            StorageWriteBatch::TideHunter(_) => 0,
1634        }
1635    }
1636
1637    /// Replay all operations from `StagedBatch`es into this batch.
1638    pub fn concat(&mut self, raw_batches: Vec<StagedBatch>) -> Result<&mut Self, TypedStoreError> {
1639        for raw_batch in raw_batches {
1640            let data = &raw_batch.data;
1641            for (i, hdr) in raw_batch.entries.iter().enumerate() {
1642                let end = raw_batch
1643                    .entries
1644                    .get(i + 1)
1645                    .map_or(data.len(), |next| next.offset);
1646                let cf_bytes = &data[hdr.offset..hdr.offset + hdr.cf_name_len];
1647                let key_start = hdr.offset + hdr.cf_name_len;
1648                let key = &data[key_start..key_start + hdr.key_len];
1649                // Safety: cf_name was written from &str bytes in insert_batch / delete_batch.
1650                let cf_name = std::str::from_utf8(cf_bytes)
1651                    .map_err(|e| TypedStoreError::SerializationError(e.to_string()))?;
1652
1653                if hdr.is_put {
1654                    let value = &data[key_start + hdr.key_len..end];
1655                    match &mut self.batch {
1656                        StorageWriteBatch::Rocks(b) => {
1657                            b.put_cf(&rocks_cf_from_db(&self.database, cf_name)?, key, value);
1658                        }
1659                        StorageWriteBatch::InMemory(b) => {
1660                            b.put_cf(cf_name, key, value);
1661                        }
1662                        #[cfg(tidehunter)]
1663                        _ => {
1664                            return Err(TypedStoreError::RocksDBError(
1665                                "concat not supported for TideHunter".to_string(),
1666                            ));
1667                        }
1668                    }
1669                } else {
1670                    match &mut self.batch {
1671                        StorageWriteBatch::Rocks(b) => {
1672                            b.delete_cf(&rocks_cf_from_db(&self.database, cf_name)?, key);
1673                        }
1674                        StorageWriteBatch::InMemory(b) => {
1675                            b.delete_cf(cf_name, key);
1676                        }
1677                        #[cfg(tidehunter)]
1678                        _ => {
1679                            return Err(TypedStoreError::RocksDBError(
1680                                "concat not supported for TideHunter".to_string(),
1681                            ));
1682                        }
1683                    }
1684                }
1685            }
1686        }
1687        Ok(self)
1688    }
1689
1690    pub fn delete_batch<J: Borrow<K>, K: Serialize, V>(
1691        &mut self,
1692        db: &DBMap<K, V>,
1693        purged_vals: impl IntoIterator<Item = J>,
1694    ) -> Result<(), TypedStoreError> {
1695        if !Arc::ptr_eq(&db.db, &self.database) {
1696            return Err(TypedStoreError::CrossDBBatch);
1697        }
1698
1699        purged_vals
1700            .into_iter()
1701            .try_for_each::<_, Result<_, TypedStoreError>>(|k| {
1702                let k_buf = be_fix_int_ser(k.borrow());
1703                match (&mut self.batch, &db.column_family) {
1704                    (StorageWriteBatch::Rocks(b), ColumnFamily::Rocks(name)) => {
1705                        b.delete_cf(&rocks_cf_from_db(&self.database, name)?, k_buf)
1706                    }
1707                    (StorageWriteBatch::InMemory(b), ColumnFamily::InMemory(name)) => {
1708                        b.delete_cf(name, k_buf)
1709                    }
1710                    #[cfg(tidehunter)]
1711                    (StorageWriteBatch::TideHunter(b), ColumnFamily::TideHunter((ks, prefix))) => {
1712                        b.delete(*ks, transform_th_key(&k_buf, prefix))
1713                    }
1714                    _ => Err(TypedStoreError::RocksDBError(
1715                        "typed store invariant violation".to_string(),
1716                    ))?,
1717                }
1718                Ok(())
1719            })?;
1720        Ok(())
1721    }
1722
1723    /// Deletes a range of keys between `from` (inclusive) and `to` (non-inclusive)
1724    /// by writing a range delete tombstone in the db map
1725    /// If the DBMap is configured with ignore_range_deletions set to false,
1726    /// the effect of this write will be visible immediately i.e. you won't
1727    /// see old values when you do a lookup or scan. But if it is configured
1728    /// with ignore_range_deletions set to true, the old value are visible until
1729    /// compaction actually deletes them which will happen sometime after. By
1730    /// default ignore_range_deletions is set to true on a DBMap (unless it is
1731    /// overridden in the config), so please use this function with caution
1732    pub fn schedule_delete_range<K: Serialize, V>(
1733        &mut self,
1734        db: &DBMap<K, V>,
1735        from: &K,
1736        to: &K,
1737    ) -> Result<(), TypedStoreError> {
1738        if !Arc::ptr_eq(&db.db, &self.database) {
1739            return Err(TypedStoreError::CrossDBBatch);
1740        }
1741
1742        let from_buf = be_fix_int_ser(from);
1743        let to_buf = be_fix_int_ser(to);
1744
1745        if let StorageWriteBatch::Rocks(b) = &mut self.batch {
1746            b.delete_range_cf(
1747                &rocks_cf_from_db(&self.database, db.cf_name())?,
1748                from_buf,
1749                to_buf,
1750            );
1751        }
1752        Ok(())
1753    }
1754
1755    /// inserts a range of (key, value) pairs given as an iterator
1756    pub fn insert_batch<J: Borrow<K>, K: Serialize, U: Borrow<V>, V: Serialize>(
1757        &mut self,
1758        db: &DBMap<K, V>,
1759        new_vals: impl IntoIterator<Item = (J, U)>,
1760    ) -> Result<&mut Self, TypedStoreError> {
1761        if !Arc::ptr_eq(&db.db, &self.database) {
1762            return Err(TypedStoreError::CrossDBBatch);
1763        }
1764        let mut total = 0usize;
1765        new_vals
1766            .into_iter()
1767            .try_for_each::<_, Result<_, TypedStoreError>>(|(k, v)| {
1768                let k_buf = be_fix_int_ser(k.borrow());
1769                let v_buf = bcs::to_bytes(v.borrow()).map_err(typed_store_err_from_bcs_err)?;
1770                total += k_buf.len() + v_buf.len();
1771                if db.opts.log_value_hash {
1772                    let key_hash = default_hash(&k_buf);
1773                    let value_hash = default_hash(&v_buf);
1774                    debug!(
1775                        "Insert to DB table: {:?}, key_hash: {:?}, value_hash: {:?}",
1776                        db.cf_name(),
1777                        key_hash,
1778                        value_hash
1779                    );
1780                }
1781                match (&mut self.batch, &db.column_family) {
1782                    (StorageWriteBatch::Rocks(b), ColumnFamily::Rocks(name)) => {
1783                        b.put_cf(&rocks_cf_from_db(&self.database, name)?, k_buf, v_buf)
1784                    }
1785                    (StorageWriteBatch::InMemory(b), ColumnFamily::InMemory(name)) => {
1786                        b.put_cf(name, k_buf, v_buf)
1787                    }
1788                    #[cfg(tidehunter)]
1789                    (StorageWriteBatch::TideHunter(b), ColumnFamily::TideHunter((ks, prefix))) => {
1790                        b.write(*ks, transform_th_key(&k_buf, prefix), v_buf.to_vec())
1791                    }
1792                    _ => Err(TypedStoreError::RocksDBError(
1793                        "typed store invariant violation".to_string(),
1794                    ))?,
1795                }
1796                Ok(())
1797            })?;
1798        self.db_metrics
1799            .op_metrics
1800            .rocksdb_batch_put_bytes
1801            .with_label_values(&[&db.cf])
1802            .observe(total as f64);
1803        Ok(self)
1804    }
1805
1806    pub fn partial_merge_batch<J: Borrow<K>, K: Serialize, U: Borrow<V>, V: Serialize>(
1807        &mut self,
1808        db: &DBMap<K, V>,
1809        new_vals: impl IntoIterator<Item = (J, U)>,
1810    ) -> Result<&mut Self, TypedStoreError> {
1811        if !Arc::ptr_eq(&db.db, &self.database) {
1812            return Err(TypedStoreError::CrossDBBatch);
1813        }
1814        new_vals
1815            .into_iter()
1816            .try_for_each::<_, Result<_, TypedStoreError>>(|(k, v)| {
1817                let k_buf = be_fix_int_ser(k.borrow());
1818                let v_buf = bcs::to_bytes(v.borrow()).map_err(typed_store_err_from_bcs_err)?;
1819                match &mut self.batch {
1820                    StorageWriteBatch::Rocks(b) => b.merge_cf(
1821                        &rocks_cf_from_db(&self.database, db.cf_name())?,
1822                        k_buf,
1823                        v_buf,
1824                    ),
1825                    _ => unimplemented!("merge operator is only implemented for RocksDB"),
1826                }
1827                Ok(())
1828            })?;
1829        Ok(self)
1830    }
1831}
1832
1833impl<'a, K, V> Map<'a, K, V> for DBMap<K, V>
1834where
1835    K: Serialize + DeserializeOwned,
1836    V: Serialize + DeserializeOwned,
1837{
1838    type Error = TypedStoreError;
1839
1840    #[instrument(level = "trace", skip_all, err)]
1841    fn contains_key(&self, key: &K) -> Result<bool, TypedStoreError> {
1842        let key_buf = be_fix_int_ser(key);
1843        self.db
1844            .contains(&self.column_family, &key_buf, &self.opts.readopts())
1845    }
1846
1847    #[instrument(level = "trace", skip_all, err)]
1848    fn multi_contains_keys<J>(
1849        &self,
1850        keys: impl IntoIterator<Item = J>,
1851    ) -> Result<Vec<bool>, Self::Error>
1852    where
1853        J: Borrow<K>,
1854    {
1855        let _timer = self
1856            .db_metrics
1857            .op_metrics
1858            .rocksdb_multiget_latency_seconds
1859            .with_label_values(&[&self.cf])
1860            .start_timer();
1861        let perf_ctx = if self.multiget_sample_interval.sample() {
1862            Some(RocksDBPerfContext)
1863        } else {
1864            None
1865        };
1866        let keys_bytes = keys.into_iter().map(|k| be_fix_int_ser(k.borrow()));
1867        let result = self
1868            .db
1869            .multi_contains(&self.column_family, keys_bytes, &self.opts.readopts());
1870        if perf_ctx.is_some() {
1871            self.db_metrics
1872                .read_perf_ctx_metrics
1873                .report_metrics(&self.cf);
1874        }
1875        result
1876    }
1877
1878    #[instrument(level = "trace", skip_all, err)]
1879    fn get(&self, key: &K) -> Result<Option<V>, TypedStoreError> {
1880        let _timer = self
1881            .db_metrics
1882            .op_metrics
1883            .rocksdb_get_latency_seconds
1884            .with_label_values(&[&self.cf])
1885            .start_timer();
1886        let key_buf = be_fix_int_ser(key);
1887        let res = get_raw(
1888            &self.db,
1889            &self.column_family,
1890            &self.cf,
1891            &self.db_metrics,
1892            &self.get_sample_interval,
1893            &self.opts,
1894            &key_buf,
1895        )?;
1896        match res {
1897            Some(data) => {
1898                let value = bcs::from_bytes(&data).map_err(typed_store_err_from_bcs_err);
1899                if let Err(e) = &value {
1900                    report_value_deserialization_error(self.cf_name(), &key_buf, &data, e);
1901                }
1902                Ok(Some(value?))
1903            }
1904            None => Ok(None),
1905        }
1906    }
1907
1908    #[instrument(level = "trace", skip_all, err)]
1909    fn insert(&self, key: &K, value: &V) -> Result<(), TypedStoreError> {
1910        let timer = self
1911            .db_metrics
1912            .op_metrics
1913            .rocksdb_put_latency_seconds
1914            .with_label_values(&[&self.cf])
1915            .start_timer();
1916        let perf_ctx = if self.write_sample_interval.sample() {
1917            Some(RocksDBPerfContext)
1918        } else {
1919            None
1920        };
1921        let key_buf = be_fix_int_ser(key);
1922        let value_buf = bcs::to_bytes(value).map_err(typed_store_err_from_bcs_err)?;
1923        self.db_metrics
1924            .op_metrics
1925            .rocksdb_put_bytes
1926            .with_label_values(&[&self.cf])
1927            .observe((key_buf.len() + value_buf.len()) as f64);
1928        if perf_ctx.is_some() {
1929            self.db_metrics
1930                .write_perf_ctx_metrics
1931                .report_metrics(&self.cf);
1932        }
1933        self.db.put_cf(&self.column_family, key_buf, value_buf)?;
1934
1935        let elapsed = timer.stop_and_record();
1936        if elapsed > 1.0 {
1937            warn!(?elapsed, cf = ?self.cf, "very slow insert");
1938            self.db_metrics
1939                .op_metrics
1940                .rocksdb_very_slow_puts_count
1941                .with_label_values(&[&self.cf])
1942                .inc();
1943            self.db_metrics
1944                .op_metrics
1945                .rocksdb_very_slow_puts_duration_ms
1946                .with_label_values(&[&self.cf])
1947                .inc_by((elapsed * 1000.0) as u64);
1948        }
1949
1950        Ok(())
1951    }
1952
1953    #[instrument(level = "trace", skip_all, err)]
1954    fn remove(&self, key: &K) -> Result<(), TypedStoreError> {
1955        let _timer = self
1956            .db_metrics
1957            .op_metrics
1958            .rocksdb_delete_latency_seconds
1959            .with_label_values(&[&self.cf])
1960            .start_timer();
1961        let perf_ctx = if self.write_sample_interval.sample() {
1962            Some(RocksDBPerfContext)
1963        } else {
1964            None
1965        };
1966        let key_buf = be_fix_int_ser(key);
1967        self.db.delete_cf(&self.column_family, key_buf)?;
1968        self.db_metrics
1969            .op_metrics
1970            .rocksdb_deletes
1971            .with_label_values(&[&self.cf])
1972            .inc();
1973        if perf_ctx.is_some() {
1974            self.db_metrics
1975                .write_perf_ctx_metrics
1976                .report_metrics(&self.cf);
1977        }
1978        Ok(())
1979    }
1980
1981    /// Writes a range delete tombstone to delete all entries in the db map
1982    /// If the DBMap is configured with ignore_range_deletions set to false,
1983    /// the effect of this write will be visible immediately i.e. you won't
1984    /// see old values when you do a lookup or scan. But if it is configured
1985    /// with ignore_range_deletions set to true, the old value are visible until
1986    /// compaction actually deletes them which will happen sometime after. By
1987    /// default ignore_range_deletions is set to true on a DBMap (unless it is
1988    /// overridden in the config), so please use this function with caution
1989    #[instrument(level = "trace", skip_all, err)]
1990    fn schedule_delete_all(&self) -> Result<(), TypedStoreError> {
1991        let first_key = self.safe_iter().next().transpose()?.map(|(k, _v)| k);
1992        let last_key = self
1993            .reversed_safe_iter_with_bounds(None, None)?
1994            .next()
1995            .transpose()?
1996            .map(|(k, _v)| k);
1997        if let Some((first_key, last_key)) = first_key.zip(last_key) {
1998            let mut batch = self.batch();
1999            batch.schedule_delete_range(self, &first_key, &last_key)?;
2000            batch.write()?;
2001        }
2002        Ok(())
2003    }
2004
2005    fn is_empty(&self) -> bool {
2006        self.safe_iter().next().is_none()
2007    }
2008
2009    fn safe_iter(&'a self) -> DbIterator<'a, (K, V)> {
2010        match &self.db.storage {
2011            Storage::Rocks(db) => {
2012                let db_iter = db
2013                    .underlying
2014                    .raw_iterator_cf_opt(&rocks_cf(db, &self.cf), self.opts.readopts());
2015                let (_timer, bytes_scanned, keys_scanned, _perf_ctx) = self.create_iter_context();
2016                Box::new(SafeIter::new(
2017                    self.cf.clone(),
2018                    db_iter,
2019                    _timer,
2020                    _perf_ctx,
2021                    bytes_scanned,
2022                    keys_scanned,
2023                    Some(self.db_metrics.clone()),
2024                ))
2025            }
2026            Storage::InMemory(db) => db.iterator(&self.cf, None, None, false),
2027            #[cfg(tidehunter)]
2028            Storage::TideHunter(db) => match &self.column_family {
2029                ColumnFamily::TideHunter((ks, prefix)) => Box::new(transform_th_iterator(
2030                    db.iterator(*ks),
2031                    prefix,
2032                    self.start_iter_timer(),
2033                )),
2034                _ => unreachable!("storage backend invariant violation"),
2035            },
2036        }
2037    }
2038
2039    fn safe_iter_with_bounds(
2040        &'a self,
2041        lower_bound: Option<K>,
2042        upper_bound: Option<K>,
2043    ) -> DbIterator<'a, (K, V)> {
2044        let (lower_bound, upper_bound) = iterator_bounds(lower_bound, upper_bound);
2045        match &self.db.storage {
2046            Storage::Rocks(db) => {
2047                let readopts =
2048                    rocks_util::apply_range_bounds(self.opts.readopts(), lower_bound, upper_bound);
2049                let db_iter = db
2050                    .underlying
2051                    .raw_iterator_cf_opt(&rocks_cf(db, &self.cf), readopts);
2052                let (_timer, bytes_scanned, keys_scanned, _perf_ctx) = self.create_iter_context();
2053                Box::new(SafeIter::new(
2054                    self.cf.clone(),
2055                    db_iter,
2056                    _timer,
2057                    _perf_ctx,
2058                    bytes_scanned,
2059                    keys_scanned,
2060                    Some(self.db_metrics.clone()),
2061                ))
2062            }
2063            Storage::InMemory(db) => db.iterator(&self.cf, lower_bound, upper_bound, false),
2064            #[cfg(tidehunter)]
2065            Storage::TideHunter(db) => match &self.column_family {
2066                ColumnFamily::TideHunter((ks, prefix)) => {
2067                    let mut iter = db.iterator(*ks);
2068                    apply_range_bounds(&mut iter, lower_bound, upper_bound, prefix);
2069                    Box::new(transform_th_iterator(iter, prefix, self.start_iter_timer()))
2070                }
2071                _ => unreachable!("storage backend invariant violation"),
2072            },
2073        }
2074    }
2075
2076    fn safe_range_iter(&'a self, range: impl RangeBounds<K>) -> DbIterator<'a, (K, V)> {
2077        let (lower_bound, upper_bound) = iterator_bounds_with_range(range);
2078        match &self.db.storage {
2079            Storage::Rocks(db) => {
2080                let readopts =
2081                    rocks_util::apply_range_bounds(self.opts.readopts(), lower_bound, upper_bound);
2082                let db_iter = db
2083                    .underlying
2084                    .raw_iterator_cf_opt(&rocks_cf(db, &self.cf), readopts);
2085                let (_timer, bytes_scanned, keys_scanned, _perf_ctx) = self.create_iter_context();
2086                Box::new(SafeIter::new(
2087                    self.cf.clone(),
2088                    db_iter,
2089                    _timer,
2090                    _perf_ctx,
2091                    bytes_scanned,
2092                    keys_scanned,
2093                    Some(self.db_metrics.clone()),
2094                ))
2095            }
2096            Storage::InMemory(db) => db.iterator(&self.cf, lower_bound, upper_bound, false),
2097            #[cfg(tidehunter)]
2098            Storage::TideHunter(db) => match &self.column_family {
2099                ColumnFamily::TideHunter((ks, prefix)) => {
2100                    let mut iter = db.iterator(*ks);
2101                    apply_range_bounds(&mut iter, lower_bound, upper_bound, prefix);
2102                    Box::new(transform_th_iterator(iter, prefix, self.start_iter_timer()))
2103                }
2104                _ => unreachable!("storage backend invariant violation"),
2105            },
2106        }
2107    }
2108
2109    /// Returns a vector of values corresponding to the keys provided.
2110    #[instrument(level = "trace", skip_all, err)]
2111    fn multi_get<J>(
2112        &self,
2113        keys: impl IntoIterator<Item = J>,
2114    ) -> Result<Vec<Option<V>>, TypedStoreError>
2115    where
2116        J: Borrow<K>,
2117    {
2118        let results = self.multi_get_pinned(keys)?;
2119        let values_parsed: Result<Vec<_>, TypedStoreError> = results
2120            .into_iter()
2121            .map(|value_byte| match value_byte {
2122                Some(data) => Ok(Some(
2123                    bcs::from_bytes(&data).map_err(typed_store_err_from_bcs_err)?,
2124                )),
2125                None => Ok(None),
2126            })
2127            .collect();
2128
2129        values_parsed
2130    }
2131
2132    /// Convenience method for batch insertion
2133    #[instrument(level = "trace", skip_all, err)]
2134    fn multi_insert<J, U>(
2135        &self,
2136        key_val_pairs: impl IntoIterator<Item = (J, U)>,
2137    ) -> Result<(), Self::Error>
2138    where
2139        J: Borrow<K>,
2140        U: Borrow<V>,
2141    {
2142        let mut batch = self.batch();
2143        batch.insert_batch(self, key_val_pairs)?;
2144        batch.write()
2145    }
2146
2147    /// Convenience method for batch removal
2148    #[instrument(level = "trace", skip_all, err)]
2149    fn multi_remove<J>(&self, keys: impl IntoIterator<Item = J>) -> Result<(), Self::Error>
2150    where
2151        J: Borrow<K>,
2152    {
2153        let mut batch = self.batch();
2154        batch.delete_batch(self, keys)?;
2155        batch.write()
2156    }
2157
2158    /// Try to catch up with primary when running as secondary
2159    #[instrument(level = "trace", skip_all, err)]
2160    fn try_catch_up_with_primary(&self) -> Result<(), Self::Error> {
2161        try_catch_up_with_primary(&self.db)
2162    }
2163}
2164
2165/// Opens a database with options, and a number of column families with individual options that are created if they do not exist.
2166#[instrument(level="debug", skip_all, fields(path = ?path.as_ref()), err)]
2167pub fn open_cf_opts<P: AsRef<Path>>(
2168    path: P,
2169    db_options: Option<rocksdb::Options>,
2170    metric_conf: MetricConf,
2171    opt_cfs: &[(&str, rocksdb::Options)],
2172) -> Result<Arc<Database>, TypedStoreError> {
2173    let path = path.as_ref();
2174    ensure_database_type(path, StorageType::Rocks)
2175        .map_err(|e| TypedStoreError::RocksDBError(e.to_string()))?;
2176    // In the simulator, we intercept the wall clock in the test thread only. This causes problems
2177    // because rocksdb uses the simulated clock when creating its background threads, but then
2178    // those threads see the real wall clock (because they are not the test thread), which causes
2179    // rocksdb to panic. The `nondeterministic` macro evaluates expressions in new threads, which
2180    // resolves the issue.
2181    //
2182    // This is a no-op in non-simulator builds.
2183
2184    let cfs = populate_missing_cfs(opt_cfs, path).map_err(typed_store_err_from_rocks_err)?;
2185    nondeterministic!({
2186        let mut options = db_options.unwrap_or_else(|| default_db_options().options);
2187        options.create_if_missing(true);
2188        options.create_missing_column_families(true);
2189        let rocksdb = {
2190            rocksdb::DBWithThreadMode::<MultiThreaded>::open_cf_descriptors(
2191                &options,
2192                path,
2193                cfs.into_iter()
2194                    .map(|(name, opts)| ColumnFamilyDescriptor::new(name, opts)),
2195            )
2196            .map_err(typed_store_err_from_rocks_err)?
2197        };
2198        Ok(Arc::new(Database::new(
2199            Storage::Rocks(RocksDB {
2200                underlying: rocksdb,
2201            }),
2202            metric_conf,
2203            None,
2204        )))
2205    })
2206}
2207
2208/// Opens a database with options, and a number of column families with individual options that are created if they do not exist.
2209pub fn open_cf_opts_secondary<P: AsRef<Path>>(
2210    primary_path: P,
2211    secondary_path: Option<P>,
2212    db_options: Option<rocksdb::Options>,
2213    metric_conf: MetricConf,
2214    opt_cfs: &[(&str, rocksdb::Options)],
2215) -> Result<Arc<Database>, TypedStoreError> {
2216    let primary_path = primary_path.as_ref();
2217    let secondary_path = secondary_path.as_ref().map(|p| p.as_ref());
2218    // See comment above for explanation of why nondeterministic is necessary here.
2219    nondeterministic!({
2220        // Customize database options
2221        let mut options = db_options.unwrap_or_else(|| default_db_options().options);
2222
2223        fdlimit::raise_fd_limit();
2224        // This is a requirement by RocksDB when opening as secondary
2225        options.set_max_open_files(-1);
2226
2227        let mut opt_cfs: std::collections::HashMap<_, _> = opt_cfs.iter().cloned().collect();
2228        let cfs = rocksdb::DBWithThreadMode::<MultiThreaded>::list_cf(&options, primary_path)
2229            .ok()
2230            .unwrap_or_default();
2231
2232        let default_db_options = default_db_options();
2233        // Add CFs not explicitly listed
2234        for cf_key in cfs.iter() {
2235            if !opt_cfs.contains_key(&cf_key[..]) {
2236                opt_cfs.insert(cf_key, default_db_options.options.clone());
2237            }
2238        }
2239
2240        let primary_path = primary_path.to_path_buf();
2241        let secondary_path = secondary_path.map(|q| q.to_path_buf()).unwrap_or_else(|| {
2242            let mut s = primary_path.clone();
2243            s.pop();
2244            s.push("SECONDARY");
2245            s.as_path().to_path_buf()
2246        });
2247
2248        ensure_database_type(&primary_path, StorageType::Rocks)
2249            .map_err(|e| TypedStoreError::RocksDBError(e.to_string()))?;
2250        ensure_database_type(&secondary_path, StorageType::Rocks)
2251            .map_err(|e| TypedStoreError::RocksDBError(e.to_string()))?;
2252
2253        let rocksdb = {
2254            options.create_if_missing(true);
2255            options.create_missing_column_families(true);
2256            let db = rocksdb::DBWithThreadMode::<MultiThreaded>::open_cf_descriptors_as_secondary(
2257                &options,
2258                &primary_path,
2259                &secondary_path,
2260                opt_cfs
2261                    .iter()
2262                    .map(|(name, opts)| ColumnFamilyDescriptor::new(*name, (*opts).clone())),
2263            )
2264            .map_err(typed_store_err_from_rocks_err)?;
2265            db.try_catch_up_with_primary()
2266                .map_err(typed_store_err_from_rocks_err)?;
2267            db
2268        };
2269        Ok(Arc::new(Database::new(
2270            Storage::Rocks(RocksDB {
2271                underlying: rocksdb,
2272            }),
2273            metric_conf,
2274            None,
2275        )))
2276    })
2277}
2278
2279// Drops a database if there is no other handle to it, with retries and timeout.
2280// Detects the storage variant (RocksDB vs. tidehunter) from the directory
2281// contents and dispatches to the matching cleanup. Both variants coexist in
2282// tidehunter builds — some stores (e.g. rpc-index) are pure RocksDB even when
2283// the tidehunter feature is enabled elsewhere in the binary.
2284pub async fn safe_drop_db(path: PathBuf, timeout: Duration) -> Result<(), std::io::Error> {
2285    #[cfg(tidehunter)]
2286    if is_tidehunter_db(&path) {
2287        return safe_drop_tidehunter_db(path, timeout).await;
2288    }
2289    safe_drop_rocksdb(path, timeout).await
2290}
2291
2292async fn safe_drop_rocksdb(path: PathBuf, timeout: Duration) -> Result<(), std::io::Error> {
2293    let mut backoff = backoff::ExponentialBackoff {
2294        max_elapsed_time: Some(timeout),
2295        ..Default::default()
2296    };
2297    loop {
2298        match rocksdb::DB::destroy(&rocksdb::Options::default(), path.clone()) {
2299            Ok(()) => return Ok(()),
2300            Err(err) => match backoff.next_backoff() {
2301                Some(duration) => tokio::time::sleep(duration).await,
2302                None => return Err(std::io::Error::other(err)),
2303            },
2304        }
2305    }
2306}
2307
2308#[cfg(tidehunter)]
2309fn is_tidehunter_db(path: &Path) -> bool {
2310    // `shape_v2.yaml` is written by TideHunterDb::open at the DB root; RocksDB
2311    // never creates it.
2312    path.join("shape_v2.yaml").exists()
2313}
2314
2315#[cfg(tidehunter)]
2316async fn safe_drop_tidehunter_db(path: PathBuf, timeout: Duration) -> Result<(), std::io::Error> {
2317    let mut backoff = backoff::ExponentialBackoff {
2318        max_elapsed_time: Some(timeout),
2319        ..Default::default()
2320    };
2321    loop {
2322        match TideHunterDb::drop_db(&path) {
2323            Ok(()) => return Ok(()),
2324            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
2325                match backoff.next_backoff() {
2326                    Some(duration) => tokio::time::sleep(duration).await,
2327                    None => {
2328                        warn!(
2329                            "Database at {:?} is still locked after timeout ({:?})",
2330                            path, timeout
2331                        );
2332                        return Err(err);
2333                    }
2334                }
2335            }
2336            Err(err) => return Err(err),
2337        }
2338    }
2339}
2340
2341fn populate_missing_cfs(
2342    input_cfs: &[(&str, rocksdb::Options)],
2343    path: &Path,
2344) -> Result<Vec<(String, rocksdb::Options)>, rocksdb::Error> {
2345    let mut cfs = vec![];
2346    let input_cf_index: HashSet<_> = input_cfs.iter().map(|(name, _)| *name).collect();
2347    let existing_cfs =
2348        rocksdb::DBWithThreadMode::<MultiThreaded>::list_cf(&rocksdb::Options::default(), path)
2349            .ok()
2350            .unwrap_or_default();
2351
2352    for cf_name in existing_cfs {
2353        if !input_cf_index.contains(&cf_name[..]) {
2354            cfs.push((cf_name, rocksdb::Options::default()));
2355        }
2356    }
2357    cfs.extend(
2358        input_cfs
2359            .iter()
2360            .map(|(name, opts)| (name.to_string(), (*opts).clone())),
2361    );
2362    Ok(cfs)
2363}
2364
2365fn default_hash(value: &[u8]) -> Digest<32> {
2366    let mut hasher = fastcrypto::hash::Blake2b256::default();
2367    hasher.update(value);
2368    hasher.finalize()
2369}