Skip to main content

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#![doc(
36    html_logo_url = "https://raw.githubusercontent.com/structured-world/coordinode-lsm-tree/main/logo.png"
37)]
38#![doc(
39    html_favicon_url = "https://raw.githubusercontent.com/structured-world/coordinode-lsm-tree/main/logo.png"
40)]
41#![deny(clippy::all, missing_docs, clippy::cargo)]
42#![deny(clippy::unwrap_used)]
43#![deny(clippy::indexing_slicing)]
44#![warn(clippy::pedantic, clippy::nursery)]
45#![warn(clippy::expect_used)]
46#![allow(clippy::missing_const_for_fn)]
47#![warn(clippy::multiple_crate_versions)]
48#![allow(clippy::option_if_let_else)]
49#![warn(clippy::redundant_feature_names)]
50#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
51
52#[doc(hidden)]
53pub type HashMap<K, V> = std::collections::HashMap<K, V, rustc_hash::FxBuildHasher>;
54
55pub(crate) type HashSet<K> = std::collections::HashSet<K, rustc_hash::FxBuildHasher>;
56
57macro_rules! fail_iter {
58    ($e:expr) => {
59        match $e {
60            Ok(v) => v,
61            Err(e) => return Some(Err(e.into())),
62        }
63    };
64}
65
66macro_rules! unwrap {
67    ($x:expr) => {{
68        $x.expect("should read")
69    }};
70}
71
72mod any_tree;
73
74mod abstract_tree;
75
76#[doc(hidden)]
77pub mod blob_tree;
78
79mod comparator;
80
81#[doc(hidden)]
82mod cache;
83
84#[doc(hidden)]
85pub mod checksum;
86
87#[doc(hidden)]
88pub mod coding;
89
90pub mod compaction;
91mod compression;
92
93/// Block-level encryption at rest.
94pub mod encryption;
95
96/// Configuration
97pub mod config;
98
99#[doc(hidden)]
100pub mod descriptor_table;
101
102#[doc(hidden)]
103pub mod file_accessor;
104
105mod double_ended_peekable;
106mod error;
107
108#[doc(hidden)]
109pub mod file;
110
111/// Pluggable filesystem abstraction for I/O backends.
112pub mod fs;
113
114mod hash;
115mod heap;
116mod ingestion;
117mod iter_guard;
118mod key;
119mod key_range;
120mod manifest;
121mod memtable;
122mod merge_operator;
123mod run_reader;
124mod run_scanner;
125
126#[doc(hidden)]
127pub mod merge;
128
129#[cfg(feature = "metrics")]
130pub(crate) mod metrics;
131
132// mod multi_reader;
133
134#[doc(hidden)]
135pub mod mvcc_stream;
136
137mod path;
138mod prefix;
139
140#[doc(hidden)]
141pub mod range;
142
143pub(crate) mod active_tombstone_set;
144pub(crate) mod range_tombstone;
145pub(crate) mod range_tombstone_filter;
146
147#[doc(hidden)]
148pub mod table;
149
150mod seqno;
151mod slice;
152mod slice_windows;
153
154#[doc(hidden)]
155pub mod stop_signal;
156
157mod format_version;
158mod time;
159mod tree;
160
161/// Utility functions
162pub mod util;
163
164mod value;
165mod value_type;
166
167/// Integrity verification for SST and blob files.
168pub mod verify;
169
170mod version;
171mod vlog;
172
173/// User defined key (byte array)
174pub type UserKey = Slice;
175
176/// User defined data (byte array)
177pub type UserValue = Slice;
178
179/// KV-tuple (key + value)
180pub type KvPair = (UserKey, UserValue);
181
182#[doc(hidden)]
183pub use {
184    blob_tree::{handle::BlobIndirection, Guard as BlobGuard},
185    checksum::Checksum,
186    iter_guard::IterGuardImpl,
187    key_range::KeyRange,
188    merge::BoxedIterator,
189    slice::Builder,
190    table::{GlobalTableId, Table, TableId},
191    tree::inner::TreeId,
192    tree::Guard as StandardGuard,
193    value::InternalValue,
194};
195
196pub use encryption::EncryptionProvider;
197
198#[cfg(feature = "encryption")]
199pub use encryption::Aes256GcmProvider;
200
201pub use {
202    abstract_tree::AbstractTree,
203    any_tree::AnyTree,
204    blob_tree::BlobTree,
205    cache::Cache,
206    comparator::{DefaultUserComparator, SharedComparator, UserComparator},
207    compression::CompressionType,
208    config::{Config, KvSeparationOptions, TreeType},
209    descriptor_table::DescriptorTable,
210    error::{Error, Result},
211    format_version::FormatVersion,
212    ingestion::AnyIngestion,
213    iter_guard::IterGuard as Guard,
214    memtable::{Memtable, MemtableId},
215    merge_operator::MergeOperator,
216    prefix::PrefixExtractor,
217    seqno::{
218        SequenceNumberCounter, SequenceNumberGenerator, SharedSequenceNumberGenerator, MAX_SEQNO,
219    },
220    slice::Slice,
221    tree::Tree,
222    value::SeqNo,
223    value_type::ValueType,
224    vlog::BlobFile,
225};
226
227#[cfg(feature = "zstd")]
228pub use compression::ZstdDictionary;
229
230#[cfg(feature = "metrics")]
231pub use metrics::Metrics;
232
233#[doc(hidden)]
234#[must_use]
235#[allow(missing_docs, clippy::missing_errors_doc, clippy::unwrap_used)]
236pub fn get_tmp_folder() -> tempfile::TempDir {
237    if let Ok(p) = std::env::var("LSMT_TMP_FOLDER") {
238        tempfile::tempdir_in(p)
239    } else {
240        tempfile::tempdir()
241    }
242    .unwrap()
243}