Skip to main content

fedimint_rocksdb/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::must_use_candidate)]
4#![allow(clippy::needless_lifetimes)]
5
6pub mod envs;
7
8use std::fmt;
9use std::ops::Range;
10use std::path::Path;
11use std::str::FromStr;
12
13use async_trait::async_trait;
14use fedimint_core::db::{
15    DatabaseError, DatabaseResult, IDatabaseTransactionOps, IDatabaseTransactionOpsCore,
16    IRawDatabase, IRawDatabaseTransaction, PrefixStream,
17};
18use fedimint_core::task::block_in_place;
19use fedimint_db_locked::{DbLockError, Locked, LockedBuilder};
20use futures::stream;
21pub use rocksdb;
22use rocksdb::{
23    DBRecoveryMode, OptimisticTransactionDB, OptimisticTransactionOptions, WriteOptions,
24};
25use tracing::debug;
26
27use crate::envs::{FM_ROCKSDB_BLOCK_CACHE_SIZE_ENV, FM_ROCKSDB_WRITE_BUFFER_SIZE_ENV};
28
29// turn an `iter` into a `Stream` where every `next` is ran inside
30// `block_in_place` to offload the blocking calls
31fn convert_to_async_stream<'i, I>(iter: I) -> impl futures::Stream<Item = I::Item> + use<I>
32where
33    I: Iterator + Send + 'i,
34    I::Item: Send,
35{
36    stream::unfold(iter, |mut iter| async {
37        fedimint_core::runtime::block_in_place(|| {
38            let item = iter.next();
39            item.map(|item| (item, iter))
40        })
41    })
42}
43
44#[derive(Debug)]
45pub struct RocksDb(rocksdb::OptimisticTransactionDB);
46
47pub struct RocksDbTransaction<'a>(rocksdb::Transaction<'a, rocksdb::OptimisticTransactionDB>);
48
49#[bon::bon]
50impl RocksDb {
51    /// Open the database using blocking IO
52    #[builder(start_fn = build)]
53    #[builder(finish_fn = open_blocking)]
54    pub fn open_blocking(
55        #[builder(start_fn)] db_path: impl AsRef<Path>,
56    ) -> Result<Locked<RocksDb>, RocksDbOpenError> {
57        let db_path = db_path.as_ref();
58
59        block_in_place(|| {
60            std::fs::create_dir_all(db_path.parent().ok_or(RocksDbOpenError::NoBaseDir)?)?;
61            LockedBuilder::new(db_path)?.with_db(|| Self::open_blocking_unlocked(db_path))
62        })
63    }
64}
65
66impl<I1, S> RocksDbOpenBlockingBuilder<I1, S>
67where
68    S: rocks_db_open_blocking_builder::State,
69    I1: std::convert::AsRef<std::path::Path>,
70{
71    /// Open the database
72    #[allow(clippy::unused_async)]
73    pub async fn open(self) -> Result<Locked<RocksDb>, RocksDbOpenError> {
74        block_in_place(|| self.open_blocking())
75    }
76}
77
78impl RocksDb {
79    fn open_blocking_unlocked(db_path: &Path) -> Result<RocksDb, RocksDbOpenError> {
80        let mut opts = get_default_options()?;
81        // Synchronous writes (set_sync(true)) ensure completed writes are
82        // durable, but a SIGKILL mid-write can still leave a truncated WAL tail
83        // record. TolerateCorruptedTailRecords (RocksDB's own default) discards
84        // only incomplete tail records — no committed data is lost.
85        // AbsoluteConsistency was used previously but made the database
86        // permanently unrecoverable after any unclean shutdown.
87        // See: https://github.com/fedimint/fedimint/issues/8072
88        //
89        // WAL files are recycled rather than created anew at every memtable
90        // switch. Every commit syncs the WAL, and on ext4 a sync that grows a
91        // file also commits a journal transaction for its new size; a recycled
92        // file already has its full size, so a sync writes only the data.
93        // RocksDB disables recycling under TolerateCorruptedTailRecords: a
94        // recycled file's tail still holds records from its previous use,
95        // which PointInTime recognizes by their log number and treats as the
96        // end of the log. After an unclean shutdown it recovers the same
97        // synced prefix. It differs on corruption in the middle of a WAL (a
98        // failing disk rather than a crash): PointInTime opens the database
99        // with the writes before the corruption, where
100        // TolerateCorruptedTailRecords refuses to open it.
101        opts.set_wal_recovery_mode(DBRecoveryMode::PointInTime);
102        opts.set_recycle_log_file_num(WAL_RECYCLE_FILES);
103        let db: rocksdb::OptimisticTransactionDB =
104            rocksdb::OptimisticTransactionDB::<rocksdb::SingleThreaded>::open(&opts, db_path)?;
105        Ok(RocksDb(db))
106    }
107
108    pub fn inner(&self) -> &rocksdb::OptimisticTransactionDB {
109        &self.0
110    }
111}
112
113// TODO: Remove this and inline it in the places where it's used.
114fn is_power_of_two(num: usize) -> bool {
115    num.is_power_of_two()
116}
117
118impl fmt::Debug for RocksDbReadOnlyTransaction<'_> {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.write_str("RocksDbTransaction")
121    }
122}
123
124impl fmt::Debug for RocksDbTransaction<'_> {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.write_str("RocksDbTransaction")
127    }
128}
129
130#[test]
131fn is_power_of_two_sanity() {
132    assert!(!is_power_of_two(0));
133    assert!(is_power_of_two(1));
134    assert!(is_power_of_two(2));
135    assert!(!is_power_of_two(3));
136    assert!(is_power_of_two(4));
137    assert!(!is_power_of_two(5));
138    assert!(is_power_of_two(2 << 10));
139    assert!(!is_power_of_two((2 << 10) + 1));
140}
141
142/// Default write buffer size: 16 MiB (`RocksDB` default is 64 MiB).
143///
144/// Every flush writes a level-0 table, and while the database is small
145/// compaction rewrites it together with the whole database, so the number of
146/// flushes drives compaction writes. Under load a 2 MiB buffer flushed several
147/// times per session; 16 MiB halves compaction writes. With at most two write
148/// buffers, memtables use at most 32 MiB.
149const DEFAULT_WRITE_BUFFER_SIZE: usize = 16 * 1024 * 1024;
150
151/// WAL files kept for reuse; see `open_blocking_unlocked`.
152const WAL_RECYCLE_FILES: usize = 4;
153
154/// Default block cache size: 64 MiB (`RocksDB` default is 8 MiB).
155/// Index/filter blocks are placed in this cache too
156/// (`set_cache_index_and_filter_blocks`), so everything is bounded. With
157/// long keys a table's index block reaches several MiB, and every lookup
158/// needs it, so the cache must be able to hold the index blocks of the tables
159/// being read or each lookup reads and decodes them again.
160const DEFAULT_BLOCK_CACHE_SIZE: usize = 64 * 1024 * 1024;
161
162/// Default max open files: 256 (`RocksDB` default is unlimited which
163/// consumes memory for each open file handle and associated metadata)
164const DEFAULT_MAX_OPEN_FILES: i32 = 256;
165
166fn parse_env_size(env_name: &'static str) -> Result<Option<usize>, RocksDbOpenError> {
167    let Ok(var) = std::env::var(env_name) else {
168        return Ok(None);
169    };
170    let size: usize = FromStr::from_str(&var).map_err(|source| RocksDbOpenError::EnvParse {
171        var: env_name,
172        source,
173    })?;
174    if !is_power_of_two(size) {
175        return Err(RocksDbOpenError::EnvNotPowerOfTwo { var: env_name });
176    }
177    Ok(Some(size))
178}
179
180fn get_default_options() -> Result<rocksdb::Options, RocksDbOpenError> {
181    let mut opts = rocksdb::Options::default();
182
183    let write_buffer_size =
184        parse_env_size(FM_ROCKSDB_WRITE_BUFFER_SIZE_ENV)?.unwrap_or(DEFAULT_WRITE_BUFFER_SIZE);
185    opts.set_write_buffer_size(write_buffer_size);
186
187    // Keep at most 2 write buffers (1 active + 1 flushing)
188    opts.set_max_write_buffer_number(2);
189
190    let block_cache_size =
191        parse_env_size(FM_ROCKSDB_BLOCK_CACHE_SIZE_ENV)?.unwrap_or(DEFAULT_BLOCK_CACHE_SIZE);
192    // A sharded cache splits the capacity evenly and an entry larger than its
193    // shard is not retained. The default sharding keeps shards at 512 KiB to
194    // 1 MiB for caches up to 64 MiB, so index blocks of several MiB would never
195    // stay cached.
196    let mut cache_opts = rocksdb::LruCacheOptions::default();
197    cache_opts.set_capacity(block_cache_size);
198    cache_opts.set_num_shard_bits(0);
199    let cache = rocksdb::Cache::new_lru_cache_opts(&cache_opts);
200    let mut block_opts = rocksdb::BlockBasedOptions::default();
201    block_opts.set_block_cache(&cache);
202    // Put index and filter blocks into the block cache so they are
203    // bounded by the same memory budget instead of growing unbounded.
204    block_opts.set_cache_index_and_filter_blocks(true);
205    opts.set_block_based_table_factory(&block_opts);
206
207    opts.set_max_open_files(DEFAULT_MAX_OPEN_FILES);
208
209    debug!(
210        write_buffer_size,
211        block_cache_size,
212        max_open_files = DEFAULT_MAX_OPEN_FILES,
213        "RocksDB memory options"
214    );
215
216    opts.create_if_missing(true);
217    Ok(opts)
218}
219
220#[derive(Debug)]
221pub struct RocksDbReadOnly(rocksdb::DB);
222
223pub struct RocksDbReadOnlyTransaction<'a>(&'a rocksdb::DB);
224
225impl RocksDbReadOnly {
226    #[allow(clippy::unused_async)]
227    pub async fn open_read_only(
228        db_path: impl AsRef<Path>,
229    ) -> Result<RocksDbReadOnly, RocksDbOpenError> {
230        let db_path = db_path.as_ref();
231        block_in_place(|| Self::open_read_only_blocking(db_path))
232    }
233
234    pub fn open_read_only_blocking(db_path: &Path) -> Result<RocksDbReadOnly, RocksDbOpenError> {
235        let opts = get_default_options()?;
236        // Note: rocksdb is OK if one process has write access, and other read-access
237        let db = rocksdb::DB::open_for_read_only(&opts, db_path, false)?;
238        Ok(RocksDbReadOnly(db))
239    }
240}
241
242/// Why a [`RocksDb`] or [`RocksDbReadOnly`] could not be opened.
243#[derive(Debug, thiserror::Error)]
244#[non_exhaustive]
245pub enum RocksDbOpenError {
246    /// The database path has no parent directory to create; only when
247    /// opening for writing.
248    #[error("db path must have a base dir")]
249    NoBaseDir,
250
251    /// The parent directory of the database could not be created; only when
252    /// opening for writing.
253    #[error(transparent)]
254    CreateDir(#[from] std::io::Error),
255
256    /// The lock file next to the database could not be opened or locked;
257    /// only when opening for writing.
258    #[error(transparent)]
259    Lock(#[from] DbLockError),
260
261    /// A size override in the environment is not a number, or is too large
262    /// for a `usize`.
263    #[error("Could not parse {var}")]
264    EnvParse {
265        /// The environment variable.
266        var: &'static str,
267        /// Why its value could not be parsed.
268        #[source]
269        source: std::num::ParseIntError,
270    },
271
272    /// A size override in the environment is not a power of two.
273    #[error("{var} is not a power of 2")]
274    EnvNotPowerOfTwo {
275        /// The environment variable.
276        var: &'static str,
277    },
278
279    /// `RocksDB` could not open the database.
280    #[error(transparent)]
281    RocksDb(#[from] rocksdb::Error),
282}
283
284impl From<rocksdb::OptimisticTransactionDB> for RocksDb {
285    fn from(db: OptimisticTransactionDB) -> Self {
286        RocksDb(db)
287    }
288}
289
290impl From<RocksDb> for rocksdb::OptimisticTransactionDB {
291    fn from(db: RocksDb) -> Self {
292        db.0
293    }
294}
295
296// When finding by prefix iterating in Reverse order, we need to start from
297// "prefix+1" instead of "prefix", using lexicographic ordering. See the tests
298// below.
299// Will return None if there is no next prefix (i.e prefix is already the last
300// possible/max one)
301fn next_prefix(prefix: &[u8]) -> Option<Vec<u8>> {
302    let mut next_prefix = prefix.to_vec();
303    let mut is_last_prefix = true;
304    for i in (0..next_prefix.len()).rev() {
305        next_prefix[i] = next_prefix[i].wrapping_add(1);
306        if next_prefix[i] > 0 {
307            is_last_prefix = false;
308            break;
309        }
310    }
311    if is_last_prefix {
312        // The given prefix is already the last/max prefix, so there is no next prefix,
313        // return None to represent that
314        None
315    } else {
316        Some(next_prefix)
317    }
318}
319
320#[async_trait]
321impl IRawDatabase for RocksDb {
322    type Transaction<'a> = RocksDbTransaction<'a>;
323    async fn begin_transaction<'a>(&'a self) -> RocksDbTransaction {
324        let mut optimistic_options = OptimisticTransactionOptions::default();
325        optimistic_options.set_snapshot(true);
326
327        let mut write_options = WriteOptions::default();
328        // Make sure we never lose data on unclean shutdown
329        write_options.set_sync(true);
330
331        RocksDbTransaction(self.0.transaction_opt(&write_options, &optimistic_options))
332    }
333
334    fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()> {
335        // Flush before the checkpoint does. The checkpoint disables file
336        // deletions and then flushes, and RocksDB does not reuse a recycled
337        // WAL file while file deletions are disabled. When the memtable does
338        // not fill up between checkpoints (an idle federation checkpoints
339        // every session), that flush would be the only WAL switch, so no WAL
340        // file would ever be reused. Flushing here switches the WAL with
341        // deletions enabled; the checkpoint's own flush then finds an empty
342        // memtable and creates no WAL.
343        self.0.flush().map_err(DatabaseError::backend)?;
344        let checkpoint =
345            rocksdb::checkpoint::Checkpoint::new(&self.0).map_err(DatabaseError::backend)?;
346        checkpoint
347            .create_checkpoint(backup_path)
348            .map_err(DatabaseError::backend)?;
349        Ok(())
350    }
351}
352
353#[async_trait]
354impl IRawDatabase for RocksDbReadOnly {
355    type Transaction<'a> = RocksDbReadOnlyTransaction<'a>;
356    async fn begin_transaction<'a>(&'a self) -> RocksDbReadOnlyTransaction<'a> {
357        RocksDbReadOnlyTransaction(&self.0)
358    }
359
360    fn checkpoint(&self, backup_path: &Path) -> DatabaseResult<()> {
361        let checkpoint =
362            rocksdb::checkpoint::Checkpoint::new(&self.0).map_err(DatabaseError::backend)?;
363        checkpoint
364            .create_checkpoint(backup_path)
365            .map_err(DatabaseError::backend)?;
366        Ok(())
367    }
368}
369
370#[async_trait]
371impl IDatabaseTransactionOpsCore for RocksDbTransaction<'_> {
372    async fn raw_insert_bytes_no_previous(
373        &mut self,
374        key: &[u8],
375        value: &[u8],
376    ) -> DatabaseResult<()> {
377        fedimint_core::runtime::block_in_place(|| {
378            self.0.put(key, value).map_err(DatabaseError::backend)
379        })
380    }
381
382    async fn raw_remove_entry_no_previous(&mut self, key: &[u8]) -> DatabaseResult<()> {
383        fedimint_core::runtime::block_in_place(|| {
384            self.0.delete(key).map_err(DatabaseError::backend)
385        })
386    }
387
388    async fn raw_insert_bytes(
389        &mut self,
390        key: &[u8],
391        value: &[u8],
392    ) -> DatabaseResult<Option<Vec<u8>>> {
393        fedimint_core::runtime::block_in_place(|| {
394            let val = self.0.snapshot().get(key).unwrap();
395            self.0.put(key, value).map_err(DatabaseError::backend)?;
396            Ok(val)
397        })
398    }
399
400    async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
401        fedimint_core::runtime::block_in_place(|| {
402            self.0.snapshot().get(key).map_err(DatabaseError::backend)
403        })
404    }
405
406    async fn raw_remove_entry(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
407        fedimint_core::runtime::block_in_place(|| {
408            let val = self.0.snapshot().get(key).unwrap();
409            self.0.delete(key).map_err(DatabaseError::backend)?;
410            Ok(val)
411        })
412    }
413
414    async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>> {
415        Ok(fedimint_core::runtime::block_in_place(|| {
416            let prefix = key_prefix.to_vec();
417            let mut options = rocksdb::ReadOptions::default();
418            options.set_iterate_range(rocksdb::PrefixRange(prefix.clone()));
419            let iter = self.0.snapshot().iterator_opt(
420                rocksdb::IteratorMode::From(&prefix, rocksdb::Direction::Forward),
421                options,
422            );
423            let rocksdb_iter = iter.map_while(move |res| {
424                let (key_bytes, value_bytes) = res.expect("Error reading from RocksDb");
425                key_bytes
426                    .starts_with(&prefix)
427                    .then_some((key_bytes.into_vec(), value_bytes.into_vec()))
428            });
429            Box::pin(convert_to_async_stream(rocksdb_iter))
430        }))
431    }
432
433    async fn raw_find_by_range(&mut self, range: Range<&[u8]>) -> DatabaseResult<PrefixStream<'_>> {
434        Ok(fedimint_core::runtime::block_in_place(|| {
435            let range = Range {
436                start: range.start.to_vec(),
437                end: range.end.to_vec(),
438            };
439            let mut options = rocksdb::ReadOptions::default();
440            options.set_iterate_range(range.clone());
441            let iter = self.0.snapshot().iterator_opt(
442                rocksdb::IteratorMode::From(&range.start, rocksdb::Direction::Forward),
443                options,
444            );
445            let rocksdb_iter = iter.map_while(move |res| {
446                let (key_bytes, value_bytes) = res.expect("Error reading from RocksDb");
447                (key_bytes.as_ref() < range.end.as_slice())
448                    .then_some((key_bytes.into_vec(), value_bytes.into_vec()))
449            });
450            Box::pin(convert_to_async_stream(rocksdb_iter))
451        }))
452    }
453
454    async fn raw_remove_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<()> {
455        fedimint_core::runtime::block_in_place(|| {
456            // Note: delete_range is not supported in Transactions :/
457            let mut options = rocksdb::ReadOptions::default();
458            options.set_iterate_range(rocksdb::PrefixRange(key_prefix.to_owned()));
459            let iter = self
460                .0
461                .snapshot()
462                .iterator_opt(
463                    rocksdb::IteratorMode::From(key_prefix, rocksdb::Direction::Forward),
464                    options,
465                )
466                .map_while(|res| {
467                    res.map(|(key_bytes, _)| {
468                        key_bytes
469                            .starts_with(key_prefix)
470                            .then_some(key_bytes.into_vec())
471                    })
472                    .transpose()
473                });
474
475            for item in iter {
476                let key = item.map_err(DatabaseError::backend)?;
477                self.0.delete(key).map_err(DatabaseError::backend)?;
478            }
479
480            Ok(())
481        })
482    }
483
484    async fn raw_find_by_prefix_sorted_descending(
485        &mut self,
486        key_prefix: &[u8],
487    ) -> DatabaseResult<PrefixStream<'_>> {
488        let prefix = key_prefix.to_vec();
489        let next_prefix = next_prefix(&prefix);
490        let iterator_mode = if let Some(next_prefix) = &next_prefix {
491            rocksdb::IteratorMode::From(next_prefix, rocksdb::Direction::Reverse)
492        } else {
493            rocksdb::IteratorMode::End
494        };
495        Ok(fedimint_core::runtime::block_in_place(|| {
496            let mut options = rocksdb::ReadOptions::default();
497            options.set_iterate_range(rocksdb::PrefixRange(prefix.clone()));
498            let iter = self.0.snapshot().iterator_opt(iterator_mode, options);
499            let rocksdb_iter = iter.map_while(move |res| {
500                let (key_bytes, value_bytes) = res.expect("Error reading from RocksDb");
501                key_bytes
502                    .starts_with(&prefix)
503                    .then_some((key_bytes.into_vec(), value_bytes.into_vec()))
504            });
505            Box::pin(convert_to_async_stream(rocksdb_iter))
506        }))
507    }
508}
509
510impl IDatabaseTransactionOps for RocksDbTransaction<'_> {}
511
512#[async_trait]
513impl IRawDatabaseTransaction for RocksDbTransaction<'_> {
514    async fn commit_tx(self) -> DatabaseResult<()> {
515        fedimint_core::runtime::block_in_place(|| {
516            match self.0.commit() {
517                Ok(()) => Ok(()),
518                Err(err) => {
519                    // `Busy` means another transaction wrote a key this one also wrote,
520                    // after our snapshot was taken. `TryAgain` means RocksDB could not
521                    // check for conflicts at all, because our snapshot is older than the
522                    // write history it retains — a different failure with a different
523                    // fix, so it gets its own variant.
524                    //
525                    // Anything else keeps its original kind and message: collapsing
526                    // unrelated failures into a conflict hides what actually went wrong.
527                    // Note that `Database::autocommit` retries on any commit error, so
528                    // nothing here changes which errors it recovers from.
529                    //
530                    // See: https://github.com/fedimint/fedimint/issues/8077
531                    // See: https://github.com/fedimint/fedimint/issues/8872
532                    match err.kind() {
533                        rocksdb::ErrorKind::Busy => Err(DatabaseError::WriteConflict),
534                        rocksdb::ErrorKind::TryAgain => Err(DatabaseError::snapshot_too_old(err)),
535                        _ => Err(DatabaseError::backend(err)),
536                    }
537                }
538            }
539        })
540    }
541}
542
543#[async_trait]
544impl IDatabaseTransactionOpsCore for RocksDbReadOnlyTransaction<'_> {
545    async fn raw_insert_bytes(
546        &mut self,
547        _key: &[u8],
548        _value: &[u8],
549    ) -> DatabaseResult<Option<Vec<u8>>> {
550        panic!("Cannot insert into a read only transaction");
551    }
552
553    async fn raw_get_bytes(&mut self, key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
554        fedimint_core::runtime::block_in_place(|| {
555            self.0.snapshot().get(key).map_err(DatabaseError::backend)
556        })
557    }
558
559    async fn raw_remove_entry(&mut self, _key: &[u8]) -> DatabaseResult<Option<Vec<u8>>> {
560        panic!("Cannot remove from a read only transaction");
561    }
562
563    async fn raw_find_by_range(&mut self, range: Range<&[u8]>) -> DatabaseResult<PrefixStream<'_>> {
564        Ok(fedimint_core::runtime::block_in_place(|| {
565            let range = Range {
566                start: range.start.to_vec(),
567                end: range.end.to_vec(),
568            };
569            let mut options = rocksdb::ReadOptions::default();
570            options.set_iterate_range(range.clone());
571            let iter = self.0.snapshot().iterator_opt(
572                rocksdb::IteratorMode::From(&range.start, rocksdb::Direction::Forward),
573                options,
574            );
575            let rocksdb_iter = iter.map_while(move |res| {
576                let (key_bytes, value_bytes) = res.expect("Error reading from RocksDb");
577                (key_bytes.as_ref() < range.end.as_slice())
578                    .then_some((key_bytes.into_vec(), value_bytes.into_vec()))
579            });
580            Box::pin(convert_to_async_stream(rocksdb_iter))
581        }))
582    }
583
584    async fn raw_find_by_prefix(&mut self, key_prefix: &[u8]) -> DatabaseResult<PrefixStream<'_>> {
585        Ok(fedimint_core::runtime::block_in_place(|| {
586            let prefix = key_prefix.to_vec();
587            let mut options = rocksdb::ReadOptions::default();
588            options.set_iterate_range(rocksdb::PrefixRange(prefix.clone()));
589            let iter = self.0.snapshot().iterator_opt(
590                rocksdb::IteratorMode::From(&prefix, rocksdb::Direction::Forward),
591                options,
592            );
593            let rocksdb_iter = iter.map_while(move |res| {
594                let (key_bytes, value_bytes) = res.expect("Error reading from RocksDb");
595                key_bytes
596                    .starts_with(&prefix)
597                    .then_some((key_bytes.into_vec(), value_bytes.into_vec()))
598            });
599            Box::pin(convert_to_async_stream(rocksdb_iter))
600        }))
601    }
602
603    async fn raw_remove_by_prefix(&mut self, _key_prefix: &[u8]) -> DatabaseResult<()> {
604        panic!("Cannot remove from a read only transaction");
605    }
606
607    async fn raw_find_by_prefix_sorted_descending(
608        &mut self,
609        key_prefix: &[u8],
610    ) -> DatabaseResult<PrefixStream<'_>> {
611        let prefix = key_prefix.to_vec();
612        let next_prefix = next_prefix(&prefix);
613        let iterator_mode = if let Some(next_prefix) = &next_prefix {
614            rocksdb::IteratorMode::From(next_prefix, rocksdb::Direction::Reverse)
615        } else {
616            rocksdb::IteratorMode::End
617        };
618        Ok(fedimint_core::runtime::block_in_place(|| {
619            let mut options = rocksdb::ReadOptions::default();
620            options.set_iterate_range(rocksdb::PrefixRange(prefix.clone()));
621            let iter = self.0.snapshot().iterator_opt(iterator_mode, options);
622            let rocksdb_iter = iter.map_while(move |res| {
623                let (key_bytes, value_bytes) = res.expect("Error reading from RocksDb");
624                key_bytes
625                    .starts_with(&prefix)
626                    .then_some((key_bytes.into_vec(), value_bytes.into_vec()))
627            });
628            Box::pin(stream::iter(rocksdb_iter))
629        }))
630    }
631}
632
633impl IDatabaseTransactionOps for RocksDbReadOnlyTransaction<'_> {}
634
635#[async_trait]
636impl IRawDatabaseTransaction for RocksDbReadOnlyTransaction<'_> {
637    async fn commit_tx(self) -> DatabaseResult<()> {
638        panic!("Cannot commit a read only transaction");
639    }
640}
641
642#[cfg(test)]
643mod fedimint_rocksdb_tests;