Skip to main content

typed_store/
database.rs

1// Copyright (c) 2026 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    borrow::Borrow,
6    marker::PhantomData,
7    ops::{Bound, Deref, RangeBounds},
8    path::{Path, PathBuf},
9    sync::{Arc, Weak},
10    time::Duration,
11};
12
13use fastcrypto::hash::{Digest, HashFunction};
14use iota_common::debug_fatal;
15use iota_macros::{fail_point, nondeterministic};
16use prometheus_filtered::{Histogram, HistogramTimer};
17use rocksdb::{
18    DBPinnableSlice, DBWithThreadMode, Error, LiveFile, MultiThreaded, ReadOptions,
19    SnapshotWithThreadMode, WriteBatch,
20};
21use serde::{Serialize, de::DeserializeOwned};
22use tokio::{sync::oneshot, time::Instant};
23use tracing::{debug, error, info, instrument, warn};
24use typed_store_error::TypedStoreError;
25
26use crate::{
27    DbIterator,
28    memstore::{InMemoryBatch, InMemoryDB},
29    metrics::{DBMetrics, RocksDBPerfContext, SamplingInterval},
30    rocks::{
31        RocksDB,
32        errors::{typed_store_err_from_bcs_err, typed_store_err_from_rocks_err},
33        options::ReadWriteOptions,
34        rocks_cf, rocks_util,
35        safe_iter::{SafeIter, SafeRevIter},
36    },
37    traits::{Map, TableSummary},
38    util::{
39        be_fix_int_ser, iterator_bounds_with_range, prefix_iterator_bounds,
40        prefix_iterator_bounds_with_range,
41    },
42};
43
44#[derive(Clone)]
45pub(crate) enum ColumnFamily {
46    Rocks(String),
47    #[allow(dead_code)]
48    InMemory(String),
49}
50
51impl std::fmt::Debug for ColumnFamily {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            ColumnFamily::Rocks(name) => write!(f, "RocksDB cf: {name}"),
55            ColumnFamily::InMemory(name) => write!(f, "InMemory cf: {name}"),
56        }
57    }
58}
59
60impl ColumnFamily {
61    pub(crate) fn name(&self) -> &str {
62        match self {
63            ColumnFamily::Rocks(name) => name,
64            ColumnFamily::InMemory(name) => name,
65        }
66    }
67}
68
69pub(crate) enum Storage {
70    Rocks(RocksDB),
71    #[allow(dead_code)]
72    InMemory(InMemoryDB),
73}
74
75/// A point-in-time RocksDB snapshot of a database.
76///
77/// Reads through it ignore every write made after it was taken. It pins a
78/// sequence number rather than copying data, and does not survive a restart.
79///
80/// While it is alive, RocksDB keeps on disk every older version it may still
81/// read, so take it as late as possible and drop it as soon as the read is
82/// done.
83///
84/// A `CompactionFilter` ignores snapshots and may drop rows one is still
85/// reading, so never install one on a column family read through a snapshot.
86pub struct DbSnapshot<'db> {
87    snapshot: SnapshotWithThreadMode<'db, DBWithThreadMode<MultiThreaded>>,
88}
89
90impl std::fmt::Debug for Storage {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        match self {
93            Storage::Rocks(db) => write!(f, "RocksDB Storage {db:?}"),
94            Storage::InMemory(db) => write!(f, "InMemoryDB Storage {db:?}"),
95        }
96    }
97}
98
99pub(crate) enum GetResult<'a> {
100    Rocks(DBPinnableSlice<'a>),
101    InMemory(Vec<u8>),
102}
103
104impl Deref for GetResult<'_> {
105    type Target = [u8];
106    fn deref(&self) -> &[u8] {
107        match self {
108            GetResult::Rocks(d) => d.deref(),
109            GetResult::InMemory(d) => d.deref(),
110        }
111    }
112}
113
114pub enum StorageWriteBatch {
115    Rocks(rocksdb::WriteBatch),
116    InMemory(InMemoryBatch),
117}
118
119#[derive(Debug, Default)]
120pub struct MetricConf {
121    pub db_name: String,
122    pub read_sample_interval: SamplingInterval,
123    pub write_sample_interval: SamplingInterval,
124    pub iter_sample_interval: SamplingInterval,
125}
126
127impl MetricConf {
128    pub fn new(db_name: &str) -> Self {
129        if db_name.is_empty() {
130            error!("A meaningful db name should be used for metrics reporting.")
131        }
132        Self {
133            db_name: db_name.to_string(),
134            read_sample_interval: SamplingInterval::default(),
135            write_sample_interval: SamplingInterval::default(),
136            iter_sample_interval: SamplingInterval::default(),
137        }
138    }
139
140    pub fn with_sampling(self, read_interval: SamplingInterval) -> Self {
141        Self {
142            db_name: self.db_name,
143            read_sample_interval: read_interval,
144            write_sample_interval: SamplingInterval::default(),
145            iter_sample_interval: SamplingInterval::default(),
146        }
147    }
148}
149
150const CF_METRICS_REPORT_PERIOD_SECS: u64 = 30;
151
152#[derive(Debug)]
153pub struct Database {
154    pub(crate) storage: Storage,
155    /// Declared right after `storage`: fields are dropped in declaration
156    /// order, so its drop sees RocksDB closed.
157    close_timer: CloseTimer,
158    pub(crate) metric_conf: MetricConf,
159    /// Declared after `storage`: fields are dropped in declaration order, so
160    /// this goes only once RocksDB has closed and released its `LOCK` file.
161    closed: Arc<()>,
162}
163
164/// Records how long a RocksDB database took to close, from the start of
165/// [`Database`]'s drop to the drop of this timer.
166#[derive(Debug)]
167struct CloseTimer {
168    db_name: String,
169    start: Option<Instant>,
170}
171
172impl Drop for CloseTimer {
173    fn drop(&mut self) {
174        let Some(start) = self.start else {
175            return;
176        };
177        let elapsed_ms = start.elapsed().as_millis();
178        DBMetrics::get()
179            .op_metrics
180            .rocksdb_close_duration_ms
181            .with_label_values(&[&self.db_name])
182            .set(elapsed_ms as i64);
183        if elapsed_ms > 100 {
184            let thread = std::thread::current();
185            info!(
186                "Closed RocksDB {} in {elapsed_ms} ms on thread {}",
187                self.db_name,
188                thread.name().unwrap_or("unnamed")
189            );
190        }
191    }
192}
193
194/// What [`wait_for_database_close`] waits on; see [`Database::close_handle`].
195pub struct DatabaseClose(Weak<()>);
196
197impl Drop for Database {
198    fn drop(&mut self) {
199        DBMetrics::get().decrement_num_active_dbs(&self.metric_conf.db_name);
200        if matches!(self.storage, Storage::Rocks(_)) {
201            self.close_timer.start = Some(Instant::now());
202        }
203    }
204}
205
206impl Database {
207    /// A handle for [`wait_for_database_close`]. Take it while the database
208    /// is still open, before its last handle is dropped.
209    pub fn close_handle(&self) -> DatabaseClose {
210        DatabaseClose(Arc::downgrade(&self.closed))
211    }
212
213    pub(crate) fn new(storage: Storage, metric_conf: MetricConf) -> Self {
214        DBMetrics::get().increment_num_active_dbs(&metric_conf.db_name);
215        Self {
216            storage,
217            close_timer: CloseTimer {
218                db_name: metric_conf.db_name.clone(),
219                start: None,
220            },
221            metric_conf,
222            closed: Arc::new(()),
223        }
224    }
225
226    pub(crate) fn get<K: AsRef<[u8]>>(
227        &self,
228        cf: &ColumnFamily,
229        key: K,
230        readopts: &ReadOptions,
231    ) -> Result<Option<GetResult<'_>>, TypedStoreError> {
232        match (&self.storage, cf) {
233            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => Ok(db
234                .underlying
235                .get_pinned_cf_opt(&rocks_cf(db, cf.name())?, key, readopts)
236                .map_err(typed_store_err_from_rocks_err)?
237                .map(GetResult::Rocks)),
238            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => {
239                Ok(db.get(cf_name, key)?.map(GetResult::InMemory))
240            }
241
242            _ => Err(TypedStoreError::RocksDB(
243                "typed store invariant violation".to_string(),
244            )),
245        }
246    }
247
248    pub(crate) fn multi_get<I, K>(
249        &self,
250        cf: &ColumnFamily,
251        keys: I,
252        readopts: &ReadOptions,
253    ) -> Vec<Result<Option<GetResult<'_>>, TypedStoreError>>
254    where
255        I: IntoIterator<Item = K>,
256        K: AsRef<[u8]>,
257    {
258        match (&self.storage, cf) {
259            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => {
260                let keys_vec: Vec<K> = keys.into_iter().collect();
261                let handle = match rocks_cf(db, cf.name()) {
262                    Ok(handle) => handle,
263                    // Fail every key, so the result keeps one slot per key.
264                    Err(e) => return keys_vec.iter().map(|_| Err(e.clone())).collect(),
265                };
266                let res = db.underlying.batched_multi_get_cf_opt(
267                    &handle,
268                    keys_vec.iter(),
269                    // sorted_input
270                    false,
271                    readopts,
272                );
273                res.into_iter()
274                    .map(|r| {
275                        r.map_err(typed_store_err_from_rocks_err)
276                            .map(|item| item.map(GetResult::Rocks))
277                    })
278                    .collect()
279            }
280            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => db
281                .multi_get(cf_name, keys)
282                .into_iter()
283                .map(|r| r.map(|value| value.map(GetResult::InMemory)))
284                .collect(),
285            _ => unreachable!("typed store invariant violation"),
286        }
287    }
288
289    pub fn cf_handle(&self, name: &str) -> Option<()> {
290        match &self.storage {
291            Storage::Rocks(db) => db.underlying.cf_handle(name).map(|_| ()),
292            Storage::InMemory(db) => db.has_cf(name).then_some(()),
293        }
294    }
295
296    /// Creates a new column family at runtime. Fails if a column family with
297    /// this name already exists.
298    ///
299    /// `options` hold until the database is next opened, after which a
300    /// column family the caller does not declare is opened with the
301    /// crate's options instead. Declare it to keep them.
302    #[instrument(level = "debug", skip(self, options), err)]
303    pub fn create_cf(&self, name: &str, options: &rocksdb::Options) -> Result<(), TypedStoreError> {
304        match &self.storage {
305            Storage::Rocks(db) => nondeterministic!(db.underlying.create_cf(name, options))
306                .map_err(typed_store_err_from_rocks_err),
307            Storage::InMemory(db) => db.create_cf(name),
308        }
309    }
310
311    /// Maps still holding the column family keep working but report
312    /// [`TypedStoreError::UnregisteredColumn`] on every operation.
313    #[instrument(level = "debug", skip(self), err)]
314    pub fn drop_cf(&self, name: &str) -> Result<(), TypedStoreError> {
315        if name == rocksdb::DEFAULT_COLUMN_FAMILY_NAME {
316            // rocksdb refuses this, but not before its wrapper has taken the
317            // handle out of its own map, losing it for the rest of the process.
318            return Err(TypedStoreError::RocksDB(format!(
319                "the {name} column family cannot be dropped"
320            )));
321        }
322        match &self.storage {
323            Storage::Rocks(db) => {
324                // RocksDB deletes a dropped column family's files once its
325                // last handle is released. Holding one across the drop moves
326                // that past the drop, which blocks every column family lookup
327                // of this database while it runs.
328                let handle = db.underlying.cf_handle(name);
329                let dropped = nondeterministic!(db.underlying.drop_cf(name))
330                    .map_err(typed_store_err_from_rocks_err);
331                drop(handle);
332                if dropped.is_ok() {
333                    DBMetrics::get().remove_column_family(name);
334                }
335                dropped
336            }
337            Storage::InMemory(db) => {
338                db.drop_cf(name);
339                Ok(())
340            }
341        }
342    }
343
344    pub(crate) fn delete_cf<K: AsRef<[u8]>>(
345        &self,
346        cf: &ColumnFamily,
347        key: K,
348    ) -> Result<(), TypedStoreError> {
349        fail_point!("delete-cf-before");
350        let ret = match (&self.storage, cf) {
351            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => {
352                rocks_cf(db, cf.name()).and_then(|handle| {
353                    db.underlying
354                        .delete_cf(&handle, key)
355                        .map_err(typed_store_err_from_rocks_err)
356                })
357            }
358            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => {
359                db.delete(cf_name, key.as_ref())
360            }
361            _ => Err(TypedStoreError::RocksDB(
362                "typed store invariant violation".to_string(),
363            )),
364        };
365        fail_point!("delete-cf-after");
366        #[allow(clippy::let_and_return)]
367        ret
368    }
369
370    pub fn path_for_pruning(&self) -> &Path {
371        match &self.storage {
372            Storage::Rocks(rocks) => rocks.underlying.path(),
373            _ => unimplemented!("method is only supported for rocksdb backend"),
374        }
375    }
376
377    pub(crate) fn put_cf(
378        &self,
379        cf: &ColumnFamily,
380        key: Vec<u8>,
381        value: Vec<u8>,
382    ) -> Result<(), TypedStoreError> {
383        fail_point!("put-cf-before");
384        let ret = match (&self.storage, cf) {
385            (Storage::Rocks(db), ColumnFamily::Rocks(_)) => {
386                rocks_cf(db, cf.name()).and_then(|handle| {
387                    db.underlying
388                        .put_cf(&handle, key, value)
389                        .map_err(typed_store_err_from_rocks_err)
390                })
391            }
392            (Storage::InMemory(db), ColumnFamily::InMemory(cf_name)) => db.put(cf_name, key, value),
393            _ => Err(TypedStoreError::RocksDB(
394                "typed store invariant violation".to_string(),
395            )),
396        };
397        fail_point!("put-cf-after");
398        #[allow(clippy::let_and_return)]
399        ret
400    }
401
402    pub(crate) fn key_may_exist_cf<K: AsRef<[u8]>>(
403        &self,
404        cf: &ColumnFamily,
405        key: K,
406        readopts: &ReadOptions,
407    ) -> bool {
408        match &self.storage {
409            // [`rocksdb::DBWithThreadMode::key_may_exist_cf`] can have false positives,
410            // but no false negatives. We use it to short-circuit the absent case
411            Storage::Rocks(rocks) => match rocks_cf(rocks, cf.name()) {
412                Ok(handle) => rocks
413                    .underlying
414                    .key_may_exist_cf_opt(&handle, key, readopts),
415                // Not a definitive absence: let the real read report it.
416                Err(_) => true,
417            },
418            _ => true,
419        }
420    }
421
422    /// Flush the memtable of a single column family to SST files on disk.
423    pub(crate) fn flush_cf(&self, cf: &ColumnFamily) -> Result<(), TypedStoreError> {
424        match &self.storage {
425            // A flush blocks on RocksDB background threads; under the simulator it
426            // must run off the test thread, like the opens in `rocks/mod.rs`, or
427            // real flush durations leak into the simulated schedule. No-op outside
428            // msim.
429            Storage::Rocks(rocks) => nondeterministic!({
430                let cf_name = cf.name();
431                // Deliberately not `rocks_cf`: flushing a column family
432                // dropped in the meantime is a no-op, not an error.
433                if let Some(handle) = rocks.underlying.cf_handle(cf_name) {
434                    rocks.underlying.flush_cf(&handle).map_err(|e| {
435                        TypedStoreError::RocksDB(format!(
436                            "Failed to flush column family {cf_name}: {e}"
437                        ))
438                    })?;
439                }
440                Ok(())
441            }),
442            // InMemory databases don't need flushing.
443            Storage::InMemory(_) => Ok(()),
444        }
445    }
446
447    /// Flush the memtables of every column family of the database to SST files
448    /// on disk.
449    pub fn flush_all(&self) -> Result<(), TypedStoreError> {
450        match &self.storage {
451            // See `flush_cf` for why the flushes run off the test thread under
452            // the simulator.
453            Storage::Rocks(rocks) => nondeterministic!({
454                for cf_name in rocks.cf_names().map_err(|e| {
455                    TypedStoreError::RocksDB(format!(
456                        "Failed to list column families of {}: {e}",
457                        rocks.underlying.path().display()
458                    ))
459                })? {
460                    if let Some(cf) = rocks.underlying.cf_handle(&cf_name) {
461                        rocks.underlying.flush_cf(&cf).map_err(|e| {
462                            TypedStoreError::RocksDB(format!(
463                                "Failed to flush column family {cf_name}: {e}"
464                            ))
465                        })?;
466                    }
467                }
468                Ok(())
469            }),
470            // InMemory databases don't need flushing.
471            Storage::InMemory(_) => Ok(()),
472        }
473    }
474
475    pub fn write_opt(
476        &self,
477        batch: StorageWriteBatch,
478        write_options: &rocksdb::WriteOptions,
479    ) -> Result<(), TypedStoreError> {
480        fail_point!("batch-write-before");
481        let ret = match (&self.storage, batch) {
482            (Storage::Rocks(rocks), StorageWriteBatch::Rocks(batch)) => rocks
483                .underlying
484                .write_opt(batch, write_options)
485                .map_err(typed_store_err_from_rocks_err),
486            (Storage::InMemory(db), StorageWriteBatch::InMemory(batch)) => {
487                // InMemory doesn't support write options.
488                db.write(batch)
489            }
490            _ => Err(TypedStoreError::RocksDB(
491                "using invalid batch type for the database".to_string(),
492            )),
493        };
494        fail_point!("batch-write-after");
495
496        #[allow(clippy::let_and_return)]
497        ret
498    }
499
500    pub(crate) fn compact_range_cf<K: AsRef<[u8]>>(
501        &self,
502        cf: &ColumnFamily,
503        start: Option<K>,
504        end: Option<K>,
505    ) -> Result<(), TypedStoreError> {
506        if let Storage::Rocks(rocksdb) = &self.storage {
507            let handle = rocks_cf(rocksdb, cf.name())?;
508            rocksdb.underlying.compact_range_cf(&handle, start, end);
509        }
510        Ok(())
511    }
512
513    /// How many sorted runs a point lookup in the column family `cf_name` may
514    /// probe: one per level-0 file and one per other level holding files. `0`
515    /// for a column family that does not exist and on the in-memory backend.
516    pub fn sorted_runs(&self, cf_name: &str) -> Result<u64, TypedStoreError> {
517        Ok(self
518            .files_per_level(cf_name)?
519            .iter()
520            .enumerate()
521            .map(|(level, &files)| {
522                if level == 0 {
523                    files
524                } else {
525                    u64::from(files > 0)
526                }
527            })
528            .sum())
529    }
530
531    /// How many SST files the column family `cf_name` has. `0` for a column
532    /// family that does not exist and on the in-memory backend.
533    pub fn sst_file_count(&self, cf_name: &str) -> Result<u64, TypedStoreError> {
534        Ok(self.files_per_level(cf_name)?.iter().sum())
535    }
536
537    /// The number of SST files on each level of the column family `cf_name`.
538    fn files_per_level(&self, cf_name: &str) -> Result<Vec<u64>, TypedStoreError> {
539        let Storage::Rocks(rocks) = &self.storage else {
540            return Ok(Vec::new());
541        };
542        let Some(handle) = rocks.underlying.cf_handle(cf_name) else {
543            return Ok(Vec::new());
544        };
545        let mut levels = Vec::new();
546        // The property is absent for the levels past the column family's
547        // last one.
548        for level in 0.. {
549            let Some(files) = rocks
550                .underlying
551                .property_value_cf(&handle, &format!("rocksdb.num-files-at-level{level}"))
552                .map_err(typed_store_err_from_rocks_err)?
553            else {
554                break;
555            };
556            levels.push(files.trim().parse().map_err(|e| {
557                TypedStoreError::RocksDB(format!(
558                    "the file count of level {level} of {cf_name} is not a number: {e}"
559                ))
560            })?);
561        }
562        Ok(levels)
563    }
564
565    /// The size of the SST files of the column family `cf_name`, which a
566    /// compaction of all of them needs again in free disk space while it runs.
567    /// `0` for a column family that does not exist and on the in-memory
568    /// backend.
569    pub fn sst_files_size(&self, cf_name: &str) -> Result<u64, TypedStoreError> {
570        let Storage::Rocks(rocks) = &self.storage else {
571            return Ok(0);
572        };
573        let Some(handle) = rocks.underlying.cf_handle(cf_name) else {
574            return Ok(0);
575        };
576        Ok(rocks
577            .underlying
578            .property_int_value_cf(&handle, rocksdb::properties::TOTAL_SST_FILES_SIZE)
579            .map_err(typed_store_err_from_rocks_err)?
580            .unwrap_or(0))
581    }
582
583    /// Compacts the whole column family `cf_name` into a single sorted run,
584    /// flushing its memtable first. Blocks until done. Other column families
585    /// keep compacting meanwhile. Does nothing on the in-memory backend.
586    pub fn compact_cf(&self, cf_name: &str) -> Result<(), TypedStoreError> {
587        if let Storage::Rocks(rocks) = &self.storage {
588            let handle = rocks_cf(rocks, cf_name)?;
589            let mut options = rocksdb::CompactOptions::default();
590            options.set_exclusive_manual_compaction(false);
591            options.set_bottommost_level_compaction(rocksdb::BottommostLevelCompaction::Force);
592            nondeterministic!(rocks.underlying.compact_range_cf_opt(
593                &handle,
594                None::<&[u8]>,
595                None::<&[u8]>,
596                &options
597            ));
598        }
599        Ok(())
600    }
601
602    /// A point-in-time snapshot of this database. See [`DbSnapshot`] for what
603    /// holding one costs.
604    ///
605    /// # Panics
606    ///
607    /// Panics on the in-memory backend, which has no point-in-time reads.
608    pub fn snapshot(&self) -> DbSnapshot<'_> {
609        match &self.storage {
610            Storage::Rocks(rocks) => DbSnapshot {
611                snapshot: rocks.underlying.snapshot(),
612            },
613            Storage::InMemory(_) => unimplemented!("method is only supported for rocksdb backend"),
614        }
615    }
616
617    pub fn get_sampling_interval(&self) -> SamplingInterval {
618        self.metric_conf.read_sample_interval.new_from_self()
619    }
620
621    pub fn multiget_sampling_interval(&self) -> SamplingInterval {
622        self.metric_conf.read_sample_interval.new_from_self()
623    }
624
625    pub fn write_sampling_interval(&self) -> SamplingInterval {
626        self.metric_conf.write_sample_interval.new_from_self()
627    }
628
629    pub fn iter_sampling_interval(&self) -> SamplingInterval {
630        self.metric_conf.iter_sample_interval.new_from_self()
631    }
632
633    pub(crate) fn db_name(&self) -> String {
634        let name = &self.metric_conf.db_name;
635        if name.is_empty() {
636            "default".to_string()
637        } else {
638            name.clone()
639        }
640    }
641
642    pub fn live_files(&self) -> Result<Vec<LiveFile>, Error> {
643        match &self.storage {
644            Storage::Rocks(rocks) => rocks.underlying.live_files(),
645            _ => Ok(vec![]),
646        }
647    }
648
649    pub(crate) fn try_catch_up_with_primary(&self) -> Result<(), TypedStoreError> {
650        if let Storage::Rocks(rocks) = &self.storage {
651            rocks
652                .underlying
653                .try_catch_up_with_primary()
654                .map_err(typed_store_err_from_rocks_err)?;
655        }
656        Ok(())
657    }
658}
659
660fn rocks_cf_from_db<'a>(
661    db: &'a Database,
662    cf_name: &str,
663) -> Result<Arc<rocksdb::BoundColumnFamily<'a>>, TypedStoreError> {
664    match &db.storage {
665        Storage::Rocks(rocksdb) => rocks_cf(rocksdb, cf_name),
666        _ => Err(TypedStoreError::RocksDB(
667            "using invalid batch type for the database".to_string(),
668        )),
669    }
670}
671
672/// An interface to a rocksDB database, keyed by a columnfamily
673#[derive(Clone, Debug)]
674pub struct DBMap<K, V> {
675    pub db: Arc<Database>,
676    _phantom: PhantomData<fn(K) -> V>,
677    column_family: ColumnFamily,
678    pub opts: ReadWriteOptions,
679    db_metrics: Arc<DBMetrics>,
680    get_sample_interval: SamplingInterval,
681    multiget_sample_interval: SamplingInterval,
682    write_sample_interval: SamplingInterval,
683    iter_sample_interval: SamplingInterval,
684    _metrics_task_cancel_handle: Arc<oneshot::Sender<()>>,
685    /// What the per-operation metrics are labelled with; the column family
686    /// name unless [`Self::with_metrics_label`] set another.
687    metrics_label: Arc<str>,
688}
689
690impl<K, V> DBMap<K, V> {
691    pub(crate) fn new(
692        db: Arc<Database>,
693        opts: &ReadWriteOptions,
694        column_family: ColumnFamily,
695        skip_metrics_reporting: bool,
696    ) -> Self {
697        let db_cloned = Arc::downgrade(&db);
698        let db_metrics = DBMetrics::get();
699        let db_metrics_cloned = db_metrics.clone();
700        let cf = column_family.name().to_string();
701
702        let (sender, mut recv) = tokio::sync::oneshot::channel();
703        if !skip_metrics_reporting && matches!(db.storage, Storage::Rocks(_)) {
704            tokio::task::spawn(async move {
705                let mut interval =
706                    tokio::time::interval(Duration::from_secs(CF_METRICS_REPORT_PERIOD_SECS));
707                loop {
708                    tokio::select! {
709                        _ = interval.tick() => {
710                            if let Some(db) = db_cloned.upgrade() {
711                                let cf = cf.clone();
712                                let db_metrics = db_metrics.clone();
713                                if let Err(e) = tokio::task::spawn_blocking(move || {
714                                    Self::report_rocksdb_metrics(&db, &cf, &db_metrics);
715                                }).await {
716                                    error!("Failed to log metrics with error: {}", e);
717                                }
718                            } else {
719                                break;
720                            }
721                        }
722                        _ = &mut recv => break,
723                    }
724                }
725                debug!("Returning the cf metric logging task for DBMap: {}", &cf);
726            });
727        }
728        let metrics_label = Arc::from(column_family.name());
729        DBMap {
730            db: db.clone(),
731            opts: opts.clone(),
732            _phantom: PhantomData,
733            column_family,
734            metrics_label,
735            db_metrics: db_metrics_cloned,
736            _metrics_task_cancel_handle: Arc::new(sender),
737            get_sample_interval: db.get_sampling_interval(),
738            multiget_sample_interval: db.multiget_sampling_interval(),
739            write_sample_interval: db.write_sampling_interval(),
740            iter_sample_interval: db.iter_sampling_interval(),
741        }
742    }
743
744    /// Reopens an open database as a typed map operating under a specific
745    /// column family. if no column family is passed, the default column
746    /// family is used.
747    ///
748    /// When `skip_metrics_reporting` is true, no periodic per-column-family
749    /// metrics task is spawned; use this for deprecated tables and for large
750    /// sets of rarely-touched column families.
751    #[instrument(level = "debug", skip(db), err)]
752    pub fn reopen(
753        db: &Arc<Database>,
754        opt_cf: Option<&str>,
755        rw_options: &ReadWriteOptions,
756        skip_metrics_reporting: bool,
757    ) -> Result<Self, TypedStoreError> {
758        let cf_key = opt_cf
759            .unwrap_or(rocksdb::DEFAULT_COLUMN_FAMILY_NAME)
760            .to_owned();
761        if db.cf_handle(&cf_key).is_none() {
762            return Err(TypedStoreError::UnregisteredColumn(cf_key));
763        }
764
765        let column_family = match &db.storage {
766            Storage::Rocks(_) => ColumnFamily::Rocks(cf_key),
767            Storage::InMemory(_) => ColumnFamily::InMemory(cf_key),
768        };
769        Ok(DBMap::new(
770            db.clone(),
771            rw_options,
772            column_family,
773            skip_metrics_reporting,
774        ))
775    }
776
777    /// Labels the per-operation metrics with `label` instead of the column
778    /// family name, so that the column families of one store, such as one per
779    /// epoch, share their series.
780    pub fn with_metrics_label(mut self, label: &str) -> Self {
781        self.metrics_label = Arc::from(label);
782        self
783    }
784
785    /// What the per-operation metrics are labelled with.
786    pub fn metrics_label(&self) -> &str {
787        &self.metrics_label
788    }
789
790    pub fn cf_name(&self) -> &str {
791        self.column_family.name()
792    }
793
794    pub fn batch(&self) -> DBBatch {
795        let batch = match &self.db.storage {
796            Storage::Rocks(_) => StorageWriteBatch::Rocks(WriteBatch::default()),
797            Storage::InMemory(_) => StorageWriteBatch::InMemory(InMemoryBatch::default()),
798        };
799        DBBatch::new(
800            &self.db,
801            batch,
802            &self.db_metrics,
803            &self.write_sample_interval,
804        )
805    }
806
807    /// Moves the SST files at `paths`, written by
808    /// [`SstFileBuffer::write_file`](crate::rocks::SstFileBuffer::write_file)
809    /// with this column family's options, into this table. The files may
810    /// overlap each other; a key in several of them keeps its value from the
811    /// last.
812    ///
813    /// # Panics
814    ///
815    /// Panics on the in-memory backend.
816    pub fn ingest_sst_files(&self, paths: &[PathBuf]) -> Result<(), TypedStoreError> {
817        if paths.is_empty() {
818            return Ok(());
819        }
820        match &self.db.storage {
821            // Ingestion can wait on a memtable flush; see `Database::flush_cf`
822            // for why that runs off the test thread under the simulator.
823            Storage::Rocks(rocks) => nondeterministic!({
824                let handle = rocks_cf(rocks, self.cf_name())?;
825                let mut options = rocksdb::IngestExternalFileOptions::default();
826                options.set_move_files(true);
827                rocks
828                    .underlying
829                    .ingest_external_file_cf_opts(&handle, &options, paths.to_vec())
830                    .map_err(typed_store_err_from_rocks_err)
831            }),
832            Storage::InMemory(_) => unimplemented!("method is only supported for rocksdb backend"),
833        }
834    }
835
836    /// Flush the memtable of this table's column family to SST files on disk.
837    pub fn flush(&self) -> Result<(), TypedStoreError> {
838        self.db.flush_cf(&self.column_family)
839    }
840
841    /// Flush the memtables of every column family of the database to SST files
842    /// on disk.
843    pub fn flush_all(&self) -> Result<(), TypedStoreError> {
844        self.db.flush_all()
845    }
846
847    pub fn compact_range<J: Serialize>(&self, start: &J, end: &J) -> Result<(), TypedStoreError> {
848        let from_buf = be_fix_int_ser(start);
849        let to_buf = be_fix_int_ser(end);
850        self.db
851            .compact_range_cf(&self.column_family, Some(from_buf), Some(to_buf))
852    }
853
854    pub fn compact_range_raw(
855        &self,
856        cf_name: &str,
857        start: Vec<u8>,
858        end: Vec<u8>,
859    ) -> Result<(), TypedStoreError> {
860        let cf = match &self.db.storage {
861            Storage::Rocks(_) => ColumnFamily::Rocks(cf_name.to_string()),
862            Storage::InMemory(_) => ColumnFamily::InMemory(cf_name.to_string()),
863        };
864        self.db.compact_range_cf(&cf, Some(start), Some(end))
865    }
866
867    /// Returns a vector of raw values corresponding to the keys provided.
868    fn multi_get_pinned(
869        &self,
870        keys_bytes: impl IntoIterator<Item = Vec<u8>>,
871    ) -> Result<Vec<Option<GetResult<'_>>>, TypedStoreError> {
872        let _timer = self
873            .db_metrics
874            .op_metrics
875            .rocksdb_multiget_latency_seconds
876            .with_label_values(&[self.metrics_label()])
877            .start_timer();
878        let perf_ctx = if self.multiget_sample_interval.sample() {
879            Some(RocksDBPerfContext)
880        } else {
881            None
882        };
883        let results: Result<Vec<_>, TypedStoreError> = self
884            .db
885            .multi_get(&self.column_family, keys_bytes, &self.opts.readopts())
886            .into_iter()
887            .collect();
888        let entries = results?;
889        let entry_size = entries
890            .iter()
891            .flatten()
892            .map(|entry| entry.len())
893            .sum::<usize>();
894        self.db_metrics
895            .op_metrics
896            .rocksdb_multiget_bytes
897            .with_label_values(&[self.metrics_label()])
898            .observe(entry_size as f64);
899        if perf_ctx.is_some() {
900            self.db_metrics
901                .read_perf_ctx_metrics
902                .report_metrics(self.metrics_label());
903        }
904        Ok(entries)
905    }
906
907    pub fn table_summary(&self) -> eyre::Result<TableSummary>
908    where
909        K: Serialize + DeserializeOwned,
910        V: Serialize + DeserializeOwned,
911    {
912        let mut num_keys = 0;
913        let mut key_bytes_total = 0;
914        let mut value_bytes_total = 0;
915        let mut key_hist = hdrhistogram::Histogram::<u64>::new_with_max(100000, 2).unwrap();
916        let mut value_hist = hdrhistogram::Histogram::<u64>::new_with_max(100000, 2).unwrap();
917        for item in self.safe_iter() {
918            let (key, value) = item?;
919            num_keys += 1;
920            let key_len = be_fix_int_ser(key.borrow()).len();
921            let value_len = bcs::to_bytes(value.borrow())?.len();
922            key_bytes_total += key_len;
923            value_bytes_total += value_len;
924            key_hist.record(key_len as u64)?;
925            value_hist.record(value_len as u64)?;
926        }
927        Ok(TableSummary {
928            num_keys,
929            key_bytes_total,
930            value_bytes_total,
931            key_hist,
932            value_hist,
933        })
934    }
935
936    // Creates metrics and context for tracking an iterator usage and performance.
937    fn create_iter_context(
938        &self,
939    ) -> (
940        Option<HistogramTimer>,
941        Option<Histogram>,
942        Option<Histogram>,
943        Option<RocksDBPerfContext>,
944    ) {
945        let timer = self
946            .db_metrics
947            .op_metrics
948            .rocksdb_iter_latency_seconds
949            .with_label_values(&[self.metrics_label()])
950            .start_timer();
951        let bytes_scanned = self
952            .db_metrics
953            .op_metrics
954            .rocksdb_iter_bytes
955            .with_label_values(&[self.metrics_label()]);
956        let keys_scanned = self
957            .db_metrics
958            .op_metrics
959            .rocksdb_iter_keys
960            .with_label_values(&[self.metrics_label()]);
961        let perf_ctx = if self.iter_sample_interval.sample() {
962            Some(RocksDBPerfContext)
963        } else {
964            None
965        };
966        (
967            Some(timer),
968            Some(bytes_scanned),
969            Some(keys_scanned),
970            perf_ctx,
971        )
972    }
973
974    /// Shared rocksdb `SafeIter` construction (raw iterator + scan metrics)
975    /// used by both the forward and reverse raw iterators.
976    fn rocks_safe_iter<'a>(
977        &self,
978        db: &'a RocksDB,
979        readopts: ReadOptions,
980    ) -> Result<SafeIter<'a, K, V>, TypedStoreError>
981    where
982        K: DeserializeOwned,
983        V: DeserializeOwned,
984    {
985        let db_iter = db
986            .underlying
987            .raw_iterator_cf_opt(&rocks_cf(db, self.column_family.name())?, readopts);
988        let (_timer, bytes_scanned, keys_scanned, _perf_ctx) = self.create_iter_context();
989        Ok(SafeIter::new(
990            self.metrics_label().to_string(),
991            db_iter,
992            _timer,
993            _perf_ctx,
994            bytes_scanned,
995            keys_scanned,
996            Some(self.db_metrics.clone()),
997        ))
998    }
999
1000    /// Iterates the whole column family as of `db_snapshot` instead of the
1001    /// current state of the database.
1002    ///
1003    /// The blocks it reads are not added to the block cache.
1004    pub fn safe_iter_at_snapshot<'a>(
1005        &'a self,
1006        db_snapshot: &'a DbSnapshot<'a>,
1007    ) -> DbIterator<'a, (K, V)>
1008    where
1009        K: DeserializeOwned,
1010        V: DeserializeOwned,
1011    {
1012        match &self.db.storage {
1013            Storage::Rocks(db) => {
1014                let mut readopts = self.opts.readopts();
1015                readopts.fill_cache(false);
1016                readopts.set_snapshot(&db_snapshot.snapshot);
1017                match self.rocks_safe_iter(db, readopts) {
1018                    Ok(iter) => Box::new(iter),
1019                    Err(e) => error_iterator(e),
1020                }
1021            }
1022            Storage::InMemory(_) => {
1023                unreachable!("a DbSnapshot is only created over the rocksdb backend")
1024            }
1025        }
1026    }
1027
1028    /// Forward iterator over the raw byte bounds `[lower_bound, upper_bound)`;
1029    /// both bounds (already serialized, `upper_bound` exclusive) are applied to
1030    /// the read options.
1031    fn iter_forward_raw(
1032        &self,
1033        lower_bound: Option<Vec<u8>>,
1034        upper_bound: Option<Vec<u8>>,
1035    ) -> DbIterator<'_, (K, V)>
1036    where
1037        K: DeserializeOwned,
1038        V: DeserializeOwned,
1039    {
1040        match &self.db.storage {
1041            Storage::Rocks(db) => {
1042                let readopts =
1043                    rocks_util::iterator_read_options(&self.opts, lower_bound, upper_bound, false);
1044                match self.rocks_safe_iter(db, readopts) {
1045                    Ok(iter) => Box::new(iter),
1046                    Err(e) => error_iterator(e),
1047                }
1048            }
1049            Storage::InMemory(db) => {
1050                db.iterator(self.column_family.name(), lower_bound, upper_bound, false)
1051            }
1052        }
1053    }
1054
1055    /// Reverse counterpart of [`Self::iter_forward_raw`], yielding the same
1056    /// keys in descending order. Only the lower bound is applied to the
1057    /// read options; the (exclusive) `upper_bound` is enforced by
1058    /// [`SafeRevIter`]'s initial seek, because setting an
1059    /// iterate-upper-bound would stop `seek_for_prev` from landing on the
1060    /// boundary key.
1061    fn iter_reversed_raw(
1062        &self,
1063        lower_bound: Option<Vec<u8>>,
1064        upper_bound: Option<Vec<u8>>,
1065    ) -> DbIterator<'_, (K, V)>
1066    where
1067        K: DeserializeOwned,
1068        V: DeserializeOwned,
1069    {
1070        match &self.db.storage {
1071            Storage::Rocks(db) => {
1072                let readopts = rocks_util::iterator_read_options(
1073                    &self.opts,
1074                    lower_bound,
1075                    upper_bound.clone(),
1076                    true,
1077                );
1078                match self.rocks_safe_iter(db, readopts) {
1079                    Ok(iter) => Box::new(SafeRevIter::new(iter, upper_bound)),
1080                    Err(e) => error_iterator(e),
1081                }
1082            }
1083            Storage::InMemory(db) => {
1084                db.iterator(self.column_family.name(), lower_bound, upper_bound, true)
1085            }
1086        }
1087    }
1088
1089    /// Forward iterator over every entry whose key begins with `prefix`.
1090    ///
1091    /// `prefix` is serialized with `be_fix_int_ser` and must form a prefix of
1092    /// the column family's key encoding — typically the leading field(s) of a
1093    /// tuple key. This avoids constructing artificial maximum keys to bound a
1094    /// composite-key scan.
1095    pub fn safe_iter_with_prefix<P>(&self, prefix: &P) -> DbIterator<'_, (K, V)>
1096    where
1097        P: ?Sized + Serialize,
1098        K: DeserializeOwned,
1099        V: DeserializeOwned,
1100    {
1101        let (lower_bound, upper_bound) = prefix_iterator_bounds(prefix);
1102        self.iter_forward_raw(lower_bound, upper_bound)
1103    }
1104
1105    /// Forward iterator over entries whose key begins with `prefix`, starting
1106    /// at the position `lower` gives within the prefix rather than at the
1107    /// first key under the prefix.
1108    ///
1109    /// The bound value is **not** a full key: it is the entire remainder of
1110    /// the key that follows `prefix` (all the trailing fields of a tuple key,
1111    /// not a partial suffix). Both `prefix` and the bound value are
1112    /// serialized with `be_fix_int_ser` and concatenated, mirroring how a
1113    /// composite key is encoded. `Included` starts the scan at
1114    /// `prefix ++ lower`, `Excluded` strictly after that position (also when
1115    /// no such key exists), and `Unbounded` at the first key under the
1116    /// prefix. The scan bounds never leave the prefix (excluding the
1117    /// maximum remainder yields an empty scan, not the next prefix's keys),
1118    /// so a paginated scan can resume from a cursor without an artificial
1119    /// maximum key for the upper bound.
1120    pub fn safe_iter_with_prefix_from<P, C>(
1121        &self,
1122        prefix: &P,
1123        lower: Bound<&C>,
1124    ) -> DbIterator<'_, (K, V)>
1125    where
1126        P: ?Sized + Serialize,
1127        C: ?Sized + Serialize,
1128        K: DeserializeOwned,
1129        V: DeserializeOwned,
1130    {
1131        let (lower_bound, upper_bound) =
1132            prefix_iterator_bounds_with_range::<P, C>(prefix, (lower, Bound::Unbounded));
1133        self.iter_forward_raw(lower_bound, upper_bound)
1134    }
1135
1136    /// Forward iterator over entries whose key begins with `prefix`, resuming
1137    /// strictly after `cursor`, or from the first key under the prefix when
1138    /// there is no cursor. `cursor` is the remainder of the key after
1139    /// `prefix`, as for [`Self::safe_iter_with_prefix_from`].
1140    pub fn safe_iter_with_prefix_after<P, C>(
1141        &self,
1142        prefix: &P,
1143        cursor: Option<&C>,
1144    ) -> DbIterator<'_, (K, V)>
1145    where
1146        P: ?Sized + Serialize,
1147        C: ?Sized + Serialize,
1148        K: DeserializeOwned,
1149        V: DeserializeOwned,
1150    {
1151        self.safe_iter_with_prefix_from(prefix, cursor.map_or(Bound::Unbounded, Bound::Excluded))
1152    }
1153
1154    /// Reverse counterpart of [`Self::safe_iter_with_prefix`]: the matching
1155    /// entries in descending key order (e.g. for "latest entry under a
1156    /// prefix").
1157    pub fn safe_iter_with_prefix_reversed<P>(&self, prefix: &P) -> DbIterator<'_, (K, V)>
1158    where
1159        P: ?Sized + Serialize,
1160        K: DeserializeOwned,
1161        V: DeserializeOwned,
1162    {
1163        let (lower_bound, upper_bound) = prefix_iterator_bounds(prefix);
1164        self.iter_reversed_raw(lower_bound, upper_bound)
1165    }
1166}
1167
1168/// Provides a mutable struct to form a collection of database write operations,
1169/// and execute them.
1170///
1171/// Batching write and delete operations is faster than performing them one by
1172/// one and ensures their atomicity,  ie. they are all written or none is.
1173/// This is also true of operations across column families in the same database.
1174///
1175/// Serializations / Deserialization, and naming of column families is performed
1176/// by passing a DBMap<K,V> with each operation.
1177///
1178/// ```
1179/// use core::fmt::Error;
1180/// use std::sync::Arc;
1181///
1182/// use prometheus_filtered::Registry;
1183/// use tempfile::tempdir;
1184/// use typed_store::{Map, metrics::DBMetrics, rocks::*};
1185///
1186/// #[tokio::main(flavor = "current_thread")]
1187/// async fn main() -> Result<(), Error> {
1188///     let rocks = open_cf_opts(
1189///         tempfile::tempdir().unwrap(),
1190///         None,
1191///         MetricConf::default(),
1192///         &[
1193///             ("First_CF", rocksdb::Options::default()),
1194///             ("Second_CF", rocksdb::Options::default()),
1195///         ],
1196///     )
1197///     .unwrap();
1198///
1199///     let db_cf_1 = DBMap::reopen(
1200///         &rocks,
1201///         Some("First_CF"),
1202///         &ReadWriteOptions::default(),
1203///         false,
1204///     )
1205///     .expect("Failed to open storage");
1206///     let keys_vals_1 = (1..100).map(|i| (i, i.to_string()));
1207///
1208///     let db_cf_2 = DBMap::reopen(
1209///         &rocks,
1210///         Some("Second_CF"),
1211///         &ReadWriteOptions::default(),
1212///         false,
1213///     )
1214///     .expect("Failed to open storage");
1215///     let keys_vals_2 = (1000..1100).map(|i| (i, i.to_string()));
1216///
1217///     let mut batch = db_cf_1.batch();
1218///     batch
1219///         .insert_batch(&db_cf_1, keys_vals_1.clone())
1220///         .expect("Failed to batch insert")
1221///         .insert_batch(&db_cf_2, keys_vals_2.clone())
1222///         .expect("Failed to batch insert");
1223///
1224///     let _ = batch.write().expect("Failed to execute batch");
1225///     for (k, v) in keys_vals_1 {
1226///         let val = db_cf_1.get(&k).expect("Failed to get inserted key");
1227///         assert_eq!(Some(v), val);
1228///     }
1229///
1230///     for (k, v) in keys_vals_2 {
1231///         let val = db_cf_2.get(&k).expect("Failed to get inserted key");
1232///         assert_eq!(Some(v), val);
1233///     }
1234///     Ok(())
1235/// }
1236/// ```
1237pub struct DBBatch {
1238    database: Arc<Database>,
1239    batch: StorageWriteBatch,
1240    db_metrics: Arc<DBMetrics>,
1241    write_sample_interval: SamplingInterval,
1242}
1243
1244impl DBBatch {
1245    /// Create a new batch associated with a DB reference.
1246    ///
1247    /// Use `open_cf` to get the DB reference or an existing open database.
1248    pub fn new(
1249        dbref: &Arc<Database>,
1250        batch: StorageWriteBatch,
1251        db_metrics: &Arc<DBMetrics>,
1252        write_sample_interval: &SamplingInterval,
1253    ) -> Self {
1254        DBBatch {
1255            database: dbref.clone(),
1256            batch,
1257            db_metrics: db_metrics.clone(),
1258            write_sample_interval: write_sample_interval.clone(),
1259        }
1260    }
1261
1262    /// Consume the batch and write its operations to the database
1263    #[instrument(level = "trace", skip_all, err)]
1264    pub fn write(self) -> Result<(), TypedStoreError> {
1265        self.write_opt(&rocksdb::WriteOptions::default())
1266    }
1267
1268    /// Consume the batch and write its operations to the database with custom
1269    /// write options.
1270    ///
1271    /// With default options, an entry whose column family was dropped
1272    /// between staging and this write fails the whole write with a fatal
1273    /// RocksDB background error. Stores that drop column families at
1274    /// runtime must pass [`drop_tolerant_write_options`].
1275    #[instrument(level = "trace", skip_all, err)]
1276    pub fn write_opt(self, write_options: &rocksdb::WriteOptions) -> Result<(), TypedStoreError> {
1277        let db_name = self.database.db_name();
1278        let timer = self
1279            .db_metrics
1280            .op_metrics
1281            .rocksdb_batch_commit_latency_seconds
1282            .with_label_values(&[&db_name])
1283            .start_timer();
1284        let batch_size_bytes = self.size_in_bytes();
1285
1286        let perf_ctx = if self.write_sample_interval.sample() {
1287            Some(RocksDBPerfContext)
1288        } else {
1289            None
1290        };
1291        self.database.write_opt(self.batch, write_options)?;
1292        self.db_metrics
1293            .op_metrics
1294            .rocksdb_batch_commit_bytes
1295            .with_label_values(&[&db_name])
1296            .observe(batch_size_bytes as f64);
1297
1298        if perf_ctx.is_some() {
1299            self.db_metrics
1300                .write_perf_ctx_metrics
1301                .report_metrics(&db_name);
1302        }
1303        let elapsed_secs = timer.stop_and_record();
1304        let threshold_secs = very_slow_batch_write_threshold_secs(batch_size_bytes);
1305        if elapsed_secs > threshold_secs {
1306            warn!(
1307                elapsed_secs,
1308                threshold_secs,
1309                batch_size_bytes,
1310                ?db_name,
1311                "very slow batch write"
1312            );
1313            self.db_metrics
1314                .op_metrics
1315                .rocksdb_very_slow_batch_writes_count
1316                .with_label_values(&[&db_name])
1317                .inc();
1318            self.db_metrics
1319                .op_metrics
1320                .rocksdb_very_slow_batch_writes_duration_ms
1321                .with_label_values(&[&db_name])
1322                .inc_by((elapsed_secs * 1000.0) as u64);
1323        }
1324        Ok(())
1325    }
1326
1327    pub fn size_in_bytes(&self) -> usize {
1328        match self.batch {
1329            StorageWriteBatch::Rocks(ref b) => b.size_in_bytes(),
1330            StorageWriteBatch::InMemory(_) => 0,
1331        }
1332    }
1333
1334    pub fn delete_batch<J: Borrow<K>, K: Serialize, V>(
1335        &mut self,
1336        db: &DBMap<K, V>,
1337        purged_vals: impl IntoIterator<Item = J>,
1338    ) -> Result<(), TypedStoreError> {
1339        self.delete_batch_raw_keys(
1340            db,
1341            purged_vals
1342                .into_iter()
1343                .map(|key| be_fix_int_ser(key.borrow())),
1344        )
1345    }
1346
1347    /// [`Self::delete_batch`] for keys already in the column family's
1348    /// `be_fix_int_ser` encoding.
1349    fn delete_batch_raw_keys<K, V>(
1350        &mut self,
1351        db: &DBMap<K, V>,
1352        purged_vals: impl IntoIterator<Item = Vec<u8>>,
1353    ) -> Result<(), TypedStoreError> {
1354        if !Arc::ptr_eq(&db.db, &self.database) {
1355            return Err(TypedStoreError::CrossDBBatch);
1356        }
1357
1358        purged_vals
1359            .into_iter()
1360            .try_for_each::<_, Result<_, TypedStoreError>>(|k_buf| {
1361                match (&mut self.batch, &db.column_family) {
1362                    (StorageWriteBatch::Rocks(b), ColumnFamily::Rocks(name)) => {
1363                        b.delete_cf(&rocks_cf_from_db(&self.database, name)?, k_buf)
1364                    }
1365                    (StorageWriteBatch::InMemory(b), ColumnFamily::InMemory(name)) => {
1366                        b.delete_cf(name, k_buf)
1367                    }
1368                    _ => Err(TypedStoreError::RocksDB(
1369                        "typed store invariant violation".to_string(),
1370                    ))?,
1371                }
1372                Ok(())
1373            })?;
1374        Ok(())
1375    }
1376
1377    /// Deletes a range of keys between `from` (inclusive) and `to`
1378    /// (non-inclusive) by writing a range delete tombstone in the db map.
1379    /// The effect of this write is visible immediately, i.e. you won't see
1380    /// old values when you do a lookup or scan.
1381    pub fn schedule_delete_range<K: Serialize, V>(
1382        &mut self,
1383        db: &DBMap<K, V>,
1384        from: &K,
1385        to: &K,
1386    ) -> Result<(), TypedStoreError> {
1387        self.schedule_delete_range_raw(db, be_fix_int_ser(from), be_fix_int_ser(to))
1388    }
1389
1390    /// [`Self::schedule_delete_range`] for a range whose bounds are not keys,
1391    /// such as a whole key prefix. The bounds are raw bytes ordered like the
1392    /// map's keys, i.e. in the `be_fix_int_ser` encoding; `from` is inclusive
1393    /// and `to` exclusive.
1394    fn schedule_delete_range_raw<K, V>(
1395        &mut self,
1396        db: &DBMap<K, V>,
1397        from: Vec<u8>,
1398        to: Vec<u8>,
1399    ) -> Result<(), TypedStoreError> {
1400        if !Arc::ptr_eq(&db.db, &self.database) {
1401            return Err(TypedStoreError::CrossDBBatch);
1402        }
1403
1404        if let StorageWriteBatch::Rocks(b) = &mut self.batch {
1405            b.delete_range_cf(&rocks_cf_from_db(&self.database, db.cf_name())?, from, to);
1406        }
1407        Ok(())
1408    }
1409
1410    /// inserts a range of (key, value) pairs given as an iterator
1411    pub fn insert_batch<J: Borrow<K>, K: Serialize, U: Borrow<V>, V: Serialize>(
1412        &mut self,
1413        db: &DBMap<K, V>,
1414        new_vals: impl IntoIterator<Item = (J, U)>,
1415    ) -> Result<&mut Self, TypedStoreError> {
1416        self.insert_batch_raw_keys(
1417            db,
1418            new_vals
1419                .into_iter()
1420                .map(|(key, value)| (be_fix_int_ser(key.borrow()), value)),
1421        )
1422    }
1423
1424    /// [`Self::insert_batch`] for keys already in the column family's
1425    /// `be_fix_int_ser` encoding.
1426    fn insert_batch_raw_keys<K, U: Borrow<V>, V: Serialize>(
1427        &mut self,
1428        db: &DBMap<K, V>,
1429        new_vals: impl IntoIterator<Item = (Vec<u8>, U)>,
1430    ) -> Result<&mut Self, TypedStoreError> {
1431        if !Arc::ptr_eq(&db.db, &self.database) {
1432            return Err(TypedStoreError::CrossDBBatch);
1433        }
1434        let mut total = 0usize;
1435        new_vals
1436            .into_iter()
1437            .try_for_each::<_, Result<_, TypedStoreError>>(|(k_buf, v)| {
1438                let v_buf = bcs::to_bytes(v.borrow()).map_err(typed_store_err_from_bcs_err)?;
1439                total += k_buf.len() + v_buf.len();
1440                if db.opts.log_value_hash {
1441                    let key_hash = default_hash(&k_buf);
1442                    let value_hash = default_hash(&v_buf);
1443                    debug!(
1444                        "Insert to DB table: {:?}, key_hash: {:?}, value_hash: {:?}",
1445                        db.cf_name(),
1446                        key_hash,
1447                        value_hash
1448                    );
1449                }
1450                match (&mut self.batch, &db.column_family) {
1451                    (StorageWriteBatch::Rocks(b), ColumnFamily::Rocks(name)) => {
1452                        b.put_cf(&rocks_cf_from_db(&self.database, name)?, k_buf, v_buf)
1453                    }
1454                    (StorageWriteBatch::InMemory(b), ColumnFamily::InMemory(name)) => {
1455                        b.put_cf(name, k_buf, v_buf)
1456                    }
1457                    _ => Err(TypedStoreError::RocksDB(
1458                        "typed store invariant violation".to_string(),
1459                    ))?,
1460                }
1461                Ok(())
1462            })?;
1463        self.db_metrics
1464            .op_metrics
1465            .rocksdb_batch_put_bytes
1466            .with_label_values(&[db.metrics_label()])
1467            .observe(total as f64);
1468        Ok(self)
1469    }
1470
1471    /// [`Self::insert_batch`] for a map sharing its column family by tag.
1472    pub fn insert_batch_tagged<J: Borrow<K>, K: Serialize, U: Borrow<V>, V: Serialize>(
1473        &mut self,
1474        map: &TaggedDBMap<K, V>,
1475        new_vals: impl IntoIterator<Item = (J, U)>,
1476    ) -> Result<&mut Self, TypedStoreError> {
1477        self.insert_batch_raw_keys(
1478            &map.map,
1479            new_vals
1480                .into_iter()
1481                .map(|(key, value)| (be_fix_int_ser(&(map.tag, key.borrow())), value)),
1482        )
1483    }
1484
1485    /// [`Self::delete_batch`] for a map sharing its column family by tag.
1486    pub fn delete_batch_tagged<J: Borrow<K>, K: Serialize, V>(
1487        &mut self,
1488        map: &TaggedDBMap<K, V>,
1489        purged_vals: impl IntoIterator<Item = J>,
1490    ) -> Result<(), TypedStoreError> {
1491        self.delete_batch_raw_keys(
1492            &map.map,
1493            purged_vals
1494                .into_iter()
1495                .map(|key| be_fix_int_ser(&(map.tag, key.borrow()))),
1496        )
1497    }
1498}
1499
1500impl<K, V> DBMap<K, V> {
1501    #[instrument(level = "trace", skip_all, err)]
1502    pub(crate) fn contains_raw_key(&self, key_buf: Vec<u8>) -> Result<bool, TypedStoreError> {
1503        let readopts = self.opts.readopts();
1504        Ok(self
1505            .db
1506            .key_may_exist_cf(&self.column_family, &key_buf, &readopts)
1507            && self
1508                .db
1509                .get(&self.column_family, &key_buf, &readopts)?
1510                .is_some())
1511    }
1512
1513    #[instrument(level = "trace", skip_all, err)]
1514    pub(crate) fn multi_contains_raw_keys(
1515        &self,
1516        keys: impl IntoIterator<Item = Vec<u8>>,
1517    ) -> Result<Vec<bool>, TypedStoreError> {
1518        let values = self.multi_get_pinned(keys)?;
1519        Ok(values.into_iter().map(|v| v.is_some()).collect())
1520    }
1521
1522    #[instrument(level = "trace", skip_all, err)]
1523    pub(crate) fn get_raw_key(&self, key_buf: Vec<u8>) -> Result<Option<V>, TypedStoreError>
1524    where
1525        V: DeserializeOwned,
1526    {
1527        let _timer = self
1528            .db_metrics
1529            .op_metrics
1530            .rocksdb_get_latency_seconds
1531            .with_label_values(&[self.metrics_label()])
1532            .start_timer();
1533        let perf_ctx = if self.get_sample_interval.sample() {
1534            Some(RocksDBPerfContext)
1535        } else {
1536            None
1537        };
1538        let res = self
1539            .db
1540            .get(&self.column_family, &key_buf, &self.opts.readopts())?;
1541        self.db_metrics
1542            .op_metrics
1543            .rocksdb_get_bytes
1544            .with_label_values(&[self.metrics_label()])
1545            .observe(res.as_ref().map_or(0.0, |v| v.len() as f64));
1546        if perf_ctx.is_some() {
1547            self.db_metrics
1548                .read_perf_ctx_metrics
1549                .report_metrics(self.metrics_label());
1550        }
1551        match res {
1552            Some(data) => {
1553                let value = bcs::from_bytes(&data).map_err(typed_store_err_from_bcs_err);
1554                if value.is_err() {
1555                    let key_hash = default_hash(&key_buf);
1556                    let value_hash = default_hash(&data);
1557                    debug_fatal!(
1558                        "Failed to deserialize value from DB table {:?}, key_hash: {:?}, value_hash: {:?}, error: {:?}",
1559                        self.cf_name(),
1560                        key_hash,
1561                        value_hash,
1562                        value.as_ref().err().unwrap()
1563                    );
1564                }
1565                Ok(Some(value?))
1566            }
1567            None => Ok(None),
1568        }
1569    }
1570
1571    #[instrument(level = "trace", skip_all, err)]
1572    pub(crate) fn insert_raw_key(&self, key_buf: Vec<u8>, value: &V) -> Result<(), TypedStoreError>
1573    where
1574        V: Serialize,
1575    {
1576        let timer = self
1577            .db_metrics
1578            .op_metrics
1579            .rocksdb_put_latency_seconds
1580            .with_label_values(&[self.metrics_label()])
1581            .start_timer();
1582        let perf_ctx = if self.write_sample_interval.sample() {
1583            Some(RocksDBPerfContext)
1584        } else {
1585            None
1586        };
1587        let value_buf = bcs::to_bytes(value).map_err(typed_store_err_from_bcs_err)?;
1588        self.db_metrics
1589            .op_metrics
1590            .rocksdb_put_bytes
1591            .with_label_values(&[self.metrics_label()])
1592            .observe((key_buf.len() + value_buf.len()) as f64);
1593        if perf_ctx.is_some() {
1594            self.db_metrics
1595                .write_perf_ctx_metrics
1596                .report_metrics(self.metrics_label());
1597        }
1598        self.db.put_cf(&self.column_family, key_buf, value_buf)?;
1599
1600        let elapsed_secs = timer.stop_and_record();
1601        if elapsed_secs > 1.0 {
1602            warn!(elapsed_secs, cf = ?self.cf_name(), "very slow insert");
1603            self.db_metrics
1604                .op_metrics
1605                .rocksdb_very_slow_puts_count
1606                .with_label_values(&[self.metrics_label()])
1607                .inc();
1608            self.db_metrics
1609                .op_metrics
1610                .rocksdb_very_slow_puts_duration_ms
1611                .with_label_values(&[self.metrics_label()])
1612                .inc_by((elapsed_secs * 1000.0) as u64);
1613        }
1614
1615        Ok(())
1616    }
1617
1618    #[instrument(level = "trace", skip_all, err)]
1619    pub(crate) fn remove_raw_key(&self, key_buf: Vec<u8>) -> Result<(), TypedStoreError> {
1620        let _timer = self
1621            .db_metrics
1622            .op_metrics
1623            .rocksdb_delete_latency_seconds
1624            .with_label_values(&[self.metrics_label()])
1625            .start_timer();
1626        let perf_ctx = if self.write_sample_interval.sample() {
1627            Some(RocksDBPerfContext)
1628        } else {
1629            None
1630        };
1631        self.db.delete_cf(&self.column_family, key_buf)?;
1632        self.db_metrics
1633            .op_metrics
1634            .rocksdb_deletes
1635            .with_label_values(&[self.metrics_label()])
1636            .inc();
1637        if perf_ctx.is_some() {
1638            self.db_metrics
1639                .write_perf_ctx_metrics
1640                .report_metrics(self.metrics_label());
1641        }
1642        Ok(())
1643    }
1644
1645    #[instrument(level = "trace", skip_all, err)]
1646    pub(crate) fn multi_get_raw_keys(
1647        &self,
1648        keys: impl IntoIterator<Item = Vec<u8>>,
1649    ) -> Result<Vec<Option<V>>, TypedStoreError>
1650    where
1651        V: DeserializeOwned,
1652    {
1653        let results = self.multi_get_pinned(keys)?;
1654        let values_parsed: Result<Vec<_>, TypedStoreError> = results
1655            .into_iter()
1656            .map(|value_byte| match value_byte {
1657                Some(data) => Ok(Some(
1658                    bcs::from_bytes(&data).map_err(typed_store_err_from_bcs_err)?,
1659                )),
1660                None => Ok(None),
1661            })
1662            .collect();
1663
1664        values_parsed
1665    }
1666}
1667
1668impl<'a, K, V> Map<'a, K, V> for DBMap<K, V>
1669where
1670    K: Serialize + DeserializeOwned,
1671    V: Serialize + DeserializeOwned,
1672{
1673    type Error = TypedStoreError;
1674
1675    fn contains_key(&self, key: &K) -> Result<bool, TypedStoreError> {
1676        self.contains_raw_key(be_fix_int_ser(key))
1677    }
1678
1679    fn multi_contains_keys<J>(
1680        &self,
1681        keys: impl IntoIterator<Item = J>,
1682    ) -> Result<Vec<bool>, Self::Error>
1683    where
1684        J: Borrow<K>,
1685    {
1686        self.multi_contains_raw_keys(keys.into_iter().map(|k| be_fix_int_ser(k.borrow())))
1687    }
1688
1689    fn get(&self, key: &K) -> Result<Option<V>, TypedStoreError> {
1690        self.get_raw_key(be_fix_int_ser(key))
1691    }
1692
1693    fn insert(&self, key: &K, value: &V) -> Result<(), TypedStoreError> {
1694        self.insert_raw_key(be_fix_int_ser(key), value)
1695    }
1696
1697    fn remove(&self, key: &K) -> Result<(), TypedStoreError> {
1698        self.remove_raw_key(be_fix_int_ser(key))
1699    }
1700
1701    /// Writes a range delete tombstone to delete all entries in the db map.
1702    /// The effect of this write is visible immediately, i.e. you won't see
1703    /// old values when you do a lookup or scan.
1704    #[instrument(level = "trace", skip_all, err)]
1705    fn schedule_delete_all(&self) -> Result<(), TypedStoreError> {
1706        let Some(last_key) = self
1707            .safe_range_iter_reversed(..)
1708            .next()
1709            .transpose()?
1710            .map(|(k, _v)| k)
1711        else {
1712            return Ok(());
1713        };
1714        // The tombstone excludes its upper bound, so it has to end past the last key:
1715        // appending a zero byte gives the first key sorting above it.
1716        let mut to = be_fix_int_ser(&last_key);
1717        to.push(0);
1718        // The empty key sorts below every key, so the range starts before the first
1719        // entry.
1720        let mut batch = self.batch();
1721        batch.schedule_delete_range_raw(self, Vec::new(), to)?;
1722        batch.write()
1723    }
1724
1725    fn is_empty(&self) -> bool {
1726        self.safe_iter().next().is_none()
1727    }
1728
1729    fn safe_iter(&'a self) -> DbIterator<'a, (K, V)> {
1730        match &self.db.storage {
1731            Storage::Rocks(db) => match self.rocks_safe_iter(db, self.opts.readopts()) {
1732                Ok(iter) => Box::new(iter),
1733                Err(e) => error_iterator(e),
1734            },
1735            Storage::InMemory(db) => db.iterator(self.column_family.name(), None, None, false),
1736        }
1737    }
1738
1739    fn safe_iter_with_bounds(
1740        &'a self,
1741        lower_bound: Option<K>,
1742        upper_bound: Option<K>,
1743    ) -> DbIterator<'a, (K, V)> {
1744        let range = (
1745            lower_bound.map(Bound::Included).unwrap_or(Bound::Unbounded),
1746            upper_bound.map(Bound::Excluded).unwrap_or(Bound::Unbounded),
1747        );
1748        self.safe_range_iter(range)
1749    }
1750
1751    fn safe_range_iter(&'a self, range: impl RangeBounds<K>) -> DbIterator<'a, (K, V)> {
1752        let (lower_bound, upper_bound) = iterator_bounds_with_range(range);
1753        self.iter_forward_raw(lower_bound, upper_bound)
1754    }
1755
1756    /// Both directions derive their bounds from the same
1757    /// `iterator_bounds_with_range`, so they are guaranteed to cover the
1758    /// identical set of keys regardless of the bound inclusivity.
1759    fn safe_range_iter_reversed(&'a self, range: impl RangeBounds<K>) -> DbIterator<'a, (K, V)> {
1760        let (lower_bound, upper_bound) = iterator_bounds_with_range(range);
1761        self.iter_reversed_raw(lower_bound, upper_bound)
1762    }
1763
1764    /// Returns a vector of values corresponding to the keys provided.
1765    fn multi_get<J>(
1766        &self,
1767        keys: impl IntoIterator<Item = J>,
1768    ) -> Result<Vec<Option<V>>, TypedStoreError>
1769    where
1770        J: Borrow<K>,
1771    {
1772        self.multi_get_raw_keys(keys.into_iter().map(|k| be_fix_int_ser(k.borrow())))
1773    }
1774
1775    /// Convenience method for batch insertion
1776    #[instrument(level = "trace", skip_all, err)]
1777    fn multi_insert<J, U>(
1778        &self,
1779        key_val_pairs: impl IntoIterator<Item = (J, U)>,
1780    ) -> Result<(), Self::Error>
1781    where
1782        J: Borrow<K>,
1783        U: Borrow<V>,
1784    {
1785        let mut batch = self.batch();
1786        batch.insert_batch(self, key_val_pairs)?;
1787        batch.write()
1788    }
1789
1790    /// Convenience method for batch removal
1791    #[instrument(level = "trace", skip_all, err)]
1792    fn multi_remove<J>(&self, keys: impl IntoIterator<Item = J>) -> Result<(), Self::Error>
1793    where
1794        J: Borrow<K>,
1795    {
1796        let mut batch = self.batch();
1797        batch.delete_batch(self, keys)?;
1798        batch.write()
1799    }
1800
1801    /// Try to catch up with primary when running as secondary
1802    #[instrument(level = "trace", skip_all, err)]
1803    fn try_catch_up_with_primary(&self) -> Result<(), Self::Error> {
1804        self.db.try_catch_up_with_primary()
1805    }
1806}
1807
1808/// A typed map sharing one column family with other typed maps,
1809/// distinguished by a tag byte prefixed to every key: the big-endian fixint
1810/// serialization of `(tag, key)` keeps each map a contiguous key range of
1811/// the column family. Useful for sets of tables that are always created and
1812/// dropped together — one column family instead of one per table keeps the
1813/// column-family and SST-file counts low.
1814///
1815/// Every read is scoped to the map's tag: full scans iterate the tag's key
1816/// prefix, and ranges are two-sided within it, so rows of other tags never
1817/// surface and their (differently typed) values are never deserialized.
1818///
1819/// Tags of existing maps must never change or be reused, or old rows would
1820/// be read under the wrong types.
1821///
1822/// Metrics are labelled by column family, so all the maps of one column
1823/// family report together, with no way to tell the tags apart.
1824///
1825/// # Examples
1826///
1827/// ```
1828/// use tempfile::tempdir;
1829/// use typed_store::{Map, rocks::*};
1830///
1831/// #[tokio::main(flavor = "current_thread")]
1832/// async fn main() {
1833///     let db = open_cf_opts(
1834///         tempdir().unwrap(),
1835///         None,
1836///         MetricConf::default(),
1837///         &[("shared", rocksdb::Options::default())],
1838///     )
1839///     .unwrap();
1840///
1841///     let numbers: TaggedDBMap<u32, String> =
1842///         TaggedDBMap::reopen(&db, "shared", 0, &ReadWriteOptions::default(), false).unwrap();
1843///     let words: TaggedDBMap<String, u64> =
1844///         TaggedDBMap::reopen(&db, "shared", 1, &ReadWriteOptions::default(), false).unwrap();
1845///
1846///     let mut batch = numbers.batch();
1847///     batch
1848///         .insert_batch_tagged(&numbers, [(1, "one".to_string())])
1849///         .unwrap()
1850///         .insert_batch_tagged(&words, [("one".to_string(), 1)])
1851///         .unwrap();
1852///     batch.write().unwrap();
1853///
1854///     assert_eq!(numbers.get(&1).unwrap(), Some("one".to_string()));
1855///     assert_eq!(words.get(&"one".to_string()).unwrap(), Some(1));
1856///     // Each map sees only its own row.
1857///     assert_eq!(numbers.safe_iter().count(), 1);
1858/// }
1859/// ```
1860pub struct TaggedDBMap<K, V> {
1861    tag: u8,
1862    map: DBMap<(u8, K), V>,
1863}
1864
1865impl<K, V> TaggedDBMap<K, V> {
1866    /// Drops the tag prefixed to a key of the underlying map, turning its row
1867    /// into a row of this map.
1868    fn strip_tag(row: Result<((u8, K), V), TypedStoreError>) -> Result<(K, V), TypedStoreError> {
1869        row.map(|((_, key), value)| (key, value))
1870    }
1871
1872    pub(crate) fn tag(&self) -> u8 {
1873        self.tag
1874    }
1875
1876    /// [`DBMap::ingest_sst_files`] for this map's column family, which the
1877    /// files may hold rows of any table sharing it for.
1878    pub fn ingest_sst_files(&self, paths: &[PathBuf]) -> Result<(), TypedStoreError> {
1879        self.map.ingest_sst_files(paths)
1880    }
1881
1882    /// Reopens an open database as a tagged map operating under `cf_name`.
1883    /// See [`DBMap::reopen`] for the remaining parameters.
1884    pub fn reopen(
1885        db: &Arc<Database>,
1886        cf_name: &str,
1887        tag: u8,
1888        rw_options: &ReadWriteOptions,
1889        skip_metrics_reporting: bool,
1890    ) -> Result<Self, TypedStoreError> {
1891        Ok(Self {
1892            tag,
1893            map: DBMap::reopen(db, Some(cf_name), rw_options, skip_metrics_reporting)?,
1894        })
1895    }
1896
1897    /// Create a batch associated with the map's database.
1898    pub fn batch(&self) -> DBBatch {
1899        self.map.batch()
1900    }
1901
1902    /// See [`DBMap::with_metrics_label`].
1903    pub fn with_metrics_label(mut self, label: &str) -> Self {
1904        self.map = self.map.with_metrics_label(label);
1905        self
1906    }
1907}
1908
1909impl<'a, K, V> Map<'a, K, V> for TaggedDBMap<K, V>
1910where
1911    K: Serialize + DeserializeOwned,
1912    V: Serialize + DeserializeOwned,
1913{
1914    type Error = TypedStoreError;
1915
1916    fn contains_key(&self, key: &K) -> Result<bool, TypedStoreError> {
1917        self.map.contains_raw_key(be_fix_int_ser(&(self.tag, key)))
1918    }
1919
1920    fn multi_contains_keys<J>(
1921        &self,
1922        keys: impl IntoIterator<Item = J>,
1923    ) -> Result<Vec<bool>, TypedStoreError>
1924    where
1925        J: Borrow<K>,
1926    {
1927        self.map.multi_contains_raw_keys(
1928            keys.into_iter()
1929                .map(|key| be_fix_int_ser(&(self.tag, key.borrow()))),
1930        )
1931    }
1932
1933    fn get(&self, key: &K) -> Result<Option<V>, TypedStoreError> {
1934        self.map.get_raw_key(be_fix_int_ser(&(self.tag, key)))
1935    }
1936
1937    fn multi_get<J>(
1938        &self,
1939        keys: impl IntoIterator<Item = J>,
1940    ) -> Result<Vec<Option<V>>, TypedStoreError>
1941    where
1942        J: Borrow<K>,
1943    {
1944        self.map.multi_get_raw_keys(
1945            keys.into_iter()
1946                .map(|key| be_fix_int_ser(&(self.tag, key.borrow()))),
1947        )
1948    }
1949
1950    fn insert(&self, key: &K, value: &V) -> Result<(), TypedStoreError> {
1951        self.map
1952            .insert_raw_key(be_fix_int_ser(&(self.tag, key)), value)
1953    }
1954
1955    fn remove(&self, key: &K) -> Result<(), TypedStoreError> {
1956        self.map.remove_raw_key(be_fix_int_ser(&(self.tag, key)))
1957    }
1958
1959    #[instrument(level = "trace", skip_all, err)]
1960    fn multi_insert<J, U>(
1961        &self,
1962        key_val_pairs: impl IntoIterator<Item = (J, U)>,
1963    ) -> Result<(), TypedStoreError>
1964    where
1965        J: Borrow<K>,
1966        U: Borrow<V>,
1967    {
1968        let mut batch = self.batch();
1969        batch.insert_batch_tagged(self, key_val_pairs)?;
1970        batch.write()
1971    }
1972
1973    #[instrument(level = "trace", skip_all, err)]
1974    fn multi_remove<J>(&self, keys: impl IntoIterator<Item = J>) -> Result<(), TypedStoreError>
1975    where
1976        J: Borrow<K>,
1977    {
1978        let mut batch = self.batch();
1979        batch.delete_batch_tagged(self, keys)?;
1980        batch.write()
1981    }
1982
1983    /// Deletes every entry of the map with a single range tombstone over the
1984    /// tag's key range, leaving the other tags of the column family untouched.
1985    ///
1986    /// The entries stay on disk until compaction, and until then iteration
1987    /// is slowed because of them.
1988    #[instrument(level = "trace", skip_all, err)]
1989    fn schedule_delete_all(&self) -> Result<(), TypedStoreError> {
1990        let from = be_fix_int_ser(&self.tag);
1991        let to = match prefix_iterator_bounds(&self.tag).1 {
1992            Some(to) => {
1993                if self.is_empty() {
1994                    return Ok(());
1995                }
1996                to
1997            }
1998            // The maximum tag has no following tag to bound the range
1999            // against, so end it just past the last entry. That read is why a
2000            // row written in between survives the clear, and why a value that
2001            // does not deserialize fails it.
2002            None => match self.safe_range_iter_reversed(..).next().transpose()? {
2003                Some((last_key, _)) => {
2004                    let mut to = be_fix_int_ser(&(self.tag, last_key));
2005                    to.push(0);
2006                    to
2007                }
2008                None => return Ok(()),
2009            },
2010        };
2011
2012        let mut batch = self.batch();
2013        batch.schedule_delete_range_raw(&self.map, from, to)?;
2014        batch.write()
2015    }
2016
2017    fn is_empty(&self) -> bool {
2018        self.safe_iter().next().is_none()
2019    }
2020
2021    fn safe_iter(&'a self) -> DbIterator<'a, (K, V)> {
2022        Box::new(
2023            self.map
2024                .safe_iter_with_prefix(&self.tag)
2025                .map(Self::strip_tag),
2026        )
2027    }
2028
2029    fn safe_iter_with_bounds(
2030        &'a self,
2031        lower_bound: Option<K>,
2032        upper_bound: Option<K>,
2033    ) -> DbIterator<'a, (K, V)> {
2034        let range = (
2035            lower_bound.map(Bound::Included).unwrap_or(Bound::Unbounded),
2036            upper_bound.map(Bound::Excluded).unwrap_or(Bound::Unbounded),
2037        );
2038        self.safe_range_iter(range)
2039    }
2040
2041    fn safe_range_iter(&'a self, range: impl RangeBounds<K>) -> DbIterator<'a, (K, V)> {
2042        let (lower_bound, upper_bound) = prefix_iterator_bounds_with_range(&self.tag, range);
2043        Box::new(
2044            self.map
2045                .iter_forward_raw(lower_bound, upper_bound)
2046                .map(Self::strip_tag),
2047        )
2048    }
2049
2050    fn safe_range_iter_reversed(&'a self, range: impl RangeBounds<K>) -> DbIterator<'a, (K, V)> {
2051        let (lower_bound, upper_bound) = prefix_iterator_bounds_with_range(&self.tag, range);
2052        Box::new(
2053            self.map
2054                .iter_reversed_raw(lower_bound, upper_bound)
2055                .map(Self::strip_tag),
2056        )
2057    }
2058
2059    fn try_catch_up_with_primary(&self) -> Result<(), TypedStoreError> {
2060        self.map.try_catch_up_with_primary()
2061    }
2062}
2063
2064/// Waits until the database of `db` has been closed, every handle to it
2065/// dropped and RocksDB's files released, so its directory can be reopened,
2066/// moved, or deleted. Returns `false` if it is still open after 30 seconds.
2067pub async fn wait_for_database_close(db: DatabaseClose) -> bool {
2068    // The deadline is read off the same clock the sleep advances, so a test
2069    // pausing time does not turn the wait into a busy loop.
2070    let deadline = Instant::now() + Duration::from_secs(30);
2071    while db.0.strong_count() != 0 {
2072        if Instant::now() > deadline {
2073            return false;
2074        }
2075        tokio::time::sleep(Duration::from_millis(100)).await;
2076    }
2077    true
2078}
2079
2080/// Returns an iterator whose only item is `Err(error)`.
2081pub(crate) fn error_iterator<'a, T: 'a>(error: TypedStoreError) -> DbIterator<'a, T> {
2082    Box::new(std::iter::once(Err(error)))
2083}
2084
2085/// Write options that discard the batch entries of a column family dropped
2086/// after staging, instead of failing the write; see [`DBBatch::write_opt`].
2087pub fn drop_tolerant_write_options() -> rocksdb::WriteOptions {
2088    let mut options = rocksdb::WriteOptions::default();
2089    options.set_ignore_missing_column_families(true);
2090    options
2091}
2092
2093fn default_hash(value: &[u8]) -> Digest<32> {
2094    let mut hasher = fastcrypto::hash::Blake2b256::default();
2095    hasher.update(value);
2096    hasher.finalize()
2097}
2098
2099// The throughput floor is used to compute the threshold for when a batch write
2100// is considered "very slow".
2101const THROUGHPUT_FLOOR_BYTES_PER_SEC: f64 = 32.0 * 1024.0 * 1024.0; // 32 MiB/s
2102
2103// A batch write that took less than this is never reported as very slow.
2104const MIN_VERY_SLOW_BATCH_WRITE_SECS: f64 = 1.0;
2105
2106/// Returns the elapsed time above which a batch write of `batch_size_bytes` is
2107/// reported as very slow: what it would take at
2108/// [`THROUGHPUT_FLOOR_BYTES_PER_SEC`], and never less than
2109/// [`MIN_VERY_SLOW_BATCH_WRITE_SECS`].
2110fn very_slow_batch_write_threshold_secs(batch_size_bytes: usize) -> f64 {
2111    (batch_size_bytes as f64 / THROUGHPUT_FLOOR_BYTES_PER_SEC).max(MIN_VERY_SLOW_BATCH_WRITE_SECS)
2112}
2113
2114#[cfg(test)]
2115mod tests {
2116    use super::very_slow_batch_write_threshold_secs;
2117
2118    const MIB: usize = 1024 * 1024;
2119
2120    #[test]
2121    fn very_slow_batch_write_threshold_never_below_one_second() {
2122        assert_eq!(very_slow_batch_write_threshold_secs(0), 1.0);
2123        assert_eq!(very_slow_batch_write_threshold_secs(1), 1.0);
2124        assert_eq!(very_slow_batch_write_threshold_secs(MIB), 1.0);
2125        assert_eq!(very_slow_batch_write_threshold_secs(32 * MIB), 1.0);
2126    }
2127
2128    #[test]
2129    fn very_slow_batch_write_threshold_grows_with_batch_size() {
2130        assert_eq!(very_slow_batch_write_threshold_secs(48 * MIB), 1.5);
2131        assert_eq!(very_slow_batch_write_threshold_secs(64 * MIB), 2.0);
2132        assert_eq!(very_slow_batch_write_threshold_secs(320 * MIB), 10.0);
2133    }
2134}