forked from romanz/electrs
-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathdb.rs
218 lines (183 loc) · 6.04 KB
/
db.rs
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use rocksdb;
use std::path::Path;
use crate::config::Config;
use crate::util::{bincode, Bytes};
static DB_VERSION: u32 = 2;
#[derive(Debug, Eq, PartialEq)]
pub struct DBRow {
pub key: Vec<u8>,
pub value: Vec<u8>,
}
pub struct ScanIterator<'a> {
prefix: Vec<u8>,
iter: rocksdb::DBIterator<'a>,
done: bool,
}
impl<'a> Iterator for ScanIterator<'a> {
type Item = DBRow;
fn next(&mut self) -> Option<DBRow> {
if self.done {
return None;
}
let (key, value) = self.iter.next()?.expect("valid iterator");
if !key.starts_with(&self.prefix) {
self.done = true;
return None;
}
Some(DBRow {
key: key.to_vec(),
value: value.to_vec(),
})
}
}
pub struct ReverseScanIterator<'a> {
prefix: Vec<u8>,
iter: rocksdb::DBRawIterator<'a>,
done: bool,
}
impl<'a> Iterator for ReverseScanIterator<'a> {
type Item = DBRow;
fn next(&mut self) -> Option<DBRow> {
if self.done || !self.iter.valid() {
return None;
}
let key = self.iter.key().unwrap();
if !key.starts_with(&self.prefix) {
self.done = true;
return None;
}
let row = DBRow {
key: key.into(),
value: self.iter.value().unwrap().into(),
};
self.iter.prev();
Some(row)
}
}
#[derive(Debug)]
pub struct DB {
db: rocksdb::DB,
}
#[derive(Copy, Clone, Debug)]
pub enum DBFlush {
Disable,
Enable,
}
impl DB {
pub fn open(path: &Path, config: &Config) -> DB {
debug!("opening DB at {:?}", path);
let mut db_opts = rocksdb::Options::default();
db_opts.create_if_missing(true);
db_opts.set_max_open_files(100_000); // TODO: make sure to `ulimit -n` this process correctly
db_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
db_opts.set_compression_type(rocksdb::DBCompressionType::Snappy);
db_opts.set_target_file_size_base(1_073_741_824);
db_opts.set_write_buffer_size(256 << 20);
db_opts.set_disable_auto_compactions(true); // for initial bulk load
// db_opts.set_advise_random_on_open(???);
db_opts.set_compaction_readahead_size(1 << 20);
db_opts.increase_parallelism(2);
// let mut block_opts = rocksdb::BlockBasedOptions::default();
// block_opts.set_block_size(???);
let db = DB {
db: rocksdb::DB::open(&db_opts, path).expect("failed to open RocksDB"),
};
db.verify_compatibility(config);
db
}
pub fn full_compaction(&self) {
// TODO: make sure this doesn't fail silently
debug!("starting full compaction on {:?}", self.db);
self.db.compact_range(None::<&[u8]>, None::<&[u8]>);
debug!("finished full compaction on {:?}", self.db);
}
pub fn enable_auto_compaction(&self) {
let opts = [("disable_auto_compactions", "false")];
self.db.set_options(&opts).unwrap();
}
pub fn raw_iterator(&self) -> rocksdb::DBRawIterator {
self.db.raw_iterator()
}
pub fn iter_scan(&self, prefix: &[u8]) -> ScanIterator {
ScanIterator {
prefix: prefix.to_vec(),
iter: self.db.prefix_iterator(prefix),
done: false,
}
}
pub fn iter_scan_from(&self, prefix: &[u8], start_at: &[u8]) -> ScanIterator {
let iter = self.db.iterator(rocksdb::IteratorMode::From(
start_at,
rocksdb::Direction::Forward,
));
ScanIterator {
prefix: prefix.to_vec(),
iter,
done: false,
}
}
pub fn iter_scan_reverse(&self, prefix: &[u8], prefix_max: &[u8]) -> ReverseScanIterator {
let mut iter = self.db.raw_iterator();
iter.seek_for_prev(prefix_max);
ReverseScanIterator {
prefix: prefix.to_vec(),
iter,
done: false,
}
}
pub fn write(&self, mut rows: Vec<DBRow>, flush: DBFlush) {
debug!(
"writing {} rows to {:?}, flush={:?}",
rows.len(),
self.db,
flush
);
rows.sort_unstable_by(|a, b| a.key.cmp(&b.key));
let mut batch = rocksdb::WriteBatch::default();
for row in rows {
#[cfg(not(feature = "oldcpu"))]
batch.put(&row.key, &row.value);
#[cfg(feature = "oldcpu")]
batch.put(&row.key, &row.value).unwrap();
}
let do_flush = match flush {
DBFlush::Enable => true,
DBFlush::Disable => false,
};
let mut opts = rocksdb::WriteOptions::new();
opts.set_sync(do_flush);
opts.disable_wal(!do_flush);
self.db.write_opt(batch, &opts).unwrap();
}
pub fn flush(&self) {
self.db.flush().unwrap();
}
pub fn put(&self, key: &[u8], value: &[u8]) {
self.db.put(key, value).unwrap();
}
pub fn put_sync(&self, key: &[u8], value: &[u8]) {
let mut opts = rocksdb::WriteOptions::new();
opts.set_sync(true);
self.db.put_opt(key, value, &opts).unwrap();
}
pub fn get(&self, key: &[u8]) -> Option<Bytes> {
self.db.get(key).unwrap().map(|v| v.to_vec())
}
fn verify_compatibility(&self, config: &Config) {
let mut compatibility_bytes = bincode::serialize_little(&DB_VERSION).unwrap();
if config.light_mode {
// append a byte to indicate light_mode is enabled.
// we're not letting bincode serialize this so that the compatibility bytes won't change
// (and require a reindex) when light_mode is disabled. this should be changed the next
// time we bump DB_VERSION and require a re-index anyway.
compatibility_bytes.push(1);
}
match self.get(b"V") {
None => self.put(b"V", &compatibility_bytes),
Some(ref x) if x != &compatibility_bytes => {
panic!("Incompatible database found. Please reindex.")
}
Some(_) => (),
}
}
}