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