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
16type FlushToTablesResult = (Vec<Table>, Option<Vec<BlobFile>>);
17
18/// Generic Tree API
19#[enum_dispatch::enum_dispatch]
20pub trait AbstractTree {
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.
165 fn drop_range<K: AsRef<[u8]>, R: RangeBounds<K>>(&self, range: R) -> crate::Result<()>;
166
167 /// Drops all tables and clears all memtables atomically.
168 ///
169 /// # Errors
170 ///
171 /// Will return `Err` only if an IO error occurs.
172 fn clear(&self) -> crate::Result<()>;
173
174 /// Performs major compaction, blocking the caller until it's done.
175 ///
176 /// # Errors
177 ///
178 /// Will return `Err` if an IO error occurs.
179 fn major_compact(&self, target_size: u64, seqno_threshold: SeqNo) -> crate::Result<()>;
180
181 /// Returns the disk space used by stale blobs.
182 fn stale_blob_bytes(&self) -> u64 {
183 0
184 }
185
186 /// Gets the space usage of all filters in the tree.
187 ///
188 /// May not correspond to the actual memory size because filter blocks may be paged out.
189 fn filter_size(&self) -> u64;
190
191 /// Gets the memory usage of all pinned filters in the tree.
192 fn pinned_filter_size(&self) -> usize;
193
194 /// Gets the memory usage of all pinned index blocks in the tree.
195 fn pinned_block_index_size(&self) -> usize;
196
197 /// Gets the length of the version free list.
198 fn version_free_list_len(&self) -> usize;
199
200 /// Returns the metrics structure.
201 #[cfg(feature = "metrics")]
202 fn metrics(&self) -> &Arc<crate::Metrics>;
203
204 /// Acquires the flush lock which is required to call [`Tree::flush`].
205 fn get_flush_lock(&self) -> MutexGuard<'_, ()>;
206
207 /// Synchronously flushes a memtable to a table.
208 ///
209 /// This method will not make the table immediately available,
210 /// use [`AbstractTree::register_tables`] for that.
211 ///
212 /// # Errors
213 ///
214 /// Will return `Err` if an IO error occurs.
215 #[warn(clippy::type_complexity)]
216 fn flush_to_tables(
217 &self,
218 stream: impl Iterator<Item = crate::Result<InternalValue>>,
219 ) -> crate::Result<Option<FlushToTablesResult>>;
220
221 /// Atomically registers flushed tables into the tree, removing their associated sealed memtables.
222 ///
223 /// # Errors
224 ///
225 /// Will return `Err` if an IO error occurs.
226 fn register_tables(
227 &self,
228 tables: &[Table],
229 blob_files: Option<&[BlobFile]>,
230 frag_map: Option<crate::blob_tree::FragmentationMap>,
231 sealed_memtables_to_delete: &[crate::tree::inner::MemtableId],
232 gc_watermark: SeqNo,
233 ) -> crate::Result<()>;
234
235 /// Clears the active memtable atomically.
236 fn clear_active_memtable(&self);
237
238 /// Returns the number of sealed memtables.
239 fn sealed_memtable_count(&self) -> usize;
240
241 /// Performs compaction on the tree's levels, blocking the caller until it's done.
242 ///
243 /// # Errors
244 ///
245 /// Will return `Err` if an IO error occurs.
246 fn compact(
247 &self,
248 strategy: Arc<dyn crate::compaction::CompactionStrategy>,
249 seqno_threshold: SeqNo,
250 ) -> crate::Result<()>;
251
252 /// Returns the next table's ID.
253 fn get_next_table_id(&self) -> TableId;
254
255 /// Returns the tree config.
256 fn tree_config(&self) -> &Config;
257
258 /// Returns the highest sequence number.
259 fn get_highest_seqno(&self) -> Option<SeqNo> {
260 let memtable_seqno = self.get_highest_memtable_seqno();
261 let table_seqno = self.get_highest_persisted_seqno();
262 memtable_seqno.max(table_seqno)
263 }
264
265 /// Returns the active memtable.
266 fn active_memtable(&self) -> Arc<Memtable>;
267
268 /// Returns the tree type.
269 fn tree_type(&self) -> crate::TreeType;
270
271 /// Seals the active memtable.
272 fn rotate_memtable(&self) -> Option<Arc<Memtable>>;
273
274 /// Returns the number of tables currently in the tree.
275 fn table_count(&self) -> usize;
276
277 /// Returns the number of tables in `levels[idx]`.
278 ///
279 /// Returns `None` if the level does not exist (if idx >= 7).
280 fn level_table_count(&self, idx: usize) -> Option<usize>;
281
282 /// Returns the number of disjoint runs in L0.
283 ///
284 /// Can be used to determine whether to write stall.
285 fn l0_run_count(&self) -> usize;
286
287 /// Returns the number of blob files currently in the tree.
288 fn blob_file_count(&self) -> usize;
289
290 /// Approximates the number of items in the tree.
291 fn approximate_len(&self) -> usize;
292
293 /// Returns the disk space usage.
294 fn disk_space(&self) -> u64;
295
296 /// Returns the highest sequence number of the active memtable.
297 fn get_highest_memtable_seqno(&self) -> Option<SeqNo>;
298
299 /// Returns the highest sequence number that is flushed to disk.
300 fn get_highest_persisted_seqno(&self) -> Option<SeqNo>;
301
302 /// Scans the entire tree, returning the number of items.
303 ///
304 /// ###### Caution
305 ///
306 /// This operation scans the entire tree: O(n) complexity!
307 ///
308 /// Never, under any circumstances, use .`len()` == 0 to check
309 /// if the tree is empty, use [`Tree::is_empty`] instead.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// # use lsm_tree::Error as TreeError;
315 /// use lsm_tree::{AbstractTree, Config, Tree};
316 ///
317 /// let folder = tempfile::tempdir()?;
318 /// let tree = Config::new(folder, Default::default(), Default::default()).open()?;
319 ///
320 /// assert_eq!(tree.len(0, None)?, 0);
321 /// tree.insert("1", "abc", 0);
322 /// tree.insert("3", "abc", 1);
323 /// tree.insert("5", "abc", 2);
324 /// assert_eq!(tree.len(3, None)?, 3);
325 /// #
326 /// # Ok::<(), TreeError>(())
327 /// ```
328 ///
329 /// # Errors
330 ///
331 /// Will return `Err` if an IO error occurs.
332 fn len(&self, seqno: SeqNo, index: Option<(Arc<Memtable>, SeqNo)>) -> crate::Result<usize> {
333 let mut count = 0;
334
335 for item in self.iter(seqno, index) {
336 let _ = item.key()?;
337 count += 1;
338 }
339
340 Ok(count)
341 }
342
343 /// Returns `true` if the tree is empty.
344 ///
345 /// This operation has O(log N) complexity.
346 ///
347 /// # Examples
348 ///
349 /// ```
350 /// # let folder = tempfile::tempdir()?;
351 /// use lsm_tree::{AbstractTree, Config, Tree};
352 ///
353 /// let tree = Config::new(folder, Default::default(), Default::default()).open()?;
354 /// assert!(tree.is_empty(0, None)?);
355 ///
356 /// tree.insert("a", "abc", 0);
357 /// assert!(!tree.is_empty(1, None)?);
358 /// #
359 /// # Ok::<(), lsm_tree::Error>(())
360 /// ```
361 ///
362 /// # Errors
363 ///
364 /// Will return `Err` if an IO error occurs.
365 fn is_empty(&self, seqno: SeqNo, index: Option<(Arc<Memtable>, SeqNo)>) -> crate::Result<bool> {
366 Ok(self
367 .first_key_value(seqno, index)
368 .map(crate::Guard::key)
369 .transpose()?
370 .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, Guard};
381 /// #
382 /// # let folder = tempfile::tempdir()?;
383 /// let tree = Config::new(folder, Default::default(), 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").key()?;
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 ) -> Option<IterGuardImpl> {
403 self.iter(seqno, index).next()
404 }
405
406 /// Returns the last key-value pair in the tree.
407 /// The key in this pair is the maximum key in the tree.
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// # use lsm_tree::Error as TreeError;
413 /// # use lsm_tree::{AbstractTree, Config, Tree, Guard};
414 /// #
415 /// # let folder = tempfile::tempdir()?;
416 /// # let tree = Config::new(folder, Default::default(), Default::default()).open()?;
417 /// #
418 /// tree.insert("1", "abc", 0);
419 /// tree.insert("3", "abc", 1);
420 /// tree.insert("5", "abc", 2);
421 ///
422 /// let key = tree.last_key_value(3, None).expect("item should exist").key()?;
423 /// assert_eq!(&*key, "5".as_bytes());
424 /// #
425 /// # Ok::<(), TreeError>(())
426 /// ```
427 ///
428 /// # Errors
429 ///
430 /// Will return `Err` if an IO error occurs.
431 fn last_key_value(
432 &self,
433 seqno: SeqNo,
434 index: Option<(Arc<Memtable>, SeqNo)>,
435 ) -> Option<IterGuardImpl> {
436 self.iter(seqno, index).next_back()
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(), 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(), 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(), 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(), 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(), 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(), 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}