lsm_tree/
abstract.rs

1// Copyright (c) 2024-present, fjall-rs
2// This source code is licensed under both the Apache 2.0 and MIT License
3// (found in the LICENSE-* files in the repository)
4
5use crate::{
6    iter_guard::IterGuardImpl, table::Table, version::Version, vlog::BlobFile, AnyTree, BlobTree,
7    Config, Guard, InternalValue, KvPair, Memtable, SeqNo, TableId, Tree, UserKey, UserValue,
8};
9use std::{
10    ops::RangeBounds,
11    sync::{Arc, MutexGuard, RwLockWriteGuard},
12};
13
14pub type RangeItem = crate::Result<KvPair>;
15
16/// Generic Tree API
17#[enum_dispatch::enum_dispatch]
18pub trait AbstractTree {
19    // TODO: fn() with Nuke compaction strategy (write lock) -> drop_range(..)
20
21    /// Returns the number of cached table file descriptors.
22    fn table_file_cache_size(&self) -> usize;
23
24    // TODO: remove
25    #[doc(hidden)]
26    fn version_memtable_size_sum(&self) -> u64 {
27        self.get_version_history_lock().memtable_size_sum()
28    }
29
30    #[doc(hidden)]
31    fn next_table_id(&self) -> TableId;
32
33    #[doc(hidden)]
34    fn id(&self) -> crate::TreeId;
35
36    /// Like [`AbstractTree::get`], but returns the actual internal entry, not just the user value.
37    ///
38    /// Used in tests.
39    #[doc(hidden)]
40    fn get_internal_entry(&self, key: &[u8], seqno: SeqNo) -> crate::Result<Option<InternalValue>>;
41
42    #[doc(hidden)]
43    fn current_version(&self) -> Version;
44
45    #[doc(hidden)]
46    fn get_version_history_lock(&self) -> RwLockWriteGuard<'_, crate::version::SuperVersions>;
47
48    /// Seals the active memtable and flushes to table(s).
49    ///
50    /// If there are already other sealed memtables lined up, those will be flushed as well.
51    ///
52    /// Only used in tests.
53    #[doc(hidden)]
54    fn flush_active_memtable(&self, eviction_seqno: SeqNo) -> crate::Result<()> {
55        let lock = self.get_flush_lock();
56        self.rotate_memtable();
57        self.flush(&lock, eviction_seqno)?;
58        Ok(())
59    }
60
61    /// Synchronously flushes pending sealed memtables to tables.
62    ///
63    /// Returns the sum of flushed memtable sizes that were flushed.
64    ///
65    /// The function may not return a result, if nothing was flushed.
66    ///
67    /// # Errors
68    ///
69    /// Will return `Err` if an IO error occurs.
70    fn flush(
71        &self,
72        _lock: &MutexGuard<'_, ()>,
73        seqno_threshold: SeqNo,
74    ) -> crate::Result<Option<u64>> {
75        use crate::{compaction::stream::CompactionStream, merge::Merger};
76
77        let version_history = self.get_version_history_lock();
78        let latest = version_history.latest_version();
79
80        if latest.sealed_memtables.len() == 0 {
81            return Ok(None);
82        }
83
84        let sealed_ids = latest
85            .sealed_memtables
86            .iter()
87            .map(|mt| mt.id)
88            .collect::<Vec<_>>();
89
90        let flushed_size = latest.sealed_memtables.iter().map(|mt| mt.size()).sum();
91
92        let merger = Merger::new(
93            latest
94                .sealed_memtables
95                .iter()
96                .map(|mt| mt.iter().map(Ok))
97                .collect::<Vec<_>>(),
98        );
99        let stream = CompactionStream::new(merger, seqno_threshold);
100
101        drop(version_history);
102
103        if let Some((tables, blob_files)) = self.flush_to_tables(stream)? {
104            self.register_tables(
105                &tables,
106                blob_files.as_deref(),
107                None,
108                &sealed_ids,
109                seqno_threshold,
110            )?;
111        }
112
113        Ok(Some(flushed_size))
114    }
115
116    /// Returns an iterator that scans through the entire tree.
117    ///
118    /// Avoid using this function, or limit it as otherwise it may scan a lot of items.
119    fn iter(
120        &self,
121        seqno: SeqNo,
122        index: Option<(Arc<Memtable>, SeqNo)>,
123    ) -> Box<dyn DoubleEndedIterator<Item = IterGuardImpl> + Send + 'static> {
124        self.range::<&[u8], _>(.., seqno, index)
125    }
126
127    /// Returns an iterator over a prefixed set of items.
128    ///
129    /// Avoid using an empty prefix as it may scan a lot of items (unless limited).
130    fn prefix<K: AsRef<[u8]>>(
131        &self,
132        prefix: K,
133        seqno: SeqNo,
134        index: Option<(Arc<Memtable>, SeqNo)>,
135    ) -> Box<dyn DoubleEndedIterator<Item = IterGuardImpl> + Send + 'static>;
136
137    /// Returns an iterator over a range of items.
138    ///
139    /// Avoid using full or unbounded ranges as they may scan a lot of items (unless limited).
140    fn range<K: AsRef<[u8]>, R: RangeBounds<K>>(
141        &self,
142        range: R,
143        seqno: SeqNo,
144        index: Option<(Arc<Memtable>, SeqNo)>,
145    ) -> Box<dyn DoubleEndedIterator<Item = IterGuardImpl> + Send + 'static>;
146
147    /// Returns the approximate number of tombstones in the tree.
148    fn tombstone_count(&self) -> u64;
149
150    /// Returns the approximate number of weak tombstones (single deletes) in the tree.
151    fn weak_tombstone_count(&self) -> u64;
152
153    /// Returns the approximate number of values reclaimable once weak tombstones can be GC'd.
154    fn weak_tombstone_reclaimable_count(&self) -> u64;
155
156    /// Drops tables that are fully contained in a given range.
157    ///
158    /// Accepts any `RangeBounds`, including unbounded or exclusive endpoints.
159    /// If the normalized lower bound is greater than the upper bound, the
160    /// method returns without performing any work.
161    ///
162    /// # Errors
163    ///
164    /// Will return `Err` only if an IO error occurs during compaction.
165    fn drop_range<K: AsRef<[u8]>, R: RangeBounds<K>>(&self, range: R) -> crate::Result<()>;
166
167    /// Performs major compaction, blocking the caller until it's done.
168    ///
169    /// # Errors
170    ///
171    /// Will return `Err` if an IO error occurs.
172    fn major_compact(&self, target_size: u64, seqno_threshold: SeqNo) -> crate::Result<()>;
173
174    /// Returns the disk space used by stale blobs.
175    fn stale_blob_bytes(&self) -> u64 {
176        0
177    }
178
179    /// Gets the space usage of all filters in the tree.
180    ///
181    /// May not correspond to the actual memory size because filter blocks may be paged out.
182    fn filter_size(&self) -> usize;
183
184    /// Gets the memory usage of all pinned filters in the tree.
185    fn pinned_filter_size(&self) -> usize;
186
187    /// Gets the memory usage of all pinned index blocks in the tree.
188    fn pinned_block_index_size(&self) -> usize;
189
190    /// Gets the length of the version free list.
191    fn version_free_list_len(&self) -> usize;
192
193    /// Returns the metrics structure.
194    #[cfg(feature = "metrics")]
195    fn metrics(&self) -> &Arc<crate::Metrics>;
196
197    /// Acquires the flush lock which is required to call [`Tree::flush`].
198    fn get_flush_lock(&self) -> MutexGuard<'_, ()>;
199
200    /// Synchronously flushes a memtable to a table.
201    ///
202    /// This method will not make the table immediately available,
203    /// use [`AbstractTree::register_tables`] for that.
204    ///
205    /// # Errors
206    ///
207    /// Will return `Err` if an IO error occurs.
208    #[warn(clippy::type_complexity)]
209    fn flush_to_tables(
210        &self,
211        stream: impl Iterator<Item = crate::Result<InternalValue>>,
212    ) -> crate::Result<Option<(Vec<Table>, Option<Vec<BlobFile>>)>>;
213
214    /// Atomically registers flushed tables into the tree, removing their associated sealed memtables.
215    ///
216    /// # Errors
217    ///
218    /// Will return `Err` if an IO error occurs.
219    fn register_tables(
220        &self,
221        tables: &[Table],
222        blob_files: Option<&[BlobFile]>,
223        frag_map: Option<crate::blob_tree::FragmentationMap>,
224        sealed_memtables_to_delete: &[crate::tree::inner::MemtableId],
225        gc_watermark: SeqNo,
226    ) -> crate::Result<()>;
227
228    /// Clears the active memtable atomically.
229    fn clear_active_memtable(&self);
230
231    /// Returns the number of sealed memtables.
232    fn sealed_memtable_count(&self) -> usize;
233
234    /// Adds a sealed memtables.
235    ///
236    /// May be used to restore the LSM-tree's in-memory state from some journals.
237    fn add_sealed_memtable(&self, memtable: Arc<Memtable>);
238
239    /// Performs compaction on the tree's levels, blocking the caller until it's done.
240    ///
241    /// # Errors
242    ///
243    /// Will return `Err` if an IO error occurs.
244    fn compact(
245        &self,
246        strategy: Arc<dyn crate::compaction::CompactionStrategy>,
247        seqno_threshold: SeqNo,
248    ) -> crate::Result<()>;
249
250    /// Returns the next table's ID.
251    fn get_next_table_id(&self) -> TableId;
252
253    /// Returns the tree config.
254    fn tree_config(&self) -> &Config;
255
256    /// Returns the highest sequence number.
257    fn get_highest_seqno(&self) -> Option<SeqNo> {
258        let memtable_seqno = self.get_highest_memtable_seqno();
259        let table_seqno = self.get_highest_persisted_seqno();
260        memtable_seqno.max(table_seqno)
261    }
262
263    /// Returns the active memtable.
264    fn active_memtable(&self) -> Arc<Memtable>;
265
266    /// Returns the tree type.
267    fn tree_type(&self) -> crate::TreeType;
268
269    /// Seals the active memtable.
270    fn rotate_memtable(&self) -> Option<Arc<Memtable>>;
271
272    /// Returns the number of tables currently in the tree.
273    fn table_count(&self) -> usize;
274
275    /// Returns the number of tables in `levels[idx]`.
276    ///
277    /// Returns `None` if the level does not exist (if idx >= 7).
278    fn level_table_count(&self, idx: usize) -> Option<usize>;
279
280    /// Returns the number of disjoint runs in L0.
281    ///
282    /// Can be used to determine whether to write stall.
283    fn l0_run_count(&self) -> usize;
284
285    /// Returns the number of blob files currently in the tree.
286    fn blob_file_count(&self) -> usize;
287
288    /// Approximates the number of items in the tree.
289    fn approximate_len(&self) -> usize;
290
291    /// Returns the disk space usage.
292    fn disk_space(&self) -> u64;
293
294    /// Returns the highest sequence number of the active memtable.
295    fn get_highest_memtable_seqno(&self) -> Option<SeqNo>;
296
297    /// Returns the highest sequence number that is flushed to disk.
298    fn get_highest_persisted_seqno(&self) -> Option<SeqNo>;
299
300    /// Scans the entire tree, returning the number of items.
301    ///
302    /// ###### Caution
303    ///
304    /// This operation scans the entire tree: O(n) complexity!
305    ///
306    /// Never, under any circumstances, use .`len()` == 0 to check
307    /// if the tree is empty, use [`Tree::is_empty`] instead.
308    ///
309    /// # Examples
310    ///
311    /// ```
312    /// # use lsm_tree::Error as TreeError;
313    /// use lsm_tree::{AbstractTree, Config, Tree};
314    ///
315    /// let folder = tempfile::tempdir()?;
316    /// let tree = Config::new(folder, Default::default()).open()?;
317    ///
318    /// assert_eq!(tree.len(0, None)?, 0);
319    /// tree.insert("1", "abc", 0);
320    /// tree.insert("3", "abc", 1);
321    /// tree.insert("5", "abc", 2);
322    /// assert_eq!(tree.len(3, None)?, 3);
323    /// #
324    /// # Ok::<(), TreeError>(())
325    /// ```
326    ///
327    /// # Errors
328    ///
329    /// Will return `Err` if an IO error occurs.
330    fn len(&self, seqno: SeqNo, index: Option<(Arc<Memtable>, SeqNo)>) -> crate::Result<usize> {
331        let mut count = 0;
332
333        for item in self.iter(seqno, index) {
334            let _ = item.key()?;
335            count += 1;
336        }
337
338        Ok(count)
339    }
340
341    /// Returns `true` if the tree is empty.
342    ///
343    /// This operation has O(log N) complexity.
344    ///
345    /// # Examples
346    ///
347    /// ```
348    /// # let folder = tempfile::tempdir()?;
349    /// use lsm_tree::{AbstractTree, Config, Tree};
350    ///
351    /// let tree = Config::new(folder, Default::default()).open()?;
352    /// assert!(tree.is_empty(0, None)?);
353    ///
354    /// tree.insert("a", "abc", 0);
355    /// assert!(!tree.is_empty(1, None)?);
356    /// #
357    /// # Ok::<(), lsm_tree::Error>(())
358    /// ```
359    ///
360    /// # Errors
361    ///
362    /// Will return `Err` if an IO error occurs.
363    fn is_empty(&self, seqno: SeqNo, index: Option<(Arc<Memtable>, SeqNo)>) -> crate::Result<bool> {
364        self.first_key_value(seqno, index).map(|x| x.is_none())
365    }
366
367    /// Returns the first key-value pair in the tree.
368    /// The key in this pair is the minimum key in the tree.
369    ///
370    /// # Examples
371    ///
372    /// ```
373    /// # use lsm_tree::Error as TreeError;
374    /// # use lsm_tree::{AbstractTree, Config, Tree};
375    /// #
376    /// # let folder = tempfile::tempdir()?;
377    /// let tree = Config::new(folder, Default::default()).open()?;
378    ///
379    /// tree.insert("1", "abc", 0);
380    /// tree.insert("3", "abc", 1);
381    /// tree.insert("5", "abc", 2);
382    ///
383    /// let (key, _) = tree.first_key_value(3, None)?.expect("item should exist");
384    /// assert_eq!(&*key, "1".as_bytes());
385    /// #
386    /// # Ok::<(), TreeError>(())
387    /// ```
388    ///
389    /// # Errors
390    ///
391    /// Will return `Err` if an IO error occurs.
392    fn first_key_value(
393        &self,
394        seqno: SeqNo,
395        index: Option<(Arc<Memtable>, SeqNo)>,
396    ) -> crate::Result<Option<KvPair>> {
397        self.iter(seqno, index)
398            .next()
399            .map(Guard::into_inner)
400            .transpose()
401    }
402
403    /// Returns the last key-value pair in the tree.
404    /// The key in this pair is the maximum key in the tree.
405    ///
406    /// # Examples
407    ///
408    /// ```
409    /// # use lsm_tree::Error as TreeError;
410    /// # use lsm_tree::{AbstractTree, Config, Tree};
411    /// #
412    /// # let folder = tempfile::tempdir()?;
413    /// # let tree = Config::new(folder, Default::default()).open()?;
414    /// #
415    /// tree.insert("1", "abc", 0);
416    /// tree.insert("3", "abc", 1);
417    /// tree.insert("5", "abc", 2);
418    ///
419    /// let (key, _) = tree.last_key_value(3, None)?.expect("item should exist");
420    /// assert_eq!(&*key, "5".as_bytes());
421    /// #
422    /// # Ok::<(), TreeError>(())
423    /// ```
424    ///
425    /// # Errors
426    ///
427    /// Will return `Err` if an IO error occurs.
428    fn last_key_value(
429        &self,
430        seqno: SeqNo,
431        index: Option<(Arc<Memtable>, SeqNo)>,
432    ) -> crate::Result<Option<KvPair>> {
433        self.iter(seqno, index)
434            .next_back()
435            .map(Guard::into_inner)
436            .transpose()
437    }
438
439    /// Returns the size of a value if it exists.
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// # let folder = tempfile::tempdir()?;
445    /// use lsm_tree::{AbstractTree, Config, Tree};
446    ///
447    /// let tree = Config::new(folder, Default::default()).open()?;
448    /// tree.insert("a", "my_value", 0);
449    ///
450    /// let size = tree.size_of("a", 1)?.unwrap_or_default();
451    /// assert_eq!("my_value".len() as u32, size);
452    ///
453    /// let size = tree.size_of("b", 1)?.unwrap_or_default();
454    /// assert_eq!(0, size);
455    /// #
456    /// # Ok::<(), lsm_tree::Error>(())
457    /// ```
458    ///
459    /// # Errors
460    ///
461    /// Will return `Err` if an IO error occurs.
462    fn size_of<K: AsRef<[u8]>>(&self, key: K, seqno: SeqNo) -> crate::Result<Option<u32>>;
463
464    /// Retrieves an item from the tree.
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// # let folder = tempfile::tempdir()?;
470    /// use lsm_tree::{AbstractTree, Config, Tree};
471    ///
472    /// let tree = Config::new(folder, Default::default()).open()?;
473    /// tree.insert("a", "my_value", 0);
474    ///
475    /// let item = tree.get("a", 1)?;
476    /// assert_eq!(Some("my_value".as_bytes().into()), item);
477    /// #
478    /// # Ok::<(), lsm_tree::Error>(())
479    /// ```
480    ///
481    /// # Errors
482    ///
483    /// Will return `Err` if an IO error occurs.
484    fn get<K: AsRef<[u8]>>(&self, key: K, seqno: SeqNo) -> crate::Result<Option<UserValue>>;
485
486    /// Returns `true` if the tree contains the specified key.
487    ///
488    /// # Examples
489    ///
490    /// ```
491    /// # let folder = tempfile::tempdir()?;
492    /// # use lsm_tree::{AbstractTree, Config, Tree};
493    /// #
494    /// let tree = Config::new(folder, Default::default()).open()?;
495    /// assert!(!tree.contains_key("a", 0)?);
496    ///
497    /// tree.insert("a", "abc", 0);
498    /// assert!(tree.contains_key("a", 1)?);
499    /// #
500    /// # Ok::<(), lsm_tree::Error>(())
501    /// ```
502    ///
503    /// # Errors
504    ///
505    /// Will return `Err` if an IO error occurs.
506    fn contains_key<K: AsRef<[u8]>>(&self, key: K, seqno: SeqNo) -> crate::Result<bool> {
507        self.get(key, seqno).map(|x| x.is_some())
508    }
509
510    /// Inserts a key-value pair into the tree.
511    ///
512    /// If the key already exists, the item will be overwritten.
513    ///
514    /// Returns the added item's size and new size of the memtable.
515    ///
516    /// # Examples
517    ///
518    /// ```
519    /// # let folder = tempfile::tempdir()?;
520    /// use lsm_tree::{AbstractTree, Config, Tree};
521    ///
522    /// let tree = Config::new(folder, Default::default()).open()?;
523    /// tree.insert("a", "abc", 0);
524    /// #
525    /// # Ok::<(), lsm_tree::Error>(())
526    /// ```
527    ///
528    /// # Errors
529    ///
530    /// Will return `Err` if an IO error occurs.
531    fn insert<K: Into<UserKey>, V: Into<UserValue>>(
532        &self,
533        key: K,
534        value: V,
535        seqno: SeqNo,
536    ) -> (u64, u64);
537
538    /// Removes an item from the tree.
539    ///
540    /// Returns the added item's size and new size of the memtable.
541    ///
542    /// # Examples
543    ///
544    /// ```
545    /// # let folder = tempfile::tempdir()?;
546    /// # use lsm_tree::{AbstractTree, Config, Tree};
547    /// #
548    /// # let tree = Config::new(folder, Default::default()).open()?;
549    /// tree.insert("a", "abc", 0);
550    ///
551    /// let item = tree.get("a", 1)?.expect("should have item");
552    /// assert_eq!("abc".as_bytes(), &*item);
553    ///
554    /// tree.remove("a", 1);
555    ///
556    /// let item = tree.get("a", 2)?;
557    /// assert_eq!(None, item);
558    /// #
559    /// # Ok::<(), lsm_tree::Error>(())
560    /// ```
561    ///
562    /// # Errors
563    ///
564    /// Will return `Err` if an IO error occurs.
565    fn remove<K: Into<UserKey>>(&self, key: K, seqno: SeqNo) -> (u64, u64);
566
567    /// Removes an item from the tree.
568    ///
569    /// The tombstone marker of this delete operation will vanish when it
570    /// collides with its corresponding insertion.
571    /// This may cause older versions of the value to be resurrected, so it should
572    /// only be used and preferred in scenarios where a key is only ever written once.
573    ///
574    /// Returns the added item's size and new size of the memtable.
575    ///
576    /// # Examples
577    ///
578    /// ```
579    /// # let folder = tempfile::tempdir()?;
580    /// # use lsm_tree::{AbstractTree, Config, Tree};
581    /// #
582    /// # let tree = Config::new(folder, Default::default()).open()?;
583    /// tree.insert("a", "abc", 0);
584    ///
585    /// let item = tree.get("a", 1)?.expect("should have item");
586    /// assert_eq!("abc".as_bytes(), &*item);
587    ///
588    /// tree.remove_weak("a", 1);
589    ///
590    /// let item = tree.get("a", 2)?;
591    /// assert_eq!(None, item);
592    /// #
593    /// # Ok::<(), lsm_tree::Error>(())
594    /// ```
595    ///
596    /// # Errors
597    ///
598    /// Will return `Err` if an IO error occurs.
599    #[doc(hidden)]
600    fn remove_weak<K: Into<UserKey>>(&self, key: K, seqno: SeqNo) -> (u64, u64);
601}