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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use std::{
ops::Deref,
sync::{atomic::AtomicU64, Arc},
};
use pagecache::FastMap8;
use parking_lot::RwLock;
use super::*;
#[derive(Clone)]
pub struct Db {
context: Context,
pub(crate) default: Tree,
tenants: Arc<RwLock<FastMap8<Vec<u8>, Tree>>>,
}
unsafe impl Send for Db {}
unsafe impl Sync for Db {}
impl Deref for Db {
type Target = Tree;
fn deref(&self) -> &Tree {
&self.default
}
}
impl std::fmt::Debug for Db {
fn fmt(
&self,
f: &mut std::fmt::Formatter<'_>,
) -> std::result::Result<(), std::fmt::Error> {
let tenants = self.tenants.read();
write!(f, "Db {{")?;
for (raw_name, tree) in tenants.iter() {
let name = std::str::from_utf8(&raw_name)
.ok()
.map_or_else(|| format!("{:?}", raw_name), String::from);
write!(f, "tree: {:?} contents: {:?}", name, tree)?;
}
write!(f, "}}")?;
Ok(())
}
}
impl Db {
pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
let config = ConfigBuilder::new().path(path).build();
Self::start(config)
}
#[doc(hidden)]
#[deprecated(since = "0.24.2", note = "replaced by `Db:open`")]
pub fn start_default<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
Self::open(path)
}
pub fn start(config: Config) -> Result<Self> {
let _measure = Measure::new(&M.tree_start);
let context = Context::start(config)?;
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
{
if !context.read_only {
let flusher_pagecache = context.pagecache.clone();
let flusher = context.flush_every_ms.map(move |fem| {
flusher::Flusher::new(
"log flusher".to_owned(),
flusher_pagecache,
fem,
)
});
*context._flusher.lock() = flusher;
}
}
let guard = pin();
let default =
meta::open_tree(&context, DEFAULT_TREE_ID.to_vec(), &guard)?;
let ret = Self {
context: context.clone(),
default,
tenants: Arc::new(RwLock::new(FastMap8::default())),
};
let mut tenants = ret.tenants.write();
for (id, root) in context.pagecache.meta(&guard)?.tenants() {
let tree = Tree(Arc::new(TreeInner {
tree_id: id.clone(),
subscriptions: Subscriptions::default(),
context: context.clone(),
root: AtomicU64::new(root),
concurrency_control: RwLock::new(()),
merge_operator: RwLock::new(None),
}));
tenants.insert(id, tree);
}
drop(tenants);
Ok(ret)
}
pub fn open_tree<V: AsRef<[u8]>>(&self, name: V) -> Result<Tree> {
let name = name.as_ref();
let tenants = self.tenants.read();
if let Some(tree) = tenants.get(name) {
return Ok(tree.clone());
}
drop(tenants);
let guard = pin();
let mut tenants = self.tenants.write();
if let Some(tree) = tenants.get(name) {
return Ok(tree.clone());
}
let tree = meta::open_tree(&self.context, name.to_vec(), &guard)?;
tenants.insert(name.to_vec(), tree.clone());
Ok(tree)
}
pub fn drop_tree(&self, name: &[u8]) -> Result<bool> {
if name == DEFAULT_TREE_ID {
return Err(Error::Unsupported(
"cannot remove the core structures".into(),
));
}
trace!("dropping tree {:?}", name,);
let mut tenants = self.tenants.write();
let tree = if let Some(tree) = tenants.remove(&*name) {
tree
} else {
return Ok(false);
};
let guard = pin();
let mut root_id =
Some(self.context.pagecache.meta_pid_for_name(&name, &guard)?);
let mut leftmost_chain: Vec<PageId> = vec![root_id.unwrap()];
let mut cursor = root_id.unwrap();
while let Some(view) = self.view_for_pid(cursor, &guard)? {
if let Some(index) = view.data.index_ref() {
let leftmost_child = index[0].1;
leftmost_chain.push(leftmost_child);
cursor = leftmost_child;
} else {
break;
}
}
loop {
let res = self
.context
.pagecache
.cas_root_in_meta(&name, root_id, None, &guard)?;
if let Err(actual_root) = res {
root_id = actual_root;
} else {
break;
}
}
tree.root
.store(u64::max_value(), std::sync::atomic::Ordering::SeqCst);
drop(tenants);
tree.gc_pages(leftmost_chain)?;
guard.flush();
Ok(true)
}
pub fn tree_names(&self) -> Vec<Vec<u8>> {
let tenants = self.tenants.read();
tenants.iter().map(|(name, _)| name.clone()).collect()
}
pub fn was_recovered(&self) -> bool {
self.context.was_recovered()
}
pub fn generate_id(&self) -> Result<u64> {
self.context.generate_id()
}
pub fn export(
&self,
) -> Vec<(
CollectionType,
CollectionName,
impl Iterator<Item = Vec<Vec<u8>>>,
)> {
let tenants = self.tenants.read();
let mut ret = vec![];
for (name, tree) in tenants.iter() {
ret.push((
b"tree".to_vec(),
name.to_vec(),
tree.iter().map(|kv| {
let kv = kv.unwrap();
vec![kv.0.to_vec(), kv.1.to_vec()]
}),
));
}
ret
}
pub fn import(
&self,
export: Vec<(
CollectionType,
CollectionName,
impl Iterator<Item = Vec<Vec<u8>>>,
)>,
) {
for (collection_type, collection_name, collection_iter) in export {
match collection_type {
ref t if t == b"tree" => {
let tree = self
.open_tree(collection_name)
.expect("failed to open new tree during import");
for mut kv in collection_iter {
let v = kv
.pop()
.expect("failed to get value from tree export");
let k = kv
.pop()
.expect("failed to get key from tree export");
tree.insert(k, v).expect(
"failed to insert value during tree import",
);
}
}
other => panic!("unknown collection type {:?}", other),
}
}
}
#[doc(hidden)]
pub fn space_amplification(&self) -> Result<f64> {
self.context.pagecache.space_amplification()
}
}
type CollectionType = Vec<u8>;
type CollectionName = Vec<u8>;