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
110macro_rules! fail_iter {
111 ($e:expr) => {
112 match $e {
113 Ok(v) => v,
114 Err(e) => return Some(Err(e.into())),
115 }
116 };
117}
118
119// TODO: investigate perf
120macro_rules! unwrap {
121 ($x:expr) => {{
122 #[cfg(not(feature = "use_unsafe"))]
123 {
124 $x.expect("should read")
125 }
126
127 #[cfg(feature = "use_unsafe")]
128 {
129 unsafe { $x.unwrap_unchecked() }
130 }
131 }};
132}
133
134pub(crate) use unwrap;
135
136mod any_tree;
137
138mod r#abstract;
139
140#[doc(hidden)]
141pub mod blob_tree;
142
143#[doc(hidden)]
144mod cache;
145
146#[doc(hidden)]
147pub mod coding;
148
149pub mod compaction;
150mod compression;
151
152/// Configuration
153pub mod config;
154
155mod double_ended_peekable;
156
157mod error;
158
159pub(crate) mod fallible_clipping_iter;
160
161#[doc(hidden)]
162pub mod file;
163
164mod hash;
165
166mod iter_guard;
167
168mod key;
169mod key_range;
170
171mod run_reader;
172mod run_scanner;
173
174mod manifest;
175mod memtable;
176
177#[doc(hidden)]
178pub mod descriptor_table;
179
180#[doc(hidden)]
181pub mod merge;
182
183#[cfg(feature = "metrics")]
184pub(crate) mod metrics;
185
186mod multi_reader;
187
188#[doc(hidden)]
189pub mod mvcc_stream;
190
191mod path;
192
193#[doc(hidden)]
194pub mod range;
195
196#[doc(hidden)]
197pub mod table;
198
199mod seqno;
200mod slice;
201mod slice_windows;
202
203#[doc(hidden)]
204pub mod stop_signal;
205
206mod format_version;
207mod time;
208mod tree;
209
210/// Utility functions
211pub mod util;
212
213mod value;
214mod value_type;
215mod version;
216mod vlog;
217
218/// User defined key (byte array)
219pub type UserKey = Slice;
220
221/// User defined data (byte array)
222pub type UserValue = Slice;
223
224/// KV-tuple (key + value)
225pub type KvPair = (UserKey, UserValue);
226
227#[doc(hidden)]
228pub use {
229 blob_tree::handle::BlobIndirection,
230 key_range::KeyRange,
231 merge::BoxedIterator,
232 slice::Builder,
233 table::{block::Checksum, GlobalTableId, Table, TableId},
234 tree::ingest::Ingestion,
235 tree::inner::TreeId,
236 value::InternalValue,
237};
238
239pub use {
240 any_tree::AnyTree,
241 blob_tree::BlobTree,
242 cache::Cache,
243 coding::{DecodeError, EncodeError},
244 compression::CompressionType,
245 config::{Config, KvSeparationOptions, TreeType},
246 descriptor_table::DescriptorTable,
247 error::{Error, Result},
248 format_version::FormatVersion,
249 iter_guard::IterGuard as Guard,
250 memtable::Memtable,
251 r#abstract::AbstractTree,
252 seqno::SequenceNumberCounter,
253 slice::Slice,
254 tree::Tree,
255 value::SeqNo,
256 value_type::ValueType,
257 vlog::BlobFile,
258};
259
260#[cfg(feature = "metrics")]
261pub use metrics::Metrics;