1
0
Fork 0
mirror of https://forgejo.ellis.link/continuwuation/continuwuity.git synced 2025-07-28 10:48:30 +00:00
continuwuity/src/database/abstraction/rocksdb.rs

239 lines
7.7 KiB
Rust
Raw Normal View History

2022-10-05 20:34:31 +02:00
use super::{super::Config, watchers::Watchers, KeyValueDatabaseEngine, KvTree};
2021-10-16 15:19:25 +02:00
use crate::{utils, Result};
use std::{
future::Future,
pin::Pin,
sync::{Arc, RwLock},
};
2021-10-16 15:19:25 +02:00
pub struct Engine {
rocks: rocksdb::DBWithThreadMode<rocksdb::MultiThreaded>,
max_open_files: i32,
2022-01-10 15:53:28 +01:00
cache: rocksdb::Cache,
2021-10-16 15:19:25 +02:00
old_cfs: Vec<String>,
}
pub struct RocksDbEngineTree<'a> {
db: Arc<Engine>,
name: &'a str,
watchers: Watchers,
2022-01-13 22:47:30 +01:00
write_lock: RwLock<()>,
2021-10-16 15:19:25 +02:00
}
2022-01-17 14:39:37 +01:00
fn db_options(max_open_files: i32, rocksdb_cache: &rocksdb::Cache) -> rocksdb::Options {
let mut block_based_options = rocksdb::BlockBasedOptions::default();
block_based_options.set_block_cache(rocksdb_cache);
// "Difference of spinning disk"
// https://zhangyuchi.gitbooks.io/rocksdbbook/content/RocksDB-Tuning-Guide.html
2022-01-12 12:27:02 +01:00
block_based_options.set_block_size(4 * 1024);
block_based_options.set_cache_index_and_filter_blocks(true);
let mut db_opts = rocksdb::Options::default();
db_opts.set_block_based_table_factory(&block_based_options);
db_opts.set_optimize_filters_for_hits(true);
db_opts.set_skip_stats_update_on_db_open(true);
db_opts.set_level_compaction_dynamic_level_bytes(true);
db_opts.set_target_file_size_base(256 * 1024 * 1024);
2022-01-12 12:27:02 +01:00
//db_opts.set_compaction_readahead_size(2 * 1024 * 1024);
//db_opts.set_use_direct_reads(true);
//db_opts.set_use_direct_io_for_flush_and_compaction(true);
db_opts.create_if_missing(true);
db_opts.increase_parallelism(num_cpus::get() as i32);
db_opts.set_max_open_files(max_open_files);
db_opts.set_compression_type(rocksdb::DBCompressionType::Zstd);
db_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
2022-01-17 14:35:38 +01:00
db_opts.optimize_level_style_compaction(10 * 1024 * 1024);
let prefix_extractor = rocksdb::SliceTransform::create_fixed_prefix(1);
db_opts.set_prefix_extractor(prefix_extractor);
db_opts
}
impl KeyValueDatabaseEngine for Arc<Engine> {
fn open(config: &Config) -> Result<Self> {
let cache_capacity_bytes = (config.db_cache_capacity_mb * 1024.0 * 1024.0) as usize;
2023-05-21 11:51:36 +02:00
let rocksdb_cache = rocksdb::Cache::new_lru_cache(cache_capacity_bytes);
2022-01-10 20:20:45 +01:00
2022-01-17 14:39:37 +01:00
let db_opts = db_options(config.rocksdb_max_open_files, &rocksdb_cache);
2021-10-16 15:19:25 +02:00
let cfs = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::list_cf(
&db_opts,
&config.database_path,
)
.unwrap_or_default();
let db = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::open_cf_descriptors(
&db_opts,
&config.database_path,
cfs.iter().map(|name| {
rocksdb::ColumnFamilyDescriptor::new(
name,
2022-01-17 14:39:37 +01:00
db_options(config.rocksdb_max_open_files, &rocksdb_cache),
)
2021-10-16 15:19:25 +02:00
}),
)?;
Ok(Arc::new(Engine {
rocks: db,
max_open_files: config.rocksdb_max_open_files,
2022-01-10 15:53:28 +01:00
cache: rocksdb_cache,
2021-10-16 15:19:25 +02:00
old_cfs: cfs,
}))
}
fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>> {
2021-10-16 15:19:25 +02:00
if !self.old_cfs.contains(&name.to_owned()) {
// Create if it didn't exist
2022-01-17 14:39:37 +01:00
let _ = self
.rocks
.create_cf(name, &db_options(self.max_open_files, &self.cache));
2021-10-16 15:19:25 +02:00
}
Ok(Arc::new(RocksDbEngineTree {
name,
db: Arc::clone(self),
watchers: Watchers::default(),
2021-12-20 10:16:22 +01:00
write_lock: RwLock::new(()),
2021-10-16 15:19:25 +02:00
}))
}
fn flush(&self) -> Result<()> {
2021-10-16 15:19:25 +02:00
// TODO?
Ok(())
}
fn memory_usage(&self) -> Result<String> {
2022-01-10 15:53:28 +01:00
let stats =
rocksdb::perf::get_memory_usage_stats(Some(&[&self.rocks]), Some(&[&self.cache]))?;
Ok(format!(
"Approximate memory usage of all the mem-tables: {:.3} MB\n\
2022-01-10 20:20:45 +01:00
Approximate memory usage of un-flushed mem-tables: {:.3} MB\n\
Approximate memory usage of all the table readers: {:.3} MB\n\
Approximate memory usage by cache: {:.3} MB\n\
2022-01-13 21:11:45 +01:00
Approximate memory usage by cache pinned: {:.3} MB\n\
2022-01-10 20:20:45 +01:00
",
2022-01-10 15:53:28 +01:00
stats.mem_table_total as f64 / 1024.0 / 1024.0,
stats.mem_table_unflushed as f64 / 1024.0 / 1024.0,
stats.mem_table_readers_total as f64 / 1024.0 / 1024.0,
2022-01-10 20:20:45 +01:00
stats.cache_total as f64 / 1024.0 / 1024.0,
self.cache.get_pinned_usage() as f64 / 1024.0 / 1024.0,
))
}
2021-10-16 15:19:25 +02:00
}
impl RocksDbEngineTree<'_> {
2022-01-10 15:53:28 +01:00
fn cf(&self) -> Arc<rocksdb::BoundColumnFamily<'_>> {
2021-10-16 15:19:25 +02:00
self.db.rocks.cf_handle(self.name).unwrap()
}
}
impl KvTree for RocksDbEngineTree<'_> {
2021-10-16 15:19:25 +02:00
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
2022-01-10 15:53:28 +01:00
Ok(self.db.rocks.get_cf(&self.cf(), key)?)
2021-10-16 15:19:25 +02:00
}
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
2021-12-20 10:16:22 +01:00
let lock = self.write_lock.read().unwrap();
2022-01-10 15:53:28 +01:00
self.db.rocks.put_cf(&self.cf(), key, value)?;
2021-12-20 10:16:22 +01:00
drop(lock);
2021-10-16 15:19:25 +02:00
self.watchers.wake(key);
2021-12-20 10:16:22 +01:00
2021-10-16 15:19:25 +02:00
Ok(())
}
fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
for (key, value) in iter {
2022-01-10 15:53:28 +01:00
self.db.rocks.put_cf(&self.cf(), key, value)?;
2021-10-16 15:19:25 +02:00
}
Ok(())
}
fn remove(&self, key: &[u8]) -> Result<()> {
2022-01-10 15:53:28 +01:00
Ok(self.db.rocks.delete_cf(&self.cf(), key)?)
2021-10-16 15:19:25 +02:00
}
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new(
self.db
.rocks
2022-01-10 15:53:28 +01:00
.iterator_cf(&self.cf(), rocksdb::IteratorMode::Start)
2023-05-21 11:51:36 +02:00
.map(|r| r.unwrap())
2021-10-16 15:19:25 +02:00
.map(|(k, v)| (Vec::from(k), Vec::from(v))),
)
}
fn iter_from<'a>(
&'a self,
from: &[u8],
backwards: bool,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new(
self.db
.rocks
.iterator_cf(
2022-01-10 15:53:28 +01:00
&self.cf(),
2021-10-16 15:19:25 +02:00
rocksdb::IteratorMode::From(
from,
if backwards {
rocksdb::Direction::Reverse
} else {
rocksdb::Direction::Forward
},
),
)
2023-05-21 11:51:36 +02:00
.map(|r| r.unwrap())
2021-10-16 15:19:25 +02:00
.map(|(k, v)| (Vec::from(k), Vec::from(v))),
)
}
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
2021-12-20 10:16:22 +01:00
let lock = self.write_lock.write().unwrap();
2022-10-10 14:09:11 +02:00
let old = self.db.rocks.get_cf(&self.cf(), key)?;
2021-10-16 15:19:25 +02:00
let new = utils::increment(old.as_deref()).unwrap();
2022-01-10 15:53:28 +01:00
self.db.rocks.put_cf(&self.cf(), key, &new)?;
2021-12-20 10:16:22 +01:00
drop(lock);
2021-10-16 15:19:25 +02:00
Ok(new)
}
fn increment_batch<'a>(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
2021-12-20 10:16:22 +01:00
let lock = self.write_lock.write().unwrap();
2021-10-16 15:19:25 +02:00
for key in iter {
2022-01-10 15:53:28 +01:00
let old = self.db.rocks.get_cf(&self.cf(), &key)?;
2021-10-16 15:19:25 +02:00
let new = utils::increment(old.as_deref()).unwrap();
2022-01-10 15:53:28 +01:00
self.db.rocks.put_cf(&self.cf(), key, new)?;
2021-10-16 15:19:25 +02:00
}
2021-12-20 10:16:22 +01:00
drop(lock);
2021-10-16 15:19:25 +02:00
Ok(())
}
fn scan_prefix<'a>(
&'a self,
prefix: Vec<u8>,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new(
self.db
.rocks
.iterator_cf(
2022-01-10 15:53:28 +01:00
&self.cf(),
2021-10-16 15:19:25 +02:00
rocksdb::IteratorMode::From(&prefix, rocksdb::Direction::Forward),
)
2023-05-21 11:51:36 +02:00
.map(|r| r.unwrap())
2021-10-16 15:19:25 +02:00
.map(|(k, v)| (Vec::from(k), Vec::from(v)))
.take_while(move |(k, _)| k.starts_with(&prefix)),
)
}
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
self.watchers.watch(prefix)
}
}