-
Notifications
You must be signed in to change notification settings - Fork 427
Expand file tree
/
Copy pathtree.rs
More file actions
2533 lines (2341 loc) · 81.3 KB
/
Copy pathtree.rs
File metadata and controls
2533 lines (2341 loc) · 81.3 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
borrow::Cow,
fmt::{self, Debug},
num::NonZeroU64,
ops::{self, Deref, RangeBounds},
sync::atomic::Ordering::SeqCst,
};
use parking_lot::RwLock;
use crate::{atomic_shim::AtomicU64, pagecache::NodeView, *};
#[derive(Debug, Clone)]
pub(crate) struct View<'g> {
pub node_view: NodeView<'g>,
pub pid: PageId,
}
impl<'g> Deref for View<'g> {
type Target = Node;
fn deref(&self) -> &Node {
&self.node_view
}
}
impl IntoIterator for &'_ Tree {
type Item = Result<(IVec, IVec)>;
type IntoIter = Iter;
fn into_iter(self) -> Iter {
self.iter()
}
}
const fn out_of_bounds(numba: usize) -> bool {
numba > MAX_BLOB
}
#[cold]
const fn bounds_error() -> Result<()> {
Err(Error::Unsupported(
"Keys and values are limited to \
128gb on 64-bit platforms and
512mb on 32-bit platforms."
))
}
/// A flash-sympathetic persistent lock-free B+ tree.
///
/// A `Tree` represents a single logical keyspace / namespace / bucket.
///
/// Separate `Trees` may be opened to separate concerns using
/// `Db::open_tree`.
///
/// `Db` implements `Deref<Target = Tree>` such that a `Db` acts
/// like the "default" `Tree`. This is the only `Tree` that cannot
/// be deleted via `Db::drop_tree`.
///
/// When a `Db` or `Tree` is dropped, `flush` is called to attempt
/// to flush all buffered writes to disk.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use sled::IVec;
///
/// # let _ = std::fs::remove_dir_all("db");
/// let db: sled::Db = sled::open("db")?;
/// db.insert(b"yo!", b"v1".to_vec());
/// assert_eq!(db.get(b"yo!"), Ok(Some(IVec::from(b"v1"))));
///
/// // Atomic compare-and-swap.
/// db.compare_and_swap(
/// b"yo!", // key
/// Some(b"v1"), // old value, None for not present
/// Some(b"v2"), // new value, None for delete
/// )?;
///
/// // Iterates over key-value pairs, starting at the given key.
/// let scan_key: &[u8] = b"a non-present key before yo!";
/// let mut iter = db.range(scan_key..);
/// assert_eq!(
/// iter.next().unwrap(),
/// Ok((IVec::from(b"yo!"), IVec::from(b"v2")))
/// );
/// assert_eq!(iter.next(), None);
///
/// db.remove(b"yo!");
/// assert_eq!(db.get(b"yo!"), Ok(None));
///
/// let other_tree: sled::Tree = db.open_tree(b"cool db facts")?;
/// other_tree.insert(
/// b"k1",
/// &b"a Db acts like a Tree due to implementing Deref<Target = Tree>"[..]
/// )?;
/// # let _ = std::fs::remove_dir_all("db");
/// # Ok(()) }
/// ```
#[derive(Clone)]
#[doc(alias = "keyspace")]
#[doc(alias = "bucket")]
#[doc(alias = "table")]
pub struct Tree(pub(crate) Arc<TreeInner>);
#[allow(clippy::module_name_repetitions)]
pub struct TreeInner {
pub(crate) tree_id: IVec,
pub(crate) context: Context,
pub(crate) subscribers: Subscribers,
pub(crate) root: AtomicU64,
pub(crate) merge_operator: RwLock<Option<Box<dyn MergeOperator>>>,
}
impl Drop for TreeInner {
fn drop(&mut self) {
// Flush the underlying system in a loop until we
// have flushed all dirty data.
loop {
match self.context.pagecache.flush() {
Ok(0) => return,
Ok(_) => continue,
Err(e) => {
error!("failed to flush data to disk: {:?}", e);
return;
}
}
}
}
}
impl Deref for Tree {
type Target = TreeInner;
fn deref(&self) -> &TreeInner {
&self.0
}
}
impl Tree {
/// Insert a key to a new value, returning the last value if it
/// was set.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// assert_eq!(db.insert(&[1, 2, 3], vec![0]), Ok(None));
/// assert_eq!(db.insert(&[1, 2, 3], vec![1]), Ok(Some(sled::IVec::from(&[0]))));
/// # Ok(()) }
/// ```
#[doc(alias = "set")]
pub fn insert<K, V>(&self, key: K, value: V) -> Result<Option<IVec>>
where
K: AsRef<[u8]>,
V: Into<IVec>,
{
let value_ivec = value.into();
let mut guard = pin();
let _cc = concurrency_control::read();
loop {
trace!("setting key {:?}", key.as_ref());
if let Ok(res) = self.insert_inner(
key.as_ref(),
Some(value_ivec.clone()),
false,
&mut guard,
)? {
return Ok(res);
}
}
}
pub(crate) fn insert_inner(
&self,
key: &[u8],
value: Option<IVec>,
is_transactional: bool,
guard: &mut Guard,
) -> Result<Conflictable<Option<IVec>>> {
#[cfg(feature = "metrics")]
let _measure = if value.is_some() {
Measure::new(&M.tree_set)
} else {
Measure::new(&M.tree_del)
};
if out_of_bounds(key.len()) {
bounds_error()?;
}
let View { node_view, pid, .. } =
self.view_for_key(key.as_ref(), guard)?;
let mut subscriber_reservation = if is_transactional {
None
} else {
Some(self.subscribers.reserve(key))
};
let (encoded_key, last_value) = node_view.node_kv_pair(key.as_ref());
let last_value_ivec = last_value.map(IVec::from);
if value == last_value_ivec {
// NB: always broadcast event
if let Some(Some(res)) = subscriber_reservation.take() {
let event = subscriber::Event::single_update(
self.clone(),
key.as_ref().into(),
value,
);
res.complete(&event);
}
// short-circuit a no-op set or delete
return Ok(Ok(last_value_ivec));
}
let frag = if let Some(value_ivec) = value.clone() {
if out_of_bounds(value_ivec.len()) {
bounds_error()?;
}
Link::Set(encoded_key, value_ivec)
} else {
Link::Del(encoded_key)
};
let link =
self.context.pagecache.link(pid, node_view.0, frag, guard)?;
if link.is_ok() {
// success
if let Some(Some(res)) = subscriber_reservation.take() {
let event = subscriber::Event::single_update(
self.clone(),
key.as_ref().into(),
value,
);
res.complete(&event);
}
Ok(Ok(last_value_ivec))
} else {
#[cfg(feature = "metrics")]
M.tree_looped();
Ok(Err(Conflict))
}
}
/// Perform a multi-key serializable transaction.
///
/// sled transactions are **optimistic** which means that
/// they may re-run in cases where conflicts are detected.
/// Do not perform IO or interact with state outside
/// of the closure unless it is idempotent, because
/// it may re-run several times.
///
/// # Examples
///
/// ```
/// # use sled::{transaction::TransactionResult, Config};
/// # fn main() -> TransactionResult<()> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// // Use write-only transactions as a writebatch:
/// db.transaction(|tx_db| {
/// tx_db.insert(b"k1", b"cats")?;
/// tx_db.insert(b"k2", b"dogs")?;
/// Ok(())
/// })?;
///
/// // Atomically swap two items:
/// db.transaction(|tx_db| {
/// let v1_option = tx_db.remove(b"k1")?;
/// let v1 = v1_option.unwrap();
/// let v2_option = tx_db.remove(b"k2")?;
/// let v2 = v2_option.unwrap();
///
/// tx_db.insert(b"k1", v2)?;
/// tx_db.insert(b"k2", v1)?;
///
/// Ok(())
/// })?;
///
/// assert_eq!(&db.get(b"k1")?.unwrap(), b"dogs");
/// assert_eq!(&db.get(b"k2")?.unwrap(), b"cats");
/// # Ok(())
/// # }
/// ```
///
/// A transaction may return information from
/// an intentionally-cancelled transaction by using
/// the abort function inside the closure in
/// combination with the try operator.
///
/// ```
/// use sled::{transaction::{abort, TransactionError, TransactionResult}, Config};
///
/// #[derive(Debug, PartialEq)]
/// struct MyBullshitError;
///
/// fn main() -> TransactionResult<(), MyBullshitError> {
/// let config = Config::new().temporary(true);
/// let db = config.open()?;
///
/// // Use write-only transactions as a writebatch:
/// let res = db.transaction(|tx_db| {
/// tx_db.insert(b"k1", b"cats")?;
/// tx_db.insert(b"k2", b"dogs")?;
/// // aborting will cause all writes to roll-back.
/// if true {
/// abort(MyBullshitError)?;
/// }
/// Ok(42)
/// }).unwrap_err();
///
/// assert_eq!(res, TransactionError::Abort(MyBullshitError));
/// assert_eq!(db.get(b"k1")?, None);
/// assert_eq!(db.get(b"k2")?, None);
///
/// Ok(())
/// }
/// ```
///
///
/// Transactions also work on tuples of `Tree`s,
/// preserving serializable ACID semantics!
/// In this example, we treat two trees like a
/// work queue, atomically apply updates to
/// data and move them from the unprocessed `Tree`
/// to the processed `Tree`.
///
/// ```
/// # use sled::transaction::TransactionResult;
/// # fn main() -> TransactionResult<()> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// use sled::Transactional;
///
/// let unprocessed = db.open_tree(b"unprocessed items")?;
/// let processed = db.open_tree(b"processed items")?;
///
/// // An update somehow gets into the tree, which we
/// // later trigger the atomic processing of.
/// unprocessed.insert(b"k3", b"ligers")?;
///
/// // Atomically process the new item and move it
/// // between `Tree`s.
/// (&unprocessed, &processed)
/// .transaction(|(tx_unprocessed, tx_processed)| {
/// let unprocessed_item = tx_unprocessed.remove(b"k3")?.unwrap();
/// let mut processed_item = b"yappin' ".to_vec();
/// processed_item.extend_from_slice(&unprocessed_item);
/// tx_processed.insert(b"k3", processed_item)?;
/// Ok(())
/// })?;
///
/// assert_eq!(unprocessed.get(b"k3").unwrap(), None);
/// assert_eq!(&processed.get(b"k3").unwrap().unwrap(), b"yappin' ligers");
/// # Ok(()) }
/// ```
pub fn transaction<F, A, E>(
&self,
f: F,
) -> transaction::TransactionResult<A, E>
where
F: Fn(
&transaction::TransactionalTree,
) -> transaction::ConflictableTransactionResult<A, E>,
{
Transactional::transaction(&self, f)
}
/// Create a new batched update that can be
/// atomically applied.
///
/// It is possible to apply a `Batch` in a transaction
/// as well, which is the way you can apply a `Batch`
/// to multiple `Tree`s atomically.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// db.insert("key_0", "val_0")?;
///
/// let mut batch = sled::Batch::default();
/// batch.insert("key_a", "val_a");
/// batch.insert("key_b", "val_b");
/// batch.insert("key_c", "val_c");
/// batch.remove("key_0");
///
/// db.apply_batch(batch)?;
/// // key_0 no longer exists, and key_a, key_b, and key_c
/// // now do exist.
/// # Ok(()) }
/// ```
pub fn apply_batch(&self, batch: Batch) -> Result<()> {
let _cc = concurrency_control::write();
let mut guard = pin();
self.apply_batch_inner(batch, None, &mut guard)
}
pub(crate) fn apply_batch_inner(
&self,
batch: Batch,
transaction_batch_opt: Option<Event>,
guard: &mut Guard,
) -> Result<()> {
let peg_opt = if transaction_batch_opt.is_none() {
Some(self.context.pin_log(guard)?)
} else {
None
};
trace!("applying batch {:?}", batch);
let mut subscriber_reservation = self.subscribers.reserve_batch(&batch);
for (k, v_opt) in &batch.writes {
loop {
if self
.insert_inner(
k,
v_opt.clone(),
transaction_batch_opt.is_some(),
guard,
)?
.is_ok()
{
break;
}
}
}
if let Some(res) = subscriber_reservation.take() {
if let Some(transaction_batch) = transaction_batch_opt {
res.complete(&transaction_batch);
} else {
res.complete(&Event::single_batch(self.clone(), batch));
}
}
if let Some(peg) = peg_opt {
// when the peg drops, it ensures all updates
// written to the log since its creation are
// recovered atomically
peg.seal_batch()
} else {
Ok(())
}
}
/// Retrieve a value from the `Tree` if it exists.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// db.insert(&[0], vec![0])?;
/// assert_eq!(db.get(&[0]), Ok(Some(sled::IVec::from(vec![0]))));
/// assert_eq!(db.get(&[1]), Ok(None));
/// # Ok(()) }
/// ```
pub fn get<K: AsRef<[u8]>>(&self, key: K) -> Result<Option<IVec>> {
let mut guard = pin();
let _cc = concurrency_control::read();
loop {
if let Ok(get) = self.get_inner(key.as_ref(), &mut guard)? {
return Ok(get);
}
}
}
/// Pass the result of getting a key's value to a closure
/// without making a new allocation. This effectively
/// "pushes" your provided code to the data without ever copying
/// the data, rather than "pulling" a copy of the data to whatever code
/// is calling `get`.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// db.insert(&[0], vec![0])?;
/// db.get_zero_copy(&[0], |value_opt| {
/// assert_eq!(
/// value_opt,
/// Some(&[0][..])
/// )
/// });
/// db.get_zero_copy(&[1], |value_opt| assert!(value_opt.is_none()));
/// # Ok(()) }
/// ```
pub fn get_zero_copy<K: AsRef<[u8]>, B, F: FnOnce(Option<&[u8]>) -> B>(
&self,
key: K,
f: F,
) -> Result<B> {
let guard = pin();
let _cc = concurrency_control::read();
#[cfg(feature = "metrics")]
let _measure = Measure::new(&M.tree_get);
trace!("getting key {:?}", key.as_ref());
let View { node_view, .. } = self.view_for_key(key.as_ref(), &guard)?;
let pair = node_view.node_kv_pair(key.as_ref());
let ret = f(pair.1);
Ok(ret)
}
pub(crate) fn get_inner(
&self,
key: &[u8],
guard: &mut Guard,
) -> Result<Conflictable<Option<IVec>>> {
#[cfg(feature = "metrics")]
let _measure = Measure::new(&M.tree_get);
trace!("getting key {:?}", key);
let View { node_view, .. } = self.view_for_key(key.as_ref(), guard)?;
let pair = node_view.node_kv_pair(key.as_ref());
let val = pair.1.map(IVec::from);
Ok(Ok(val))
}
/// Delete a value, returning the old value if it existed.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// db.insert(&[1], vec![1]);
/// assert_eq!(db.remove(&[1]), Ok(Some(sled::IVec::from(vec![1]))));
/// assert_eq!(db.remove(&[1]), Ok(None));
/// # Ok(()) }
/// ```
#[doc(alias = "delete")]
#[doc(alias = "del")]
pub fn remove<K: AsRef<[u8]>>(&self, key: K) -> Result<Option<IVec>> {
let mut guard = pin();
let _cc = concurrency_control::read();
loop {
trace!("removing key {:?}", key.as_ref());
if let Ok(res) =
self.insert_inner(key.as_ref(), None, false, &mut guard)?
{
return Ok(res);
}
}
}
/// Compare and swap. Capable of unique creation, conditional modification,
/// or deletion. If old is `None`, this will only set the value if it
/// doesn't exist yet. If new is `None`, will delete the value if old is
/// correct. If both old and new are `Some`, will modify the value if
/// old is correct.
///
/// It returns `Ok(Ok(()))` if operation finishes successfully.
///
/// If it fails it returns:
/// - `Ok(Err(CompareAndSwapError(current, proposed)))` if operation
/// failed to setup a new value. `CompareAndSwapError` contains
/// current and proposed values.
/// - `Err(Error::Unsupported)` if the database is opened in read-only
/// mode.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// // unique creation
/// assert_eq!(
/// db.compare_and_swap(&[1], None as Option<&[u8]>, Some(&[10])),
/// Ok(Ok(()))
/// );
///
/// // conditional modification
/// assert_eq!(
/// db.compare_and_swap(&[1], Some(&[10]), Some(&[20])),
/// Ok(Ok(()))
/// );
///
/// // failed conditional modification -- the current value is returned in
/// // the error variant
/// let operation = db.compare_and_swap(&[1], Some(&[30]), Some(&[40]));
/// assert!(operation.is_ok()); // the operation succeeded
/// let modification = operation.unwrap();
/// assert!(modification.is_err());
/// let actual_value = modification.unwrap_err();
/// assert_eq!(actual_value.current.map(|ivec| ivec.to_vec()), Some(vec![20]));
///
/// // conditional deletion
/// assert_eq!(
/// db.compare_and_swap(&[1], Some(&[20]), None as Option<&[u8]>),
/// Ok(Ok(()))
/// );
/// assert_eq!(db.get(&[1]), Ok(None));
/// # Ok(()) }
/// ```
#[allow(clippy::needless_pass_by_value)]
#[doc(alias = "cas")]
#[doc(alias = "tas")]
#[doc(alias = "test_and_swap")]
#[doc(alias = "compare_and_set")]
pub fn compare_and_swap<K, OV, NV>(
&self,
key: K,
old: Option<OV>,
new: Option<NV>,
) -> CompareAndSwapResult
where
K: AsRef<[u8]>,
OV: AsRef<[u8]>,
NV: Into<IVec>,
{
trace!("cas'ing key {:?}", key.as_ref());
#[cfg(feature = "metrics")]
let _measure = Measure::new(&M.tree_cas);
let guard = pin();
let _cc = concurrency_control::read();
let new2 = new.map(Into::into);
// we need to retry caps until old != cur, since just because
// cap fails it doesn't mean our value was changed.
loop {
let View { pid, node_view, .. } =
self.view_for_key(key.as_ref(), &guard)?;
let (encoded_key, current_value) =
node_view.node_kv_pair(key.as_ref());
let matches = match (old.as_ref(), ¤t_value) {
(None, None) => true,
(Some(o), Some(c)) => o.as_ref() == &**c,
_ => false,
};
if !matches {
return Ok(Err(CompareAndSwapError {
current: current_value.map(IVec::from),
proposed: new2,
}));
}
if current_value == new2.as_ref().map(AsRef::as_ref) {
// short-circuit no-op write. this is still correct
// because we verified that the input matches, so
// doing the work has the same semantic effect as not
// doing it in this case.
return Ok(Ok(()));
}
let mut subscriber_reservation = self.subscribers.reserve(&key);
let frag = if let Some(ref new3) = new2 {
Link::Set(encoded_key, new3.clone())
} else {
Link::Del(encoded_key)
};
let link =
self.context.pagecache.link(pid, node_view.0, frag, &guard)?;
if link.is_ok() {
if let Some(res) = subscriber_reservation.take() {
let event = subscriber::Event::single_update(
self.clone(),
key.as_ref().into(),
new2,
);
res.complete(&event);
}
return Ok(Ok(()));
}
#[cfg(feature = "metrics")]
M.tree_looped();
}
}
/// Fetch the value, apply a function to it and return the result.
///
/// # Note
///
/// This may call the function multiple times if the value has been
/// changed from other threads in the meantime.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use sled::{Config, Error, IVec};
/// use std::convert::TryInto;
///
/// let config = Config::new().temporary(true);
/// let db = config.open()?;
///
/// fn u64_to_ivec(number: u64) -> IVec {
/// IVec::from(number.to_be_bytes().to_vec())
/// }
///
/// let zero = u64_to_ivec(0);
/// let one = u64_to_ivec(1);
/// let two = u64_to_ivec(2);
/// let three = u64_to_ivec(3);
///
/// fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
/// let number = match old {
/// Some(bytes) => {
/// let array: [u8; 8] = bytes.try_into().unwrap();
/// let number = u64::from_be_bytes(array);
/// number + 1
/// }
/// None => 0,
/// };
///
/// Some(number.to_be_bytes().to_vec())
/// }
///
/// assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(zero)));
/// assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(one)));
/// assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(two)));
/// assert_eq!(db.update_and_fetch("counter", increment), Ok(Some(three)));
/// # Ok(()) }
/// ```
pub fn update_and_fetch<K, V, F>(
&self,
key: K,
mut f: F,
) -> Result<Option<IVec>>
where
K: AsRef<[u8]>,
F: FnMut(Option<&[u8]>) -> Option<V>,
V: Into<IVec>,
{
let key_ref = key.as_ref();
let mut current = self.get(key_ref)?;
loop {
let tmp = current.as_ref().map(AsRef::as_ref);
let next = f(tmp).map(Into::into);
match self.compare_and_swap::<_, _, IVec>(
key_ref,
tmp,
next.clone(),
)? {
Ok(()) => return Ok(next),
Err(CompareAndSwapError { current: cur, .. }) => {
current = cur;
}
}
}
}
/// Fetch the value, apply a function to it and return the previous value.
///
/// # Note
///
/// This may call the function multiple times if the value has been
/// changed from other threads in the meantime.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use sled::{Config, Error, IVec};
/// use std::convert::TryInto;
///
/// let config = Config::new().temporary(true);
/// let db = config.open()?;
///
/// fn u64_to_ivec(number: u64) -> IVec {
/// IVec::from(number.to_be_bytes().to_vec())
/// }
///
/// let zero = u64_to_ivec(0);
/// let one = u64_to_ivec(1);
/// let two = u64_to_ivec(2);
///
/// fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
/// let number = match old {
/// Some(bytes) => {
/// let array: [u8; 8] = bytes.try_into().unwrap();
/// let number = u64::from_be_bytes(array);
/// number + 1
/// }
/// None => 0,
/// };
///
/// Some(number.to_be_bytes().to_vec())
/// }
///
/// assert_eq!(db.fetch_and_update("counter", increment), Ok(None));
/// assert_eq!(db.fetch_and_update("counter", increment), Ok(Some(zero)));
/// assert_eq!(db.fetch_and_update("counter", increment), Ok(Some(one)));
/// assert_eq!(db.fetch_and_update("counter", increment), Ok(Some(two)));
/// # Ok(()) }
/// ```
pub fn fetch_and_update<K, V, F>(
&self,
key: K,
mut f: F,
) -> Result<Option<IVec>>
where
K: AsRef<[u8]>,
F: FnMut(Option<&[u8]>) -> Option<V>,
V: Into<IVec>,
{
let key_ref = key.as_ref();
let mut current = self.get(key_ref)?;
loop {
let tmp = current.as_ref().map(AsRef::as_ref);
let next = f(tmp);
match self.compare_and_swap(key_ref, tmp, next)? {
Ok(()) => return Ok(current),
Err(CompareAndSwapError { current: cur, .. }) => {
current = cur;
}
}
}
}
/// Subscribe to `Event`s that happen to keys that have
/// the specified prefix. Events for particular keys are
/// guaranteed to be witnessed in the same order by all
/// threads, but threads may witness different interleavings
/// of `Event`s across different keys. If subscribers don't
/// keep up with new writes, they will cause new writes
/// to block. There is a buffer of 1024 items per
/// `Subscriber`. This can be used to build reactive
/// and replicated systems.
///
/// `Subscriber` implements both `Iterator<Item = Event>`
/// and `Future<Output=Option<Event>>`
///
/// # Examples
///
/// Synchronous, blocking subscriber:
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// // watch all events by subscribing to the empty prefix
/// let mut subscriber = db.watch_prefix(vec![]);
///
/// let tree_2 = db.clone();
/// let thread = std::thread::spawn(move || {
/// db.insert(vec![0], vec![1])
/// });
///
/// // `Subscription` implements `Iterator<Item=Event>`
/// for event in subscriber.take(1) {
/// // Events occur due to single key operations,
/// // batches, or transactions. The tree is included
/// // so that you may perform a new transaction or
/// // operation in response to the event.
/// for (tree, key, value_opt) in &event {
/// if let Some(value) = value_opt {
/// // key `key` was set to value `value`
/// } else {
/// // key `key` was removed
/// }
/// }
/// }
///
/// # thread.join().unwrap();
/// # Ok(()) }
/// ```
/// Asynchronous, non-blocking subscriber:
///
/// `Subscription` implements `Future<Output=Option<Event>>`.
///
/// ```
/// # async fn foo() {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open().unwrap();
/// # let mut subscriber = db.watch_prefix(vec![]);
/// while let Some(event) = (&mut subscriber).await {
/// /* use it */
/// }
/// # }
/// ```
pub fn watch_prefix<P: AsRef<[u8]>>(&self, prefix: P) -> Subscriber {
self.subscribers.register(prefix.as_ref())
}
/// Synchronously flushes all dirty IO buffers and calls
/// fsync. If this succeeds, it is guaranteed that all
/// previous writes will be recovered if the system
/// crashes. Returns the number of bytes flushed during
/// this call.
///
/// Flushing can take quite a lot of time, and you should
/// measure the performance impact of using it on
/// realistic sustained workloads running on realistic
/// hardware.
///
/// This is called automatically on drop.
pub fn flush(&self) -> Result<usize> {
self.context.pagecache.flush()
}
/// Asynchronously flushes all dirty IO buffers
/// and calls fsync. If this succeeds, it is
/// guaranteed that all previous writes will
/// be recovered if the system crashes. Returns
/// the number of bytes flushed during this call.
///
/// Flushing can take quite a lot of time, and you
/// should measure the performance impact of
/// using it on realistic sustained workloads
/// running on realistic hardware.
// this clippy check is miss-firing on async code.
#[allow(clippy::used_underscore_binding)]
#[allow(clippy::shadow_same)]
pub async fn flush_async(&self) -> Result<usize> {
let pagecache = self.context.pagecache.clone();
if let Some(result) = threadpool::spawn(move || pagecache.flush()).await
{
result
} else {
Err(Error::ReportableBug(
"threadpool failed to complete \
action before shutdown"
))
}
}
/// Returns `true` if the `Tree` contains a value for
/// the specified key.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// db.insert(&[0], vec![0])?;
/// assert!(db.contains_key(&[0])?);
/// assert!(!db.contains_key(&[1])?);
/// # Ok(()) }
/// ```
pub fn contains_key<K: AsRef<[u8]>>(&self, key: K) -> Result<bool> {
self.get(key).map(|v| v.is_some())
}
/// Retrieve the key and value before the provided key,
/// if one exists.
///
/// # Note
/// The order follows the Ord implementation for `Vec<u8>`:
///
/// `[] < [0] < [255] < [255, 0] < [255, 255] ...`
///
/// To retain the ordering of numerical types use big endian representation
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use sled::IVec;
/// # let config = sled::Config::new().temporary(true);
/// # let db = config.open()?;
/// for i in 0..10 {
/// db.insert(&[i], vec![i])
/// .expect("should write successfully");
/// }
///
/// assert_eq!(db.get_lt(&[]), Ok(None));
/// assert_eq!(db.get_lt(&[0]), Ok(None));
/// assert_eq!(
/// db.get_lt(&[1]),
/// Ok(Some((IVec::from(&[0]), IVec::from(&[0]))))