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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#![feature(async_closure,iter_partition_in_place,drain_filter,
extended_key_value_attributes, backtrace)]
#![doc=include_str!("../readme.md")]
mod error;
pub use error::{EyrosError,EyrosErrorKind,Error};
mod store;
pub use store::Storage;
#[cfg(not(feature="wasm"))] #[doc(hidden)] pub use store::FileStore;
mod setup;
pub use setup::{Setup,SetupFields};
mod tree;
#[doc(hidden)] pub use tree::{Tree,TreeRef,TreeId,Merge};
mod bytes;
mod query;
#[doc(hidden)] pub use query::QueryStream;
mod unfold;
mod tree_file;
use tree_file::TreeFile;
mod value;
pub use value::Value;
#[cfg(feature="wasm")]
mod wasm;
mod batch;
pub use batch::{BatchFields,BatchOptions};
use async_std::{sync::{Arc,Mutex}};
use random_access_storage::RandomAccess;
use desert::{ToBytes,FromBytes,CountBytes};
use core::ops::{Add,Div};
use std::fmt::Debug;
pub trait Scalar: Clone+PartialOrd+From<u8>+Debug
+Send+Sync+'static+PartialEq
+ToBytes+CountBytes+FromBytes
+Add<Output=Self>+Div<Output=Self> {}
impl Scalar for f32 {}
impl Scalar for f64 {}
impl Scalar for u8 {}
impl Scalar for u16 {}
impl Scalar for u32 {}
impl Scalar for u64 {}
impl Scalar for i16 {}
impl Scalar for i32 {}
impl Scalar for i64 {}
#[doc(hidden)] pub trait RA: RandomAccess<Error=Error>+Unpin+Send+Sync+'static {}
impl<S> RA for S where S: RandomAccess<Error=Error>+Unpin+Send+Sync+'static {}
#[derive(Debug,Clone,PartialEq,PartialOrd)]
pub enum Coord<X> where X: Scalar {
Scalar(X),
Interval(X,X)
}
#[async_trait::async_trait]
pub trait Point: 'static+Overlap+Clone+Send+Sync+Debug{
type Bounds: Clone+Send+Sync+Debug+ToBytes+FromBytes+CountBytes+Overlap;
fn to_bounds(&self) -> Result<Self::Bounds,Error>;
fn from_bounds(bounds: &Self::Bounds) -> Self;
fn check(&self) -> Result<(),Error>;
}
pub trait Overlap {
fn overlap(&self, other: &Self) -> bool;
}
macro_rules! impl_point {
($Tree:ident,$open_from_path:ident,($($T:tt),+),($($i:tt),+)) => {
pub use tree::$Tree;
#[cfg(not(feature="wasm"))] pub use store::$open_from_path;
#[async_trait::async_trait]
impl<$($T),+> Point for ($(Coord<$T>),+) where $($T: Scalar),+ {
type Bounds = (($($T),+),($($T),+));
fn to_bounds(&self) -> Result<Self::Bounds,Error> {
Ok((
($(match &self.$i {
Coord::Scalar(_) => {
return EyrosErrorKind::ScalarInBounds {}.raise();
},
Coord::Interval(min,_) => min.clone(),
}),+),
($(match &self.$i {
Coord::Scalar(_) => {
return EyrosErrorKind::ScalarInBounds {}.raise();
},
Coord::Interval(_,max) => max.clone(),
}),+),
))
}
fn from_bounds(bounds: &Self::Bounds) -> Self {
($(Coord::Interval((bounds.0).$i.clone(),(bounds.1).$i.clone())),+)
}
fn check(&self) -> Result<(),Error> {
$(match &(self.$i) {
Coord::Interval(min,max) => {
if !(min <= max) {
return EyrosErrorKind::IntervalSides {
dimension: $i,
min: format!["{:?}", min],
max: format!["{:?}", max],
}.raise();
}
},
_ => {}
};)+
Ok(())
}
}
}
}
#[cfg(feature="2d")] impl_point![Tree2,open_from_path2,(P0,P1),(0,1)];
#[cfg(feature="3d")] impl_point![Tree3,open_from_path3,(P0,P1,P2),(0,1,2)];
#[cfg(feature="4d")] impl_point![Tree4,open_from_path4,(P0,P1,P2,P3),(0,1,2,3)];
#[cfg(feature="5d")] impl_point![Tree5,open_from_path5,(P0,P1,P2,P3,P4),(0,1,2,3,4)];
#[cfg(feature="6d")] impl_point![Tree6,open_from_path6,(P0,P1,P2,P3,P4,P5),(0,1,2,3,4,5)];
#[cfg(feature="7d")] impl_point![Tree7,open_from_path7,(P0,P1,P2,P3,P4,P5,P6),(0,1,2,3,4,5,6)];
#[cfg(feature="8d")] impl_point![Tree8,open_from_path8,(P0,P1,P2,P3,P4,P5,P6,P7),(0,1,2,3,4,5,6,7)];
#[derive(Debug,Clone)]
pub enum Row<P,V> where P: Point, V: Value {
Insert(P,V),
Delete(P,V::Id)
}
#[doc(hidden)]
pub type Root<P> = Option<tree::TreeRef<P>>;
#[doc(hidden)]
#[derive(Debug,Clone)]
pub struct Meta<P> where P: Point {
pub roots: Vec<Root<P>>,
pub next_tree: TreeId,
}
pub struct DB<S,T,P,V>
where S: RA, P: Point, V: Value, T: Tree<P,V> {
pub storage: Arc<Mutex<Box<dyn Storage<S>>>>,
pub fields: Arc<SetupFields>,
pub meta_store: Arc<Mutex<S>>,
pub meta: Meta<P>,
pub trees: Arc<Mutex<TreeFile<S,T,P,V>>>,
}
impl<S,T,P,V> DB<S,T,P,V>
where S: RA, P: Point, V: Value, T: Tree<P,V> {
pub async fn open_from_setup(setup: Setup<S>) -> Result<Self,Error> {
let mut meta_store = setup.storage.lock().await.open("meta").await?;
let meta = match meta_store.len().await? {
0 => Meta { roots: vec![], next_tree: 0 },
n => Meta::from_bytes(&meta_store.read(0,n).await?)?.1,
};
let fields = Arc::new(setup.fields);
let trees = TreeFile::new(Arc::clone(&fields), Arc::clone(&setup.storage));
Ok(Self {
storage: Arc::clone(&setup.storage),
fields,
meta_store: Arc::new(Mutex::new(meta_store)),
meta,
trees: Arc::new(Mutex::new(trees)),
})
}
pub async fn open_from_storage(storage: Box<dyn Storage<S>>) -> Result<Self,Error> {
Setup::from_storage(storage).build().await
}
pub async fn batch(&mut self, rows: &[Row<P,V>]) -> Result<(),Error> {
let opts = BatchOptions::new().rebuild_depth(self.fields.rebuild_depth);
self.batch_with_options(rows, &opts).await
}
pub async fn batch_with_rebuild_depth(&mut self, rebuild_depth: usize, rows: &[Row<P,V>])
-> Result<(),Error> {
let opts = BatchOptions::new().rebuild_depth(rebuild_depth);
self.batch_with_options(rows, &opts).await
}
pub async fn batch_with_options(&mut self, rows: &[Row<P,V>], opts: &BatchOptions) -> Result<(),Error> {
if rows.is_empty() { return Ok(()) }
for row in rows.iter() {
match row {
Row::Insert(p,_) => p.check()?,
Row::Delete(p,_) => p.check()?,
}
}
let inserts: Vec<(&P,&V)> = rows.iter()
.map(|row| match row {
Row::Insert(p,v) => Some((p,v)),
_ => None
})
.filter(|row| !row.is_none())
.map(|x| x.unwrap())
.collect();
let deletes: Vec<(P,V::Id)> = rows.iter()
.map(|row| match row {
Row::Delete(p,x) => Some((p.clone(),x.clone())),
_ => None
})
.filter(|row| !row.is_none())
.map(|x| x.unwrap())
.collect();
let merge_trees = Arc::new(
self.meta.roots.iter()
.take_while(|r| r.is_some())
.map(|r| r.as_ref().unwrap().clone())
.collect::<Vec<TreeRef<P>>>()
);
let mut m = Merge {
fields: Arc::clone(&self.fields),
inserts: inserts.as_slice(),
deletes: Arc::new(deletes),
inputs: Arc::clone(&merge_trees),
roots: self.meta.roots.clone(),
trees: Arc::clone(&self.trees),
next_tree: &mut self.meta.next_tree,
rebuild_depth: opts.fields.rebuild_depth,
error_if_missing: opts.fields.error_if_missing,
};
if inserts.is_empty() {
m.remove().await?;
return Ok(());
}
let (tr,t,rm_trees,create_trees) = m.merge().await?;
let trees = &mut self.trees.lock().await;
for r in rm_trees.iter() {
trees.remove(r).await;
}
for (r,t) in create_trees.iter() {
trees.put(r,Arc::clone(t)).await;
}
trees.put(&tr.id, Arc::new(Mutex::new(t))).await;
for i in 0..merge_trees.len() {
if i < self.meta.roots.len() {
self.meta.roots[i] = None;
} else {
self.meta.roots.push(None);
}
}
if merge_trees.len() < self.meta.roots.len() {
self.meta.roots[merge_trees.len()] = Some(tr);
} else {
self.meta.roots.push(Some(tr));
}
Ok(())
}
pub async fn optimize(&mut self, rebuild_depth: usize) -> Result<(),Error> {
let merge_trees = Arc::new(
self.meta.roots.iter()
.filter(|r| r.is_some())
.map(|r| r.as_ref().unwrap().clone())
.collect::<Vec<TreeRef<P>>>()
);
let mut m = Merge {
fields: Arc::clone(&self.fields),
inserts: &vec![],
deletes: Arc::new(vec![]),
inputs: Arc::clone(&merge_trees),
roots: self.meta.roots.clone(),
trees: Arc::clone(&self.trees),
next_tree: &mut self.meta.next_tree,
rebuild_depth,
error_if_missing: true,
};
let (tr,t,rm_trees,create_trees) = m.merge().await?;
let trees = &mut self.trees.lock().await;
for r in rm_trees.iter() {
trees.remove(r).await;
}
for (r,t) in create_trees.iter() {
trees.put(r,Arc::clone(t)).await;
}
trees.put(&tr.id, Arc::new(Mutex::new(t))).await;
self.meta.roots.clear();
self.meta.roots.push(Some(tr));
Ok(())
}
pub async fn sync(&mut self) -> Result<(),Error> {
self.trees.lock().await.sync().await?;
let rbytes = self.meta.to_bytes()?;
self.meta_store.lock().await.write(0, &rbytes).await?;
Ok(())
}
pub async fn query(&mut self, bbox: &P::Bounds) -> Result<query::QStream<P,V>,Error> {
let mut queries = vec![];
for root in self.meta.roots.iter() {
if let Some(r) = root {
let mut trees = self.trees.lock().await;
let t = trees.get(&r.id).await?;
queries.push(t.lock().await.query(Arc::clone(&self.trees), bbox));
}
}
<QueryStream<P,V>>::from_queries(queries)
}
}