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
//! `sled` is a high-performance embedded database with //! an API that is similar to a `BTreeMap<[u8], [u8]>`, //! but with several additional capabilities for //! assisting creators of stateful systems. //! //! It is fully thread-safe, and all operations are //! atomic. Multiple `Tree`s are supported with the //! [`Db::open_tree`](struct.Db.html#method.open_tree) method. //! //! ACID transactions involving reads and writes to //! multiple items are supported with the //! [`Tree::transaction`](struct.Tree.html#method.transaction) //! method. Transactions may also operate over //! multiple `Tree`s (see //! [`Tree::transaction`](struct.Tree.html#method.transaction) //! docs for more info). //! //! Users may also subscribe to updates on individual //! `Tree`s by using the //! [`Tree::watch_prefix`](struct.Tree.html#method.watch_prefix) //! method, which returns a blocking `Iterator` over //! updates to keys that begin with the provided //! prefix. You may supply an empty prefix to subscribe //! to everything. //! //! [Merge operators](https://github.com/spacejam/sled/wiki/merge-operators) //! (aka read-modify-write operators) are supported. A //! merge operator is a function that specifies //! how new data can be merged into an existing value //! without requiring both a read and a write. //! Using the //! [`Tree::merge`](struct.Tree.html#method.merge) //! method, you may "push" data to a `Tree` value //! and have the provided merge operator combine //! it with the existing value, if there was one. //! They are set on a per-`Tree` basis, and essentially //! allow any sort of data structure to be built //! using merges as an atomic high-level operation. //! //! `sled` is built by experienced database engineers //! who think users should spend less time tuning and //! working against high-friction APIs. Expect //! significant ergonomic and performance improvements //! over time. Most surprises are bugs, so please //! [let us know](mailto:t@jujit.su?subject=sled%20sucks!!!) if something //! is high friction. //! //! # Examples //! //! ``` //! use sled::Db; //! //! let t = Db::open("my_db").unwrap(); //! //! // insert and get //! t.insert(b"yo!", b"v1"); //! assert_eq!(&t.get(b"yo!").unwrap().unwrap(), b"v1"); //! //! // Atomic compare-and-swap. //! t.compare_and_swap( //! b"yo!", // key //! Some(b"v1"), // old value, None for not present //! Some(b"v2"), // new value, None for delete //! ) //! .unwrap(); //! //! // Iterates over key-value pairs, starting at the given key. //! let scan_key: &[u8] = b"a non-present key before yo!"; //! let mut iter = t.range(scan_key..); //! assert_eq!(&iter.next().unwrap().unwrap().0, b"yo!"); //! assert_eq!(iter.next(), None); //! //! t.remove(b"yo!"); //! assert_eq!(t.get(b"yo!"), Ok(None)); //! ``` #![doc( html_logo_url = "https://raw.githubusercontent.com/spacejam/sled/master/art/tree_face_anti-transphobia.png" )] #![cfg_attr(test, deny(warnings))] #![deny(missing_docs)] #![deny(future_incompatible)] #![deny(nonstandard_style)] #![deny(rust_2018_idioms)] #![deny(missing_copy_implementations)] #![deny(trivial_casts)] #![deny(trivial_numeric_casts)] #![deny(unsafe_code)] #![deny(unused_qualifications)] #[cfg(feature = "failpoints")] use fail::fail_point; macro_rules! maybe_fail { ($e:expr) => { #[cfg(feature = "failpoints")] fail_point!($e, |_| Err(Error::FailPoint)); }; } mod batch; mod binary_search; mod config; mod context; mod db; mod dll; mod frag; mod histogram; mod iter; mod ivec; mod lazy; mod lru; mod meta; mod metrics; mod node; mod oneshot; mod pagecache; mod pagetable; mod prefix; mod result; mod stack; mod subscription; mod sys_limits; mod threadpool; mod transaction; mod tree; mod vecset; #[cfg(any(windows, target_os = "linux", target_os = "macos"))] mod flusher; #[cfg(feature = "event_log")] /// The event log helps debug concurrency issues. pub mod event_log; #[cfg(feature = "measure_allocs")] mod measure_allocs; #[cfg(feature = "measure_allocs")] #[global_allocator] static ALLOCATOR: measure_allocs::TrackingAllocator = measure_allocs::TrackingAllocator; const DEFAULT_TREE_ID: &[u8] = b"__sled__default"; /// hidden re-export of items for testing purposes #[doc(hidden)] pub use { self::{ config::RunningConfig, lazy::Lazy, pagecache::{ constants::{ MAX_SPACE_AMPLIFICATION, MINIMUM_ITEMS_PER_SEGMENT, MSG_HEADER_LEN, SEG_HEADER_LEN, }, DiskPtr, Log, LogKind, LogOffset, LogRead, Lsn, PageCache, PageId, SegmentMode, }, pagetable::PAGETABLE_NODE_SZ, }, crossbeam_epoch::{pin, Atomic, Guard, Owned, Shared}, }; pub use self::{ batch::Batch, config::Config, db::Db, iter::Iter, ivec::IVec, result::{Error, Result}, subscription::{Event, Subscriber}, transaction::{ abort, ConflictableTransactionError, ConflictableTransactionResult, TransactionError, TransactionResult, Transactional, TransactionalTree, }, tree::{CompareAndSwapError, CompareAndSwapResult, Tree}, }; use { self::{ binary_search::interpolation_search_lub, config::PersistedConfig, context::Context, frag::Frag, histogram::Histogram, lru::Lru, meta::Meta, metrics::{clock, measure, Measure, M}, node::{Data, Node}, oneshot::{OneShot, OneShotFiller}, pagetable::PageTable, result::CasResult, stack::{node_from_frag_vec, Stack, StackIter}, subscription::Subscriptions, tree::TreeInner, vecset::VecSet, }, bincode::{deserialize, serialize}, crossbeam_utils::{Backoff, CachePadded}, log::{debug, error, trace, warn}, pagecache::RecoveryGuard, parking_lot::{Condvar, Mutex, RwLock}, serde::{Deserialize, Serialize}, std::{ collections::BTreeMap, convert::TryFrom, fmt::{self, Debug}, io::{Read, Write}, sync::{ atomic::{ AtomicI64 as AtomicLsn, AtomicU64, AtomicUsize, Ordering::{Acquire, Relaxed, Release, SeqCst}, }, Arc, }, }, }; fn crc32(buf: &[u8]) -> u32 { let mut hasher = crc32fast::Hasher::new(); hasher.update(&buf); hasher.finalize() } type TreePtr<'g> = pagecache::PagePtr<'g>; #[cfg(any(test, feature = "lock_free_delays"))] mod debug_delay; #[cfg(any(test, feature = "lock_free_delays"))] use debug_delay::debug_delay; /// This function is useful for inducing random jitter into our atomic /// operations, shaking out more possible interleavings quickly. It gets /// fully eliminated by the compiler in non-test code. #[cfg(not(any(test, feature = "lock_free_delays")))] fn debug_delay() {} /// A fast map that is not resistant to collision attacks. Works /// on 8 bytes at a time. pub(crate) type FastMap8<K, V> = std::collections::HashMap< K, V, std::hash::BuildHasherDefault<fxhash::FxHasher64>, >; /// A fast set that is not resistant to collision attacks. Works /// on 8 bytes at a time. pub(crate) type FastSet8<V> = std::collections::HashSet< V, std::hash::BuildHasherDefault<fxhash::FxHasher64>, >; /// Allows arbitrary logic to be injected into mere operations of the /// `PageCache`. pub type MergeOperator = fn( key: &[u8], last_value: Option<&[u8]>, new_merge: &[u8], ) -> Option<Vec<u8>>;