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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::path::Path;

use datacake_crdt::{HLCTimestamp, Key};
use datacake_eventual_consistency::{Document, DocumentMetadata};
use flume::{self, Receiver, Sender};
use futures::channel::oneshot;
use heed::byteorder::LittleEndian;
use heed::types::{ByteSlice, Str, Unit, U64};
use heed::{Database, Env, EnvOpenOptions};

type KvDB = Database<U64<LittleEndian>, ByteSlice>;
type MetaDB = Database<U64<LittleEndian>, U64<LittleEndian>>;
type KeyspaceDB = Database<Str, Unit>;
type DatabaseKeyspace = BTreeMap<String, (KvDB, MetaDB)>;
type Task = Box<dyn FnOnce(&Env, &KeyspaceDB, &mut DatabaseKeyspace) + Send + 'static>;

const DEFAULT_MAP_SIZE: usize = 10 << 20;
const MAX_NUM_DBS: u32 = 250;
const CAPACITY: usize = 10;

#[derive(Debug, Clone)]
/// A asynchronous wrapper around a LMDB database.
///
/// These operations will be ran in a background thread preventing
/// any IO operations from blocking the async context.
pub struct StorageHandle {
    tx: Sender<Task>,
    env: Env,
}

impl StorageHandle {
    /// Connects to the LMDB database.
    ///
    /// This spawns 1 background threads with actions being executed within that thread.
    ///
    /// This approach reduces the affect of writes blocking reads and vice-versa.
    ///
    /// If the database does not already exist it will be created.
    ///
    /// ```rust
    /// use datacake_lmdb::StorageHandle;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let storage = StorageHandle::open("./my-lmdb-data").await.expect("Create database");
    /// # drop(storage);
    /// # let _ = std::fs::remove_dir_all("./my-lmdb-data");
    /// # }
    /// ```
    pub async fn open(path: impl AsRef<Path>) -> heed::Result<Self> {
        let (tx, env) = setup_database(path).await?;
        Ok(Self { tx, env })
    }

    #[inline]
    /// Get the current heed environment.
    pub fn env(&self) -> &Env {
        &self.env
    }

    /// Get the current keyspace list.
    pub(crate) async fn keyspace_list(&self) -> heed::Result<Vec<String>> {
        let (tx, rx) = oneshot::channel();

        let cb = move |env: &Env,
                       keyspace_list: &KeyspaceDB,
                       _databases: &mut DatabaseKeyspace| {
            let res = read_keyspace_list(env, keyspace_list);
            let _ = tx.send(res);
        };

        self.tx
            .send_async(Box::new(cb))
            .await
            .expect("send message");

        rx.await.unwrap()
    }

    /// Execute a PUT operation on the DB.
    pub(crate) async fn put_kv(
        &self,
        keyspace: &str,
        doc: Document,
    ) -> heed::Result<()> {
        self.submit_task(keyspace, move |env: &Env, kv: &KvDB, meta: &MetaDB| {
            let mut txn = env.write_txn()?;
            kv.put(&mut txn, &doc.id(), doc.data())?;
            meta.put(&mut txn, &doc.id(), &doc.last_updated().as_u64())?;
            txn.commit()?;
            Ok(())
        })
        .await
    }

    /// Execute a many PUT operations on the DB.
    pub(crate) async fn put_many_kv(
        &self,
        keyspace: &str,
        docs: impl Iterator<Item = Document>,
    ) -> heed::Result<()> {
        let docs = Vec::from_iter(docs);

        self.submit_task(keyspace, move |env: &Env, kv: &KvDB, meta: &MetaDB| {
            let mut txn = env.write_txn()?;
            for doc in docs {
                kv.put(&mut txn, &doc.id(), doc.data())?;
                meta.put(&mut txn, &doc.id(), &doc.last_updated().as_u64())?;
            }
            txn.commit()?;
            Ok(())
        })
        .await
    }

    /// Get the metadata list from the DB.
    pub(crate) async fn get_metadata(
        &self,
        keyspace: &str,
    ) -> heed::Result<Vec<(Key, HLCTimestamp, bool)>> {
        self.submit_task(keyspace, move |env: &Env, kv: &KvDB, meta: &MetaDB| {
            let mut entries = Vec::new();
            let txn = env.read_txn()?;

            for pair in meta.iter(&txn)? {
                let (id, ts) = pair?;

                let is_tombstone = kv.get(&txn, &id)?.is_none();
                entries.push((id, HLCTimestamp::from_u64(ts), is_tombstone));
            }

            Ok(entries)
        })
        .await
    }

    /// Mark an entry as a tombstone.
    pub(crate) async fn mark_tombstone(
        &self,
        keyspace: &str,
        key: Key,
        ts: HLCTimestamp,
    ) -> heed::Result<()> {
        self.submit_task(keyspace, move |env: &Env, kv: &KvDB, meta: &MetaDB| {
            let mut txn = env.write_txn()?;
            kv.delete(&mut txn, &key)?;
            meta.put(&mut txn, &key, &ts.as_u64())?;
            txn.commit()?;
            Ok(())
        })
        .await
    }

    /// Mark an entry as a tombstone.
    pub(crate) async fn mark_many_as_tombstone(
        &self,
        keyspace: &str,
        docs: impl Iterator<Item = DocumentMetadata>,
    ) -> heed::Result<()> {
        let docs = Vec::from_iter(docs);

        self.submit_task(keyspace, move |env: &Env, kv: &KvDB, meta: &MetaDB| {
            let mut txn = env.write_txn()?;
            for doc in docs {
                kv.delete(&mut txn, &doc.id)?;
                meta.put(&mut txn, &doc.id, &doc.last_updated.as_u64())?;
            }
            txn.commit()?;
            Ok(())
        })
        .await
    }

    /// Clear a tombstone entry.
    pub(crate) async fn remove_tombstones(
        &self,
        keyspace: &str,
        keys: impl Iterator<Item = Key>,
    ) -> heed::Result<()> {
        let keys = Vec::from_iter(keys);

        self.submit_task(keyspace, move |env: &Env, _kv: &KvDB, meta: &MetaDB| {
            let mut txn = env.write_txn()?;
            for key in keys {
                meta.delete(&mut txn, &key)?; // Our entry will already be removed.
            }
            txn.commit()?;
            Ok(())
        })
        .await
    }

    /// Execute a PUT operation on the DB.
    pub(crate) async fn get(
        &self,
        keyspace: &str,
        key: u64,
    ) -> heed::Result<Option<Document>> {
        self.submit_task(keyspace, move |env: &Env, kv: &KvDB, meta: &MetaDB| {
            let txn = env.read_txn()?;
            if let Some(doc) = kv.get(&txn, &key)? {
                let ts = meta.get(&txn, &key)?.unwrap();
                Ok(Some(Document::new(key, HLCTimestamp::from_u64(ts), doc)))
            } else {
                Ok(None)
            }
        })
        .await
    }

    /// Execute a PUT operation on the DB.
    pub(crate) async fn get_many(
        &self,
        keyspace: &str,
        keys: impl Iterator<Item = Key>,
    ) -> heed::Result<Vec<Document>> {
        let keys = Vec::from_iter(keys);

        self.submit_task(keyspace, move |env: &Env, kv: &KvDB, meta: &MetaDB| {
            let mut docs = Vec::with_capacity(keys.len());
            let txn = env.read_txn()?;
            for key in keys {
                if let Some(doc) = kv.get(&txn, &key)? {
                    let ts = meta.get(&txn, &key)?.unwrap();
                    docs.push(Document::new(key, HLCTimestamp::from_u64(ts), doc));
                }
            }

            Ok(docs)
        })
        .await
    }

    /// Submits a writer task to execute on the KV store.
    ///
    /// This executes the callback on the memory view connection which should be
    /// significantly faster to modify or read.
    async fn submit_task<CB, T>(&self, keyspace: &str, inner: CB) -> heed::Result<T>
    where
        T: Send + 'static,
        CB: FnOnce(&Env, &KvDB, &MetaDB) -> heed::Result<T> + Send + 'static,
    {
        let (tx, rx) = oneshot::channel();
        let keyspace = keyspace.to_owned();

        let cb = move |env: &Env,
                       keyspace_list: &KeyspaceDB,
                       databases: &mut DatabaseKeyspace| {
            let res = match databases.entry(keyspace) {
                Entry::Vacant(entry) => {
                    match try_create_dbs(env, keyspace_list, entry.key()) {
                        Ok(dbs) => {
                            let (kv, meta) = entry.insert(dbs);
                            inner(env, kv, meta)
                        },
                        Err(e) => Err(e),
                    }
                },
                Entry::Occupied(existing) => {
                    let (kv, meta) = existing.get();
                    inner(env, kv, meta)
                },
            };

            let _ = tx.send(res);
        };

        self.tx
            .send_async(Box::new(cb))
            .await
            .expect("send message");

        rx.await.unwrap()
    }
}

fn try_create_dbs(
    env: &Env,
    keyspace_list: &KeyspaceDB,
    keyspace: &str,
) -> heed::Result<(KvDB, MetaDB)> {
    let kv_name = format!("datacake-{keyspace}-kv");
    let meta_name = format!("datacake-{keyspace}-meta");

    let mut txn = env.write_txn()?;
    keyspace_list.put(&mut txn, keyspace, &())?;
    let kv_db = env.create_database(&mut txn, Some(&kv_name))?;
    let meta_db = env.create_database(&mut txn, Some(&meta_name))?;
    txn.commit()?;

    Ok((kv_db, meta_db))
}

fn read_keyspace_list(
    env: &Env,
    keyspace_list: &KeyspaceDB,
) -> heed::Result<Vec<String>> {
    let mut list = Vec::new();
    let txn = env.read_txn()?;

    for key in keyspace_list.iter(&txn)? {
        let (keyspace, _) = key?;
        list.push(keyspace.to_owned());
    }

    Ok(list)
}

async fn setup_database(path: impl AsRef<Path>) -> heed::Result<(Sender<Task>, Env)> {
    let path = path.as_ref().to_path_buf();
    let (tx, rx) = flume::bounded(CAPACITY);

    let env = tokio::task::spawn_blocking(move || setup_disk_handle(&path, rx))
        .await
        .expect("spawn background runner")?;

    Ok((tx, env))
}

fn setup_disk_handle(path: &Path, tasks: Receiver<Task>) -> heed::Result<Env> {
    if !path.exists() {
        let _ = std::fs::create_dir_all(path); // Attempt to create the directory.
    }

    let env = EnvOpenOptions::new()
        .map_size(DEFAULT_MAP_SIZE)
        .max_dbs(MAX_NUM_DBS)
        .open(path)?;

    let mut txn = env.write_txn()?;
    let keyspace_list = env.create_database(&mut txn, Some("datacake-keyspace"))?;
    txn.commit()?;

    let env2 = env.clone();
    std::thread::spawn(move || run_tasks(env, tasks, keyspace_list));

    Ok(env2)
}

/// Runs all tasks received with a mutable reference to the given connection.
fn run_tasks(env: Env, tasks: Receiver<Task>, keyspace_list: KeyspaceDB) {
    let mut dbs = DatabaseKeyspace::new();
    while let Ok(task) = tasks.recv() {
        (task)(&env, &keyspace_list, &mut dbs);
    }
}

#[cfg(test)]
mod tests {
    use std::env::temp_dir;
    use std::path::PathBuf;

    use uuid::Uuid;

    use super::*;

    fn get_path() -> PathBuf {
        let path = temp_dir().join(Uuid::new_v4().to_string());
        std::fs::create_dir_all(&path).unwrap();
        path
    }

    #[tokio::test]
    async fn test_db_creation() {
        StorageHandle::open(get_path())
            .await
            .expect("Database should open OK.");
    }

    #[tokio::test]
    async fn test_db_put_and_get() {
        let handle = StorageHandle::open(get_path())
            .await
            .expect("Database should open OK.");

        let doc1 = Document::new(1, HLCTimestamp::from_u64(0), b"Hello".as_ref());
        handle
            .put_kv("test", doc1.clone())
            .await
            .expect("Put new doc");

        // Test keyspace dont overlap
        let doc2 = Document::new(1, HLCTimestamp::from_u64(2), b"Hello 2".as_ref());
        handle
            .put_kv("test2", doc2.clone())
            .await
            .expect("Put new doc");

        let doc3 = Document::new(1, HLCTimestamp::from_u64(3), b"Hello 3".as_ref());
        handle
            .put_kv("test3", doc3.clone())
            .await
            .expect("Put new doc");

        let fetched_doc_1 = handle
            .get("test", 1)
            .await
            .expect("Get doc")
            .expect("Doc exists");
        let fetched_doc_2 = handle
            .get("test2", 1)
            .await
            .expect("Get doc")
            .expect("Doc exists");
        let fetched_doc_3 = handle
            .get("test3", 1)
            .await
            .expect("Get doc")
            .expect("Doc exists");

        assert_eq!(
            [doc1, doc2, doc3],
            [fetched_doc_1, fetched_doc_2, fetched_doc_3],
            "Documents returned should not overlap and match."
        );
    }

    #[tokio::test]
    async fn test_db_put_get_many() {
        let handle = StorageHandle::open(get_path())
            .await
            .expect("Database should open OK.");

        let docs = vec![
            Document::new(1, HLCTimestamp::from_u64(0), b"Hello".as_ref()),
            Document::new(2, HLCTimestamp::from_u64(0), b"Hello".as_ref()),
            Document::new(3, HLCTimestamp::from_u64(0), b"Hello".as_ref()),
        ];
        handle
            .put_many_kv("test", docs.clone().into_iter())
            .await
            .expect("Put new docs");

        let fetched_docs = handle
            .get_many("test", [1, 2, 3].into_iter())
            .await
            .expect("Get docs");

        assert_eq!(docs, fetched_docs, "Documents returned should match.");
    }

    #[tokio::test]
    async fn test_db_mark_tombstone() {
        let handle = StorageHandle::open(get_path())
            .await
            .expect("Database should open OK.");

        let doc1 = Document::new(1, HLCTimestamp::from_u64(0), b"Hello".as_ref());
        handle
            .put_kv("test", doc1.clone())
            .await
            .expect("Put new doc");
        assert!(
            handle.get("test", 1).await.expect("Get doc").is_some(),
            "Document should exist"
        );

        // Mark it as a tombstone so we shouldn't get it returned anymore.
        handle
            .mark_tombstone("test", doc1.id(), HLCTimestamp::from_u64(1))
            .await
            .expect("Put new doc");
        assert!(
            handle.get("test", 1).await.expect("Get doc").is_none(),
            "Document should not exist"
        );

        // Add a doc simulating an update and check it get's re-inserted.
        handle
            .put_kv("test", doc1.clone())
            .await
            .expect("Put new doc");
        assert!(
            handle.get("test", 1).await.expect("Get doc").is_some(),
            "Document should exist"
        );
    }
}