lsm_tree/
lib.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
5//! A K.I.S.S. implementation of log-structured merge trees (LSM-trees/LSMTs).
6//!
7//! ##### NOTE
8//!
9//! > This crate only provides a primitive LSM-tree, not a full storage engine.
10//! > You probably want to use <https://crates.io/crates/fjall> instead.
11//! > For example, it does not ship with a write-ahead log, so writes are not
12//! > persisted until manually flushing the memtable.
13//!
14//! ##### About
15//!
16//! This crate exports a `Tree` that supports a subset of the `BTreeMap` API.
17//!
18//! LSM-trees are an alternative to B-trees to persist a sorted list of items (e.g. a database table)
19//! on disk and perform fast lookup queries.
20//! Instead of updating a disk-based data structure in-place,
21//! deltas (inserts and deletes) are added into an in-memory write buffer (`Memtable`).
22//! Data is then flushed to disk-resident table files when the write buffer reaches some threshold.
23//!
24//! Amassing many tables on disk will degrade read performance and waste disk space, so tables
25//! can be periodically merged into larger tables in a process called `Compaction`.
26//! Different compaction strategies have different advantages and drawbacks, and should be chosen based
27//! on the workload characteristics.
28//!
29//! Because maintaining an efficient structure is deferred to the compaction process, writing to an LSMT
30//! is very fast (_O(1)_ complexity).
31//!
32//! Keys are limited to 65536 bytes, values are limited to 2^32 bytes. As is normal with any kind of storage
33//! engine, larger keys and values have a bigger performance impact.
34//!
35//! # Example usage
36//!
37//! ```
38//! use lsm_tree::{AbstractTree, Config, Tree};
39//! #
40//! # let folder = tempfile::tempdir()?;
41//!
42//! // A tree is a single physical keyspace/index/...
43//! // and supports a BTreeMap-like API
44//! let tree = Config::new(folder).open()?;
45//!
46//! // Note compared to the BTreeMap API, operations return a Result<T>
47//! // So you can handle I/O errors if they occur
48//! tree.insert("my_key", "my_value", /* sequence number */ 0);
49//!
50//! let item = tree.get("my_key", 1)?;
51//! assert_eq!(Some("my_value".as_bytes().into()), item);
52//!
53//! // Search by prefix
54//! for item in tree.prefix("prefix", 1, None) {
55//!   // ...
56//! }
57//!
58//! // Search by range
59//! for item in tree.range("a"..="z", 1, None) {
60//!   // ...
61//! }
62//!
63//! // Iterators implement DoubleEndedIterator, so you can search backwards, too!
64//! for item in tree.prefix("user1", 1, None).rev() {
65//!   // ...
66//! }
67//!
68//! // Flush to secondary storage, clearing the memtable
69//! // and persisting all in-memory data.
70//! // Note, this flushes synchronously, which may not be desired
71//! tree.flush_active_memtable(0)?;
72//!
73//! // When some tables have amassed, use compaction
74//! // to reduce the number of tables
75//!
76//! // Choose compaction strategy based on workload
77//! use lsm_tree::compaction::Leveled;
78//! # use std::sync::Arc;
79//!
80//! let strategy = Leveled::default();
81//!
82//! let version_gc_threshold = 0;
83//! tree.compact(Arc::new(strategy), version_gc_threshold)?;
84//! #
85//! # Ok::<(), lsm_tree::Error>(())
86//! ```
87
88#![doc(html_logo_url = "https://raw.githubusercontent.com/fjall-rs/lsm-tree/main/logo.png")]
89#![doc(html_favicon_url = "https://raw.githubusercontent.com/fjall-rs/lsm-tree/main/logo.png")]
90#![deny(clippy::all, missing_docs, clippy::cargo)]
91#![deny(clippy::unwrap_used)]
92#![deny(clippy::indexing_slicing)]
93#![warn(clippy::pedantic, clippy::nursery)]
94#![warn(clippy::expect_used)]
95#![allow(clippy::missing_const_for_fn)]
96#![warn(clippy::multiple_crate_versions)]
97#![allow(clippy::option_if_let_else)]
98#![warn(clippy::redundant_feature_names)]
99// the bytes feature uses unsafe to improve from_reader performance; so we need to relax this lint
100// #![cfg_attr(feature = "bytes", deny(unsafe_code))]
101// #![cfg_attr(not(feature = "bytes"), forbid(unsafe_code))]
102
103// TODO: 3.0.0 use checksum type impl from sfa as well
104
105#[doc(hidden)]
106pub type HashMap<K, V> = std::collections::HashMap<K, V, rustc_hash::FxBuildHasher>;
107
108pub(crate) type HashSet<K> = std::collections::HashSet<K, rustc_hash::FxBuildHasher>;
109
110#[allow(unused)]
111macro_rules! set {
112    ($($x:expr),+ $(,)?) => {
113        [$($x),+].into_iter().collect::<HashSet<_>>()
114    }
115}
116
117macro_rules! fail_iter {
118    ($e:expr) => {
119        match $e {
120            Ok(v) => v,
121            Err(e) => return Some(Err(e.into())),
122        }
123    };
124}
125
126// TODO: investigate perf
127macro_rules! unwrap {
128    ($x:expr) => {{
129        #[cfg(not(feature = "use_unsafe"))]
130        {
131            $x.expect("should read")
132        }
133
134        #[cfg(feature = "use_unsafe")]
135        {
136            unsafe { $x.unwrap_unchecked() }
137        }
138    }};
139}
140
141pub(crate) use unwrap;
142
143mod any_tree;
144
145mod r#abstract;
146
147#[doc(hidden)]
148pub mod blob_tree;
149
150#[doc(hidden)]
151mod cache;
152
153#[doc(hidden)]
154pub mod coding;
155
156pub mod compaction;
157mod compression;
158
159/// Configuration
160pub mod config;
161
162mod double_ended_peekable;
163
164mod error;
165
166pub(crate) mod fallible_clipping_iter;
167
168#[doc(hidden)]
169pub mod file;
170
171mod hash;
172
173mod iter_guard;
174
175mod key;
176mod key_range;
177
178mod run_reader;
179mod run_scanner;
180
181mod manifest;
182mod memtable;
183
184#[doc(hidden)]
185pub mod descriptor_table;
186
187#[doc(hidden)]
188pub mod merge;
189
190#[cfg(feature = "metrics")]
191pub(crate) mod metrics;
192
193mod multi_reader;
194
195#[doc(hidden)]
196pub mod mvcc_stream;
197
198mod path;
199
200#[doc(hidden)]
201pub mod range;
202
203#[doc(hidden)]
204pub mod table;
205
206mod seqno;
207mod slice;
208mod slice_windows;
209
210#[doc(hidden)]
211pub mod stop_signal;
212
213mod format_version;
214mod time;
215mod tree;
216
217/// Utility functions
218pub mod util;
219
220mod value;
221mod value_type;
222mod version;
223mod vlog;
224
225/// User defined key (byte array)
226pub type UserKey = Slice;
227
228/// User defined data (byte array)
229pub type UserValue = Slice;
230
231/// KV-tuple (key + value)
232pub type KvPair = (UserKey, UserValue);
233
234#[doc(hidden)]
235pub use {
236    blob_tree::handle::BlobIndirection,
237    key_range::KeyRange,
238    merge::BoxedIterator,
239    slice::Builder,
240    table::{block::Checksum, GlobalTableId, Table, TableId},
241    tree::ingest::Ingestion,
242    tree::inner::TreeId,
243    value::InternalValue,
244};
245
246pub use {
247    any_tree::AnyTree,
248    blob_tree::BlobTree,
249    cache::Cache,
250    coding::{DecodeError, EncodeError},
251    compression::CompressionType,
252    config::{Config, KvSeparationOptions, TreeType},
253    descriptor_table::DescriptorTable,
254    error::{Error, Result},
255    format_version::FormatVersion,
256    iter_guard::IterGuard as Guard,
257    memtable::Memtable,
258    r#abstract::AbstractTree,
259    seqno::SequenceNumberCounter,
260    slice::Slice,
261    tree::Tree,
262    value::SeqNo,
263    value_type::ValueType,
264    vlog::BlobFile,
265};
266
267#[cfg(feature = "metrics")]
268pub use metrics::Metrics;