1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use crate::NUM_COLS;
use snarkvm_dpc::{errors::StorageError, DatabaseTransaction, Op, Storage};
use rocksdb::{ColumnFamily, ColumnFamilyDescriptor, IteratorMode, Options, WriteBatch, DB};
use std::path::Path;
fn convert_err(err: rocksdb::Error) -> StorageError {
StorageError::Crate("rocksdb", err.to_string())
}
pub struct RocksDb {
db: Option<DB>,
cf_names: Vec<String>,
}
impl Storage for RocksDb {
const IN_MEMORY: bool = false;
fn open(path: Option<&Path>, secondary_path: Option<&Path>) -> Result<Self, StorageError> {
assert!(path.is_some(), "RocksDB must have an associated filesystem path!");
let primary_path = path.unwrap();
if let Some(secondary_path) = secondary_path {
RocksDb::open_secondary_cf(primary_path, secondary_path, NUM_COLS)
} else {
RocksDb::open_cf(primary_path, NUM_COLS)
}
}
fn get(&self, col: u32, key: &[u8]) -> Result<Option<Vec<u8>>, StorageError> {
self.db().get_cf(self.get_cf_ref(col), key).map_err(convert_err)
}
#[allow(clippy::type_complexity)]
fn get_col(&self, col: u32) -> Result<Vec<(Box<[u8]>, Box<[u8]>)>, StorageError> {
Ok(self
.db()
.iterator_cf(self.get_cf_ref(col), IteratorMode::Start)
.collect())
}
fn get_keys(&self, col: u32) -> Result<Vec<Box<[u8]>>, StorageError> {
Ok(self
.db()
.iterator_cf(self.get_cf_ref(col), IteratorMode::Start)
.map(|(k, _v)| k)
.collect())
}
fn put<K: AsRef<[u8]>, V: AsRef<[u8]>>(&self, col: u32, key: K, value: V) -> Result<(), StorageError> {
self.db().put_cf(self.get_cf_ref(col), key, value).map_err(convert_err)
}
fn batch(&self, transaction: DatabaseTransaction) -> Result<(), StorageError> {
let mut batch = WriteBatch::default();
for operation in transaction.0 {
match operation {
Op::Insert { col, key, value } => {
let cf = self.get_cf_ref(col);
batch.put_cf(cf, &key, value);
}
Op::Delete { col, key } => {
let cf = self.get_cf_ref(col);
batch.delete_cf(cf, &key);
}
};
}
self.db().write(batch).map_err(convert_err)?;
Ok(())
}
fn exists(&self, col: u32, key: &[u8]) -> bool {
match self.db().get_cf(self.get_cf_ref(col), key) {
Ok(val) => val.is_some(),
Err(_) => false,
}
}
fn try_catch_up_with_primary(&self) -> Result<(), StorageError> {
self.db()
.try_catch_up_with_primary()
.map_err(|e| StorageError::Message(format!("Can't catch up with primary storage: {}", e)))
}
}
impl Drop for RocksDb {
fn drop(&mut self) {
let db = self.db.take().unwrap();
let _path = db.path().to_path_buf();
drop(db);
#[cfg(feature = "test")]
{
let _ = DB::destroy(&Options::default(), _path);
}
}
}
impl RocksDb {
fn db(&self) -> &DB {
self.db.as_ref().unwrap()
}
pub fn open_cf<P: AsRef<Path>>(path: P, num_cfs: u32) -> Result<Self, StorageError> {
let mut cfs = Vec::with_capacity(num_cfs as usize);
let mut cf_names: Vec<String> = Vec::with_capacity(cfs.len());
for column in 0..num_cfs {
let column_name = format!("col{}", column.to_string());
let mut cf_opts = Options::default();
cf_opts.set_max_write_buffer_number(16);
cfs.push(ColumnFamilyDescriptor::new(&column_name, cf_opts));
cf_names.push(column_name);
}
let mut storage_opts = Options::default();
storage_opts.increase_parallelism(3);
storage_opts.create_missing_column_families(true);
storage_opts.create_if_missing(true);
let storage = DB::open_cf_descriptors(&storage_opts, path, cfs).map_err(convert_err)?;
Ok(Self {
db: Some(storage),
cf_names,
})
}
pub fn open_secondary_cf<P: AsRef<Path> + Clone>(
primary_path: P,
secondary_path: P,
num_cfs: u32,
) -> Result<Self, StorageError> {
let mut cf_names: Vec<String> = Vec::with_capacity(num_cfs as usize);
for column in 0..num_cfs {
let column_name = format!("col{}", column.to_string());
cf_names.push(column_name);
}
let mut storage_opts = Options::default();
storage_opts.increase_parallelism(2);
let storage = DB::open_cf_as_secondary(&storage_opts, primary_path, secondary_path, cf_names.clone())
.map_err(convert_err)?;
storage.try_catch_up_with_primary().map_err(convert_err)?;
Ok(Self {
db: Some(storage),
cf_names,
})
}
pub(crate) fn get_cf_ref(&self, index: u32) -> &ColumnFamily {
self.db()
.cf_handle(&self.cf_names[index as usize])
.expect("the column family exists")
}
}