lsm_tree/config/
mod.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
5mod block_size;
6mod compression;
7mod filter;
8mod hash_ratio;
9mod pinning;
10mod restart_interval;
11
12pub use block_size::BlockSizePolicy;
13pub use compression::CompressionPolicy;
14pub use filter::{BloomConstructionPolicy, FilterPolicy, FilterPolicyEntry};
15pub use hash_ratio::HashRatioPolicy;
16pub use pinning::PinningPolicy;
17pub use restart_interval::RestartIntervalPolicy;
18
19/// Partioning policy for indexes and filters
20pub type PartioningPolicy = PinningPolicy;
21
22use crate::{
23    path::absolute_path, version::DEFAULT_LEVEL_COUNT, AnyTree, BlobTree, Cache, CompressionType,
24    DescriptorTable, SequenceNumberCounter, Tree,
25};
26use std::{
27    path::{Path, PathBuf},
28    sync::Arc,
29};
30
31/// LSM-tree type
32#[derive(Copy, Clone, Debug, PartialEq, Eq)]
33pub enum TreeType {
34    /// Standard LSM-tree, see [`Tree`]
35    Standard,
36
37    /// Key-value separated LSM-tree, see [`BlobTree`]
38    Blob,
39}
40
41impl From<TreeType> for u8 {
42    fn from(val: TreeType) -> Self {
43        match val {
44            TreeType::Standard => 0,
45            TreeType::Blob => 1,
46        }
47    }
48}
49
50impl TryFrom<u8> for TreeType {
51    type Error = ();
52
53    fn try_from(value: u8) -> Result<Self, Self::Error> {
54        match value {
55            0 => Ok(Self::Standard),
56            1 => Ok(Self::Blob),
57            _ => Err(()),
58        }
59    }
60}
61
62const DEFAULT_FILE_FOLDER: &str = ".lsm.data";
63
64/// Options for key-value separation
65#[derive(Clone, Debug, PartialEq)]
66pub struct KvSeparationOptions {
67    /// What type of compression is used for blobs
68    #[doc(hidden)]
69    pub compression: CompressionType,
70
71    /// Blob file target size in bytes
72    #[doc(hidden)]
73    pub file_target_size: u64,
74
75    /// Key-value separation threshold in bytes
76    #[doc(hidden)]
77    pub separation_threshold: u32,
78
79    #[doc(hidden)]
80    pub staleness_threshold: f32,
81
82    #[doc(hidden)]
83    pub age_cutoff: f32,
84}
85
86impl Default for KvSeparationOptions {
87    fn default() -> Self {
88        Self {
89            #[cfg(feature="lz4")]
90            compression:   CompressionType::Lz4,
91
92            #[cfg(not(feature="lz4"))]
93            compression: CompressionType::None,
94
95            file_target_size: /* 64 MiB */ 64 * 1_024 * 1_024,
96            separation_threshold: /* 1 KiB */ 1_024,
97
98            staleness_threshold: 0.33,
99            age_cutoff: 0.20,
100        }
101    }
102}
103
104impl KvSeparationOptions {
105    /// Sets the blob compression method.
106    #[must_use]
107    pub fn compression(mut self, compression: CompressionType) -> Self {
108        self.compression = compression;
109        self
110    }
111
112    /// Sets the target size of blob files.
113    ///
114    /// Smaller blob files allow more granular garbage collection
115    /// which allows lower space amp for lower write I/O cost.
116    ///
117    /// Larger blob files decrease the number of files on disk and maintenance
118    /// overhead.
119    ///
120    /// Defaults to 64 MiB.
121    #[must_use]
122    pub fn file_target_size(mut self, bytes: u64) -> Self {
123        self.file_target_size = bytes;
124        self
125    }
126
127    /// Sets the key-value separation threshold in bytes.
128    ///
129    /// Smaller value will reduce compaction overhead and thus write amplification,
130    /// at the cost of lower read performance.
131    ///
132    /// Defaults to 1 KiB.
133    #[must_use]
134    pub fn separation_threshold(mut self, bytes: u32) -> Self {
135        self.separation_threshold = bytes;
136        self
137    }
138
139    /// Sets the staleness threshold percentage.
140    ///
141    /// The staleness percentage determines how much a blob file needs to be fragmented to be
142    /// picked up by the garbage collection.
143    ///
144    /// Defaults to 33%.
145    #[must_use]
146    pub fn staleness_threshold(mut self, ratio: f32) -> Self {
147        self.staleness_threshold = ratio;
148        self
149    }
150
151    /// Sets the age cutoff threshold.
152    ///
153    /// Defaults to 20%.
154    #[must_use]
155    pub fn age_cutoff(mut self, ratio: f32) -> Self {
156        self.age_cutoff = ratio;
157        self
158    }
159}
160
161#[derive(Clone)]
162/// Tree configuration builder
163pub struct Config {
164    /// Folder path
165    #[doc(hidden)]
166    pub path: PathBuf,
167
168    /// Block cache to use
169    #[doc(hidden)]
170    pub cache: Arc<Cache>,
171
172    /// Descriptor table to use
173    #[doc(hidden)]
174    pub descriptor_table: Arc<DescriptorTable>,
175
176    /// Number of levels of the LSM tree (depth of tree)
177    ///
178    /// Once set, the level count is fixed (in the "manifest" file)
179    pub level_count: u8,
180
181    /// What type of compression is used for data blocks
182    pub data_block_compression_policy: CompressionPolicy,
183
184    /// What type of compression is used for index blocks
185    pub index_block_compression_policy: CompressionPolicy,
186
187    /// Restart interval inside data blocks
188    pub data_block_restart_interval_policy: RestartIntervalPolicy,
189
190    /// Restart interval inside index blocks
191    pub index_block_restart_interval_policy: RestartIntervalPolicy,
192
193    /// Block size of data blocks
194    pub data_block_size_policy: BlockSizePolicy,
195
196    /// Whether to pin index blocks
197    pub index_block_pinning_policy: PinningPolicy,
198
199    /// Whether to pin filter blocks
200    pub filter_block_pinning_policy: PinningPolicy,
201
202    /// Whether to pin top level index of partitioned index
203    pub top_level_index_block_pinning_policy: PinningPolicy,
204
205    /// Whether to pin top level index of partitioned filter
206    pub top_level_filter_block_pinning_policy: PinningPolicy,
207
208    /// Data block hash ratio
209    pub data_block_hash_ratio_policy: HashRatioPolicy,
210
211    /// Whether to partition index blocks
212    pub index_block_partitioning_policy: PartioningPolicy,
213
214    /// Whether to partition filter blocks
215    pub filter_block_partitioning_policy: PartioningPolicy,
216
217    /// Partition size when using partitioned indexes
218    pub index_block_partition_size_policy: BlockSizePolicy,
219
220    /// Partition size when using partitioned filters
221    pub filter_block_partition_size_policy: BlockSizePolicy,
222
223    /// If `true`, the last level will not build filters, reducing the filter size of a database
224    /// by ~90% typically
225    pub(crate) expect_point_read_hits: bool,
226
227    /// Filter construction policy
228    pub filter_policy: FilterPolicy,
229
230    #[doc(hidden)]
231    pub kv_separation_opts: Option<KvSeparationOptions>,
232
233    /// The global sequence number generator
234    ///
235    /// Should be shared between multple trees of a database
236    pub(crate) seqno: SequenceNumberCounter,
237
238    pub(crate) visible_seqno: SequenceNumberCounter,
239}
240
241// TODO: remove default?
242impl Default for Config {
243    fn default() -> Self {
244        Self {
245            path: absolute_path(Path::new(DEFAULT_FILE_FOLDER)),
246            descriptor_table: Arc::new(DescriptorTable::new(256)),
247            seqno: SequenceNumberCounter::default(),
248            visible_seqno: SequenceNumberCounter::default(),
249
250            cache: Arc::new(Cache::with_capacity_bytes(
251                /* 16 MiB */ 16 * 1_024 * 1_024,
252            )),
253
254            data_block_restart_interval_policy: RestartIntervalPolicy::all(16),
255            index_block_restart_interval_policy: RestartIntervalPolicy::all(1),
256
257            level_count: DEFAULT_LEVEL_COUNT,
258
259            data_block_size_policy: BlockSizePolicy::all(4_096),
260
261            index_block_pinning_policy: PinningPolicy::new([true, true, false]),
262            filter_block_pinning_policy: PinningPolicy::new([true, false]),
263
264            top_level_index_block_pinning_policy: PinningPolicy::all(true), // TODO: implement
265            top_level_filter_block_pinning_policy: PinningPolicy::all(true), // TODO: implement
266
267            index_block_partitioning_policy: PinningPolicy::new([false, false, false, true]),
268            filter_block_partitioning_policy: PinningPolicy::new([false, false, false, true]),
269
270            index_block_partition_size_policy: BlockSizePolicy::all(4_096), // TODO: implement
271            filter_block_partition_size_policy: BlockSizePolicy::all(4_096), // TODO: implement
272
273            data_block_compression_policy: ({
274                #[cfg(feature = "lz4")]
275                let c = CompressionPolicy::new([CompressionType::None, CompressionType::Lz4]);
276
277                #[cfg(not(feature = "lz4"))]
278                let c = CompressionPolicy::new([CompressionType::None]);
279
280                c
281            }),
282            index_block_compression_policy: CompressionPolicy::all(CompressionType::None),
283
284            data_block_hash_ratio_policy: HashRatioPolicy::all(0.0),
285
286            filter_policy: FilterPolicy::all(FilterPolicyEntry::Bloom(
287                BloomConstructionPolicy::BitsPerKey(10.0),
288            )),
289
290            expect_point_read_hits: false,
291
292            kv_separation_opts: None,
293        }
294    }
295}
296
297impl Config {
298    /// Initializes a new config
299    pub fn new<P: AsRef<Path>>(
300        path: P,
301        seqno: SequenceNumberCounter,
302        visible_seqno: SequenceNumberCounter,
303    ) -> Self {
304        Self {
305            path: absolute_path(path.as_ref()),
306            seqno,
307            visible_seqno,
308            ..Default::default()
309        }
310    }
311
312    /// Sets the global cache.
313    ///
314    /// You can create a global [`Cache`] and share it between multiple
315    /// trees to cap global cache memory usage.
316    ///
317    /// Defaults to a cache with 16 MiB of capacity *per tree*.
318    #[must_use]
319    pub fn use_cache(mut self, cache: Arc<Cache>) -> Self {
320        self.cache = cache;
321        self
322    }
323
324    #[must_use]
325    #[doc(hidden)]
326    pub fn use_descriptor_table(mut self, descriptor_table: Arc<DescriptorTable>) -> Self {
327        self.descriptor_table = descriptor_table;
328        self
329    }
330
331    /// If `true`, the last level will not build filters, reducing the filter size of a database
332    /// by ~90% typically.
333    ///
334    /// **Enable this only if you know that point reads generally are expected to find a key-value pair.**
335    #[must_use]
336    pub fn expect_point_read_hits(mut self, b: bool) -> Self {
337        self.expect_point_read_hits = b;
338        self
339    }
340
341    /// Sets the partitioning policy for filter blocks.
342    #[must_use]
343    pub fn filter_block_partitioning_policy(mut self, policy: PinningPolicy) -> Self {
344        self.filter_block_partitioning_policy = policy;
345        self
346    }
347
348    /// Sets the partitioning policy for index blocks.
349    #[must_use]
350    pub fn index_block_partitioning_policy(mut self, policy: PinningPolicy) -> Self {
351        self.index_block_partitioning_policy = policy;
352        self
353    }
354
355    /// Sets the pinning policy for filter blocks.
356    #[must_use]
357    pub fn filter_block_pinning_policy(mut self, policy: PinningPolicy) -> Self {
358        self.filter_block_pinning_policy = policy;
359        self
360    }
361
362    /// Sets the pinning policy for index blocks.
363    #[must_use]
364    pub fn index_block_pinning_policy(mut self, policy: PinningPolicy) -> Self {
365        self.index_block_pinning_policy = policy;
366        self
367    }
368
369    /// Sets the restart interval inside data blocks.
370    ///
371    /// A higher restart interval saves space while increasing lookup times
372    /// inside data blocks.
373    ///
374    /// Default = 16
375    #[must_use]
376    pub fn data_block_restart_interval_policy(mut self, policy: RestartIntervalPolicy) -> Self {
377        self.data_block_restart_interval_policy = policy;
378        self
379    }
380
381    // TODO: not supported yet in index blocks
382    // /// Sets the restart interval inside index blocks.
383    // ///
384    // /// A higher restart interval saves space while increasing lookup times
385    // /// inside index blocks.
386    // ///
387    // /// Default = 1
388    // #[must_use]
389    // pub fn index_block_restart_interval_policy(mut self, policy: RestartIntervalPolicy) -> Self {
390    //     self.index_block_restart_interval_policy = policy;
391    //     self
392    // }
393
394    /// Sets the filter construction policy.
395    #[must_use]
396    pub fn filter_policy(mut self, policy: FilterPolicy) -> Self {
397        self.filter_policy = policy;
398        self
399    }
400
401    /// Sets the compression method for data blocks.
402    #[must_use]
403    pub fn data_block_compression_policy(mut self, policy: CompressionPolicy) -> Self {
404        self.data_block_compression_policy = policy;
405        self
406    }
407
408    /// Sets the compression method for index blocks.
409    #[must_use]
410    pub fn index_block_compression_policy(mut self, policy: CompressionPolicy) -> Self {
411        self.index_block_compression_policy = policy;
412        self
413    }
414
415    // TODO: level count is fixed to 7 right now
416    // /// Sets the number of levels of the LSM tree (depth of tree).
417    // ///
418    // /// Defaults to 7, like `LevelDB` and `RocksDB`.
419    // ///
420    // /// Cannot be changed once set.
421    // ///
422    // /// # Panics
423    // ///
424    // /// Panics if `n` is 0.
425    // #[must_use]
426    // pub fn level_count(mut self, n: u8) -> Self {
427    //     assert!(n > 0);
428
429    //     self.level_count = n;
430    //     self
431    // }
432
433    /// Sets the data block size policy.
434    #[must_use]
435    pub fn data_block_size_policy(mut self, policy: BlockSizePolicy) -> Self {
436        self.data_block_size_policy = policy;
437        self
438    }
439
440    /// Sets the hash ratio policy for data blocks.
441    ///
442    /// If greater than 0.0, a hash index is embedded into data blocks that can speed up reads
443    /// inside the data block.
444    #[must_use]
445    pub fn data_block_hash_ratio_policy(mut self, policy: HashRatioPolicy) -> Self {
446        self.data_block_hash_ratio_policy = policy;
447        self
448    }
449
450    /// Toggles key-value separation.
451    #[must_use]
452    pub fn with_kv_separation(mut self, opts: Option<KvSeparationOptions>) -> Self {
453        self.kv_separation_opts = opts;
454        self
455    }
456
457    /// Opens a tree using the config.
458    ///
459    /// # Errors
460    ///
461    /// Will return `Err` if an IO error occurs.
462    pub fn open(self) -> crate::Result<AnyTree> {
463        Ok(if self.kv_separation_opts.is_some() {
464            AnyTree::Blob(BlobTree::open(self)?)
465        } else {
466            AnyTree::Standard(Tree::open(self)?)
467        })
468    }
469}