lsm_tree/snapshot.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
// Copyright (c) 2024-present, fjall-rs
// This source code is licensed under both the Apache 2.0 and MIT License
// (found in the LICENSE-* files in the repository)
use crate::{
value::{SeqNo, UserKey, UserValue},
AbstractTree, AnyTree, KvPair,
};
use std::ops::RangeBounds;
/// A snapshot captures a read-only point-in-time view of the tree at the time the snapshot was created
///
/// As long as the snapshot is open, old versions of objects will not be evicted as to
/// keep the snapshot consistent. Thus, snapshots should only be kept around for as little as possible.
///
/// Snapshots do not persist across restarts.
#[derive(Clone)]
pub struct Snapshot {
tree: AnyTree,
#[doc(hidden)]
pub seqno: SeqNo,
}
impl Snapshot {
/// Creates a snapshot
pub(crate) fn new(tree: AnyTree, seqno: SeqNo) -> Self {
log::trace!("Opening snapshot with seqno: {seqno}");
Self { tree, seqno }
}
/// Retrieves an item from the snapshot.
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
/// let snapshot = tree.snapshot(0);
///
/// tree.insert("a", "my_value", 0);
///
/// let item = snapshot.get("a")?;
/// assert_eq!(None, item);
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
///
/// # Errors
///
/// Will return `Err` if an IO error occurs.
pub fn get<K: AsRef<[u8]>>(&self, key: K) -> crate::Result<Option<UserValue>> {
self.tree.get_with_seqno(key, self.seqno)
}
/// Returns an iterator that scans through the entire snapshot.
///
/// Avoid using this function, or limit it as otherwise it may scan a lot of items.
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
///
/// tree.insert("a", "abc", 0);
/// tree.insert("f", "abc", 1);
/// let snapshot = tree.snapshot(2);
///
/// tree.insert("g", "abc", 2);
///
/// assert_eq!(2, snapshot.iter().count());
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
#[must_use]
pub fn iter(&self) -> impl DoubleEndedIterator<Item = crate::Result<KvPair>> + 'static {
self.tree.iter_with_seqno(self.seqno, None)
}
/// Returns an iterator that scans through the entire snapshot, returning keys only.
///
/// Avoid using this function, or limit it as otherwise it may scan a lot of items.
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
///
/// tree.insert("a", "abc", 0);
/// tree.insert("f", "abc", 1);
/// let snapshot = tree.snapshot(2);
///
/// tree.insert("g", "abc", 2);
///
/// assert_eq!(2, snapshot.keys().count());
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
#[must_use]
pub fn keys(&self) -> impl DoubleEndedIterator<Item = crate::Result<UserKey>> + 'static {
self.tree.keys_with_seqno(self.seqno, None)
}
/// Returns an iterator that scans through the entire snapshot, returning values only.
///
/// Avoid using this function, or limit it as otherwise it may scan a lot of items.
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
///
/// tree.insert("a", "abc", 0);
/// tree.insert("f", "abc", 1);
/// let snapshot = tree.snapshot(2);
///
/// tree.insert("g", "abc", 2);
///
/// assert_eq!(2, snapshot.values().count());
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
#[must_use]
pub fn values(&self) -> impl DoubleEndedIterator<Item = crate::Result<UserValue>> + 'static {
self.tree.values_with_seqno(self.seqno, None)
}
/// Returns an iterator over a range of items in the snapshot.
///
/// Avoid using full or unbounded ranges as they may scan a lot of items (unless limited).
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
///
/// tree.insert("a", "abc", 0);
/// let snapshot = tree.snapshot(1);
///
/// tree.insert("f", "abc", 1);
/// tree.insert("g", "abc", 2);
///
/// assert_eq!(1, snapshot.range("a"..="f").count());
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
pub fn range<K: AsRef<[u8]>, R: RangeBounds<K>>(
&self,
range: R,
) -> impl DoubleEndedIterator<Item = crate::Result<KvPair>> + 'static {
self.tree.range_with_seqno(range, self.seqno, None)
}
/// Returns an iterator over a prefixed set of items in the snapshot.
///
/// Avoid using an empty prefix as it may scan a lot of items (unless limited).
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
///
/// tree.insert("a", "abc", 0);
/// tree.insert("ab", "abc", 1);
/// let snapshot = tree.snapshot(2);
///
/// tree.insert("abc", "abc", 2);
///
/// assert_eq!(2, snapshot.prefix("a").count());
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
pub fn prefix<K: AsRef<[u8]>>(
&self,
prefix: K,
) -> impl DoubleEndedIterator<Item = crate::Result<KvPair>> + 'static {
self.tree.prefix_with_seqno(prefix, self.seqno, None)
}
/// Returns the first key-value pair in the snapshot.
/// The key in this pair is the minimum key in the snapshot.
///
/// # Examples
///
/// ```
/// # use lsm_tree::Error as TreeError;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// # let folder = tempfile::tempdir()?;
/// let tree = Config::new(folder).open()?;
///
/// tree.insert("5", "abc", 0);
/// tree.insert("3", "abc", 1);
/// let snapshot = tree.snapshot(2);
///
/// tree.insert("1", "abc", 2);
///
/// let (key, _) = snapshot.first_key_value()?.expect("item should exist");
/// assert_eq!(&*key, "3".as_bytes());
/// #
/// # Ok::<(), TreeError>(())
/// ```
///
/// # Errors
///
/// Will return `Err` if an IO error occurs.
pub fn first_key_value(&self) -> crate::Result<Option<(UserKey, UserValue)>> {
self.iter().next().transpose()
}
/// Returns the las key-value pair in the snapshot.
/// The key in this pair is the maximum key in the snapshot.
///
/// # Examples
///
/// ```
/// # use lsm_tree::Error as TreeError;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// # let folder = tempfile::tempdir()?;
/// let tree = Config::new(folder).open()?;
///
/// tree.insert("1", "abc", 0);
/// tree.insert("3", "abc", 1);
/// let snapshot = tree.snapshot(2);
///
/// tree.insert("5", "abc", 2);
///
/// let (key, _) = snapshot.last_key_value()?.expect("item should exist");
/// assert_eq!(&*key, "3".as_bytes());
/// #
/// # Ok::<(), TreeError>(())
/// ```
///
/// # Errors
///
/// Will return `Err` if an IO error occurs.
pub fn last_key_value(&self) -> crate::Result<Option<(UserKey, UserValue)>> {
self.iter().next_back().transpose()
}
/// Returns `true` if the snapshot contains the specified key.
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
/// let snapshot = tree.snapshot(0);
///
/// assert!(!snapshot.contains_key("a")?);
///
/// tree.insert("a", "abc", 0);
/// assert!(!snapshot.contains_key("a")?);
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
///
/// # Errors
///
/// Will return `Err` if an IO error occurs.
pub fn contains_key<K: AsRef<[u8]>>(&self, key: K) -> crate::Result<bool> {
self.tree.contains_key_with_seqno(key, self.seqno)
}
/// Returns `true` if the snapshot is empty.
///
/// This operation has O(1) complexity.
///
/// # Examples
///
/// ```
/// # let folder = tempfile::tempdir()?;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// let tree = Config::new(folder).open()?;
/// let snapshot = tree.snapshot(0);
///
/// assert!(snapshot.is_empty()?);
///
/// tree.insert("a", "abc", 0);
/// assert!(snapshot.is_empty()?);
/// #
/// # Ok::<(), lsm_tree::Error>(())
/// ```
///
/// # Errors
///
/// Will return `Err` if an IO error occurs.
pub fn is_empty(&self) -> crate::Result<bool> {
self.first_key_value().map(|x| x.is_none())
}
/// Scans the entire snapshot, returning the amount of items.
///
/// ###### Caution
///
/// This operation scans the entire tree: O(n) complexity!
///
/// Never, under any circumstances, use .`len()` == 0 to check
/// if the snapshot is empty, use [`Snapshot::is_empty`] instead.
///
/// # Examples
///
/// ```
/// # use lsm_tree::Error as TreeError;
/// use lsm_tree::{AbstractTree, Config, Tree};
///
/// # let folder = tempfile::tempdir()?;
/// let tree = Config::new(folder).open()?;
/// let snapshot = tree.snapshot(0);
///
/// assert_eq!(snapshot.len()?, 0);
/// tree.insert("1", "abc", 0);
/// tree.insert("3", "abc", 1);
/// tree.insert("5", "abc", 2);
/// assert_eq!(snapshot.len()?, 0);
/// #
/// # Ok::<(), TreeError>(())
/// ```
///
/// # Errors
///
/// Will return `Err` if an IO error occurs.
pub fn len(&self) -> crate::Result<usize> {
let mut count = 0;
for item in self.iter() {
let _ = item?;
count += 1;
}
Ok(count)
}
}