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 /// Sets the active memtable.
232 ///
233 /// May be used to restore the LSM-tree's in-memory state from a write-ahead log
234 /// after tree recovery.
235 fn set_active_memtable(&self, memtable: Memtable);
236
237 /// Returns the number of sealed memtables.
238 fn sealed_memtable_count(&self) -> usize;
239
240 /// Adds a sealed memtables.
241 ///
242 /// May be used to restore the LSM-tree's in-memory state from some journals.
243 fn add_sealed_memtable(&self, memtable: Arc<Memtable>);
244
245 /// Performs compaction on the tree's levels, blocking the caller until it's done.
246 ///
247 /// # Errors
248 ///
249 /// Will return `Err` if an IO error occurs.
250 fn compact(
251 &self,
252 strategy: Arc<dyn crate::compaction::CompactionStrategy>,
253 seqno_threshold: SeqNo,
254 ) -> crate::Result<()>;
255
256 /// Returns the next table's ID.
257 fn get_next_table_id(&self) -> TableId;
258
259 /// Returns the tree config.
260 fn tree_config(&self) -> &Config;
261
262 /// Returns the highest sequence number.
263 fn get_highest_seqno(&self) -> Option<SeqNo> {
264 let memtable_seqno = self.get_highest_memtable_seqno();
265 let table_seqno = self.get_highest_persisted_seqno();
266 memtable_seqno.max(table_seqno)
267 }
268
269 /// Returns the active memtable.
270 fn active_memtable(&self) -> Arc<Memtable>;
271
272 /// Returns the tree type.
273 fn tree_type(&self) -> crate::TreeType;
274
275 /// Seals the active memtable.
276 fn rotate_memtable(&self) -> Option<Arc<Memtable>>;
277
278 /// Returns the number of tables currently in the tree.
279 fn table_count(&self) -> usize;
280
281 /// Returns the number of tables in `levels[idx]`.
282 ///
283 /// Returns `None` if the level does not exist (if idx >= 7).
284 fn level_table_count(&self, idx: usize) -> Option<usize>;
285
286 /// Returns the number of disjoint runs in L0.
287 ///
288 /// Can be used to determine whether to write stall.
289 fn l0_run_count(&self) -> usize;
290
291 /// Returns the number of blob files currently in the tree.
292 fn blob_file_count(&self) -> usize;
293
294 /// Approximates the number of items in the tree.
295 fn approximate_len(&self) -> usize;
296
297 /// Returns the disk space usage.
298 fn disk_space(&self) -> u64;
299
300 /// Returns the highest sequence number of the active memtable.
301 fn get_highest_memtable_seqno(&self) -> Option<SeqNo>;
302
303 /// Returns the highest sequence number that is flushed to disk.
304 fn get_highest_persisted_seqno(&self) -> Option<SeqNo>;
305
306 /// Scans the entire tree, returning the number of items.
307 ///
308 /// ###### Caution
309 ///
310 /// This operation scans the entire tree: O(n) complexity!
311 ///
312 /// Never, under any circumstances, use .`len()` == 0 to check
313 /// if the tree is empty, use [`Tree::is_empty`] instead.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// # use lsm_tree::Error as TreeError;
319 /// use lsm_tree::{AbstractTree, Config, Tree};
320 ///
321 /// let folder = tempfile::tempdir()?;
322 /// let tree = Config::new(folder, Default::default()).open()?;
323 ///
324 /// assert_eq!(tree.len(0, None)?, 0);
325 /// tree.insert("1", "abc", 0);
326 /// tree.insert("3", "abc", 1);
327 /// tree.insert("5", "abc", 2);
328 /// assert_eq!(tree.len(3, None)?, 3);
329 /// #
330 /// # Ok::<(), TreeError>(())
331 /// ```
332 ///
333 /// # Errors
334 ///
335 /// Will return `Err` if an IO error occurs.
336 fn len(&self, seqno: SeqNo, index: Option<(Arc<Memtable>, SeqNo)>) -> crate::Result<usize> {
337 let mut count = 0;
338
339 for item in self.iter(seqno, index) {
340 let _ = item.key()?;
341 count += 1;
342 }
343
344 Ok(count)
345 }
346
347 /// Returns `true` if the tree is empty.
348 ///
349 /// This operation has O(log N) complexity.
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// # let folder = tempfile::tempdir()?;
355 /// use lsm_tree::{AbstractTree, Config, Tree};
356 ///
357 /// let tree = Config::new(folder, Default::default()).open()?;
358 /// assert!(tree.is_empty(0, None)?);
359 ///
360 /// tree.insert("a", "abc", 0);
361 /// assert!(!tree.is_empty(1, None)?);
362 /// #
363 /// # Ok::<(), lsm_tree::Error>(())
364 /// ```
365 ///
366 /// # Errors
367 ///
368 /// Will return `Err` if an IO error occurs.
369 fn is_empty(&self, seqno: SeqNo, index: Option<(Arc<Memtable>, SeqNo)>) -> crate::Result<bool> {
370 self.first_key_value(seqno, index).map(|x| x.is_none())
371 }
372
373 /// Returns the first key-value pair in the tree.
374 /// The key in this pair is the minimum key in the tree.
375 ///
376 /// # Examples
377 ///
378 /// ```
379 /// # use lsm_tree::Error as TreeError;
380 /// # use lsm_tree::{AbstractTree, Config, Tree};
381 /// #
382 /// # let folder = tempfile::tempdir()?;
383 /// let tree = Config::new(folder, Default::default()).open()?;
384 ///
385 /// tree.insert("1", "abc", 0);
386 /// tree.insert("3", "abc", 1);
387 /// tree.insert("5", "abc", 2);
388 ///
389 /// let (key, _) = tree.first_key_value(3, None)?.expect("item should exist");
390 /// assert_eq!(&*key, "1".as_bytes());
391 /// #
392 /// # Ok::<(), TreeError>(())
393 /// ```
394 ///
395 /// # Errors
396 ///
397 /// Will return `Err` if an IO error occurs.
398 fn first_key_value(
399 &self,
400 seqno: SeqNo,
401 index: Option<(Arc<Memtable>, SeqNo)>,
402 ) -> crate::Result<Option<KvPair>> {
403 self.iter(seqno, index)
404 .next()
405 .map(Guard::into_inner)
406 .transpose()
407 }
408
409 /// Returns the last key-value pair in the tree.
410 /// The key in this pair is the maximum key in the tree.
411 ///
412 /// # Examples
413 ///
414 /// ```
415 /// # use lsm_tree::Error as TreeError;
416 /// # use lsm_tree::{AbstractTree, Config, Tree};
417 /// #
418 /// # let folder = tempfile::tempdir()?;
419 /// # let tree = Config::new(folder, Default::default()).open()?;
420 /// #
421 /// tree.insert("1", "abc", 0);
422 /// tree.insert("3", "abc", 1);
423 /// tree.insert("5", "abc", 2);
424 ///
425 /// let (key, _) = tree.last_key_value(3, None)?.expect("item should exist");
426 /// assert_eq!(&*key, "5".as_bytes());
427 /// #
428 /// # Ok::<(), TreeError>(())
429 /// ```
430 ///
431 /// # Errors
432 ///
433 /// Will return `Err` if an IO error occurs.
434 fn last_key_value(
435 &self,
436 seqno: SeqNo,
437 index: Option<(Arc<Memtable>, SeqNo)>,
438 ) -> crate::Result<Option<KvPair>> {
439 self.iter(seqno, index)
440 .next_back()
441 .map(Guard::into_inner)
442 .transpose()
443 }
444
445 /// Returns the size of a value if it exists.
446 ///
447 /// # Examples
448 ///
449 /// ```
450 /// # let folder = tempfile::tempdir()?;
451 /// use lsm_tree::{AbstractTree, Config, Tree};
452 ///
453 /// let tree = Config::new(folder, Default::default()).open()?;
454 /// tree.insert("a", "my_value", 0);
455 ///
456 /// let size = tree.size_of("a", 1)?.unwrap_or_default();
457 /// assert_eq!("my_value".len() as u32, size);
458 ///
459 /// let size = tree.size_of("b", 1)?.unwrap_or_default();
460 /// assert_eq!(0, size);
461 /// #
462 /// # Ok::<(), lsm_tree::Error>(())
463 /// ```
464 ///
465 /// # Errors
466 ///
467 /// Will return `Err` if an IO error occurs.
468 fn size_of<K: AsRef<[u8]>>(&self, key: K, seqno: SeqNo) -> crate::Result<Option<u32>>;
469
470 /// Retrieves an item from the tree.
471 ///
472 /// # Examples
473 ///
474 /// ```
475 /// # let folder = tempfile::tempdir()?;
476 /// use lsm_tree::{AbstractTree, Config, Tree};
477 ///
478 /// let tree = Config::new(folder, Default::default()).open()?;
479 /// tree.insert("a", "my_value", 0);
480 ///
481 /// let item = tree.get("a", 1)?;
482 /// assert_eq!(Some("my_value".as_bytes().into()), item);
483 /// #
484 /// # Ok::<(), lsm_tree::Error>(())
485 /// ```
486 ///
487 /// # Errors
488 ///
489 /// Will return `Err` if an IO error occurs.
490 fn get<K: AsRef<[u8]>>(&self, key: K, seqno: SeqNo) -> crate::Result<Option<UserValue>>;
491
492 /// Returns `true` if the tree contains the specified key.
493 ///
494 /// # Examples
495 ///
496 /// ```
497 /// # let folder = tempfile::tempdir()?;
498 /// # use lsm_tree::{AbstractTree, Config, Tree};
499 /// #
500 /// let tree = Config::new(folder, Default::default()).open()?;
501 /// assert!(!tree.contains_key("a", 0)?);
502 ///
503 /// tree.insert("a", "abc", 0);
504 /// assert!(tree.contains_key("a", 1)?);
505 /// #
506 /// # Ok::<(), lsm_tree::Error>(())
507 /// ```
508 ///
509 /// # Errors
510 ///
511 /// Will return `Err` if an IO error occurs.
512 fn contains_key<K: AsRef<[u8]>>(&self, key: K, seqno: SeqNo) -> crate::Result<bool> {
513 self.get(key, seqno).map(|x| x.is_some())
514 }
515
516 /// Inserts a key-value pair into the tree.
517 ///
518 /// If the key already exists, the item will be overwritten.
519 ///
520 /// Returns the added item's size and new size of the memtable.
521 ///
522 /// # Examples
523 ///
524 /// ```
525 /// # let folder = tempfile::tempdir()?;
526 /// use lsm_tree::{AbstractTree, Config, Tree};
527 ///
528 /// let tree = Config::new(folder, Default::default()).open()?;
529 /// tree.insert("a", "abc", 0);
530 /// #
531 /// # Ok::<(), lsm_tree::Error>(())
532 /// ```
533 ///
534 /// # Errors
535 ///
536 /// Will return `Err` if an IO error occurs.
537 fn insert<K: Into<UserKey>, V: Into<UserValue>>(
538 &self,
539 key: K,
540 value: V,
541 seqno: SeqNo,
542 ) -> (u64, u64);
543
544 /// Removes an item from the tree.
545 ///
546 /// Returns the added item's size and new size of the memtable.
547 ///
548 /// # Examples
549 ///
550 /// ```
551 /// # let folder = tempfile::tempdir()?;
552 /// # use lsm_tree::{AbstractTree, Config, Tree};
553 /// #
554 /// # let tree = Config::new(folder, Default::default()).open()?;
555 /// tree.insert("a", "abc", 0);
556 ///
557 /// let item = tree.get("a", 1)?.expect("should have item");
558 /// assert_eq!("abc".as_bytes(), &*item);
559 ///
560 /// tree.remove("a", 1);
561 ///
562 /// let item = tree.get("a", 2)?;
563 /// assert_eq!(None, item);
564 /// #
565 /// # Ok::<(), lsm_tree::Error>(())
566 /// ```
567 ///
568 /// # Errors
569 ///
570 /// Will return `Err` if an IO error occurs.
571 fn remove<K: Into<UserKey>>(&self, key: K, seqno: SeqNo) -> (u64, u64);
572
573 /// Removes an item from the tree.
574 ///
575 /// The tombstone marker of this delete operation will vanish when it
576 /// collides with its corresponding insertion.
577 /// This may cause older versions of the value to be resurrected, so it should
578 /// only be used and preferred in scenarios where a key is only ever written once.
579 ///
580 /// Returns the added item's size and new size of the memtable.
581 ///
582 /// # Examples
583 ///
584 /// ```
585 /// # let folder = tempfile::tempdir()?;
586 /// # use lsm_tree::{AbstractTree, Config, Tree};
587 /// #
588 /// # let tree = Config::new(folder, Default::default()).open()?;
589 /// tree.insert("a", "abc", 0);
590 ///
591 /// let item = tree.get("a", 1)?.expect("should have item");
592 /// assert_eq!("abc".as_bytes(), &*item);
593 ///
594 /// tree.remove_weak("a", 1);
595 ///
596 /// let item = tree.get("a", 2)?;
597 /// assert_eq!(None, item);
598 /// #
599 /// # Ok::<(), lsm_tree::Error>(())
600 /// ```
601 ///
602 /// # Errors
603 ///
604 /// Will return `Err` if an IO error occurs.
605 #[doc(hidden)]
606 fn remove_weak<K: Into<UserKey>>(&self, key: K, seqno: SeqNo) -> (u64, u64);
607}