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 segments when the write buffer reaches some threshold.
23//!
24//! Amassing many segments on disk will degrade read performance and waste disk space, so segments
25//! can be periodically merged into larger segments 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 disk segments have amassed, use compaction
74//! // to reduce the number of disk segments
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 binary_search;
149
150#[doc(hidden)]
151pub mod blob_tree;
152
153#[doc(hidden)]
154mod cache;
155
156#[doc(hidden)]
157pub mod coding;
158
159pub mod compaction;
160mod compression;
161
162/// Configuration
163pub mod config;
164
165mod double_ended_peekable;
166
167mod error;
168
169pub(crate) mod fallible_clipping_iter;
170
171#[doc(hidden)]
172pub mod file;
173
174mod hash;
175
176mod iter_guard;
177
178mod key;
179mod key_range;
180
181mod run_reader;
182mod run_scanner;
183
184mod manifest;
185mod memtable;
186
187#[doc(hidden)]
188mod descriptor_table;
189
190#[doc(hidden)]
191pub mod merge;
192
193#[cfg(feature = "metrics")]
194pub(crate) mod metrics;
195
196mod multi_reader;
197
198#[doc(hidden)]
199pub mod mvcc_stream;
200
201mod path;
202
203#[doc(hidden)]
204pub mod range;
205
206#[doc(hidden)]
207pub mod segment;
208
209mod seqno;
210mod slice;
211mod slice_windows;
212
213#[doc(hidden)]
214pub mod stop_signal;
215
216mod format_version;
217mod time;
218mod tree;
219mod value;
220mod value_type;
221mod version;
222mod vlog;
223
224/// User defined key
225pub type UserKey = Slice;
226
227/// User defined data (byte array)
228pub type UserValue = Slice;
229
230/// KV-tuple, typically returned by an iterator
231pub type KvPair = (UserKey, UserValue);
232
233#[doc(hidden)]
234pub use {
235 key_range::KeyRange,
236 merge::BoxedIterator,
237 segment::{block::Checksum, GlobalSegmentId, Segment, SegmentId},
238 tree::ingest::Ingestion,
239 tree::inner::TreeId,
240 value::InternalValue,
241};
242
243pub use {
244 any_tree::AnyTree,
245 blob_tree::BlobTree,
246 cache::Cache,
247 coding::{DecodeError, EncodeError},
248 compression::CompressionType,
249 config::{Config, KvSeparationOptions, TreeType},
250 descriptor_table::DescriptorTable,
251 error::{Error, Result},
252 format_version::FormatVersion,
253 iter_guard::IterGuard as Guard,
254 memtable::Memtable,
255 r#abstract::AbstractTree,
256 seqno::SequenceNumberCounter,
257 slice::Slice,
258 tree::Tree,
259 value::SeqNo,
260 value_type::ValueType,
261 vlog::BlobFile,
262};
263
264#[cfg(feature = "metrics")]
265pub use metrics::Metrics;