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
//! A locker's resident state: its key index, its byte budget, and its staged
//! writes.
//!
//! # Why this is not simply fields on the locker
//!
//! Two things need to reach it without knowing the locker's value type:
//!
//! * the **coherence callback**, which folds another tab's news into the key
//! index (see [`crate::coherence`]);
//! * [`crate::Bank::flush_all`], which must commit every open locker's staged
//! writes and cannot be generic over each one's `T`.
//!
//! Everything here is therefore non-generic. It works in keys, payload bytes
//! and ops — the value type only matters at the two edges, where a caller
//! hands one in or takes one out.
use std::collections::BTreeSet;
use std::sync::{Arc, Mutex};
use crate::backend::api::Op;
use crate::error::{Error, Result};
use crate::watch::Event;
use super::inner::{Inner, Prior};
use super::lru::{self, Entry, LruState, Plan};
use super::policy::{Commit, Policy};
use super::transaction::TxMode;
/// One write waiting for a commit.
///
/// Payload bytes rather than a value: encoding happens when the write is
/// staged, on the caller's thread, so a flush is pure I/O and no user code can
/// run inside it.
#[derive(Debug, Clone)]
pub(crate) enum Pending {
Put { key: Vec<u8>, payload: Vec<u8> },
Delete { key: Vec<u8> },
Clear,
}
/// What one commit does to an evictable locker's accounting.
///
/// Empty, and free, for a `Precious` locker.
#[derive(Debug, Default)]
pub(crate) struct Budget {
updates: Vec<(Vec<u8>, Entry)>,
removals: Vec<Vec<u8>>,
cleared: bool,
pub(crate) plan: Plan,
/// Deferred tick bumps this commit carried, to forget once it lands.
pending: Vec<Vec<u8>>,
}
pub(crate) struct Resident {
pub(crate) inner: Arc<Inner>,
mode: TxMode,
/// The resident key index. `None` on an eager locker, which holds whole
/// values instead and keeps them itself.
index: Option<Mutex<BTreeSet<Vec<u8>>>>,
/// Byte-budget accounting, present only under [`Policy::Evictable`].
lru: Option<Mutex<LruState>>,
staged: Mutex<Vec<Pending>>,
/// Keys this handle has itself stored an **inline** record under, and has
/// not touched since in any way that could have made it chunked.
///
/// Purely a fast path for [`Resident::prior`], and deliberately only ever
/// *shrinks* on doubt: forgetting a key costs one read, wrongly keeping
/// one orphans chunks. `None` on a locker with no index, where absence
/// cannot be proven anyway.
known_inline: Option<Mutex<BTreeSet<Vec<u8>>>>,
/// Keys whose stored bytes would not decode.
///
/// Lives here, rather than on the locker handle, because every handle on
/// one name shares this state — see [`crate::Bank::locker`]. An eager
/// locker fills it at open and never adds to it; a lazy one adds a key as
/// a read discovers the damage.
corrupt: Mutex<BTreeSet<Vec<u8>>>,
/// Keys another tab wrote with a value this locker could not take on —
/// too large to ride inside a coherence message, or bytes it could not
/// decode — so the resident copy was dropped and [`crate::Event::Stale`]
/// raised. The record is still stored; only this tab's copy is gone.
///
/// Separate from `corrupt` because `corrupt_keys()` is public and means
/// *unreadable*, which these keys are not. Together they are
/// [`Resident::stored_but_unheld`].
dropped: Mutex<BTreeSet<Vec<u8>>>,
/// This name's registration with the cross-tab channel, which holds only
/// a `Weak` and so stops delivering the moment this is dropped.
///
/// One per *name*, not per handle: every handle folds another tab's news
/// into the same resident state, so a second registration would apply the
/// same news twice, and hanging it off one handle would silently stop the
/// others hearing anything the moment that handle was dropped.
#[cfg(target_arch = "wasm32")]
sink: Mutex<Option<crate::coherence::SinkHandle>>,
}
impl std::fmt::Debug for Resident {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Resident")
.field("locker", &self.inner.name)
.field("pending", &self.pending_len().unwrap_or(0))
.finish()
}
}
impl Resident {
pub(crate) fn new(
inner: Arc<Inner>,
mode: TxMode,
index: Option<BTreeSet<Vec<u8>>>,
lru: Option<LruState>,
) -> Self {
Self {
inner,
mode,
known_inline: index.as_ref().map(|_| Mutex::new(BTreeSet::new())),
index: index.map(Mutex::new),
lru: lru.map(Mutex::new),
staged: Mutex::new(Vec::new()),
corrupt: Mutex::new(BTreeSet::new()),
dropped: Mutex::new(BTreeSet::new()),
#[cfg(target_arch = "wasm32")]
sink: Mutex::new(None),
}
}
// ---- keys that are stored but not held -----------------------------
/// Note that `key`'s stored bytes did not decode.
pub(crate) fn note_corrupt(&self, key: &[u8]) {
if let Ok(mut guard) = self.corrupt.lock() {
guard.insert(key.to_vec());
}
}
/// Every key noted so far, in byte order.
/// Whether this key's stored bytes would not decode when the locker was
/// opened — so it is missing from the resident map while its record is
/// still very much on disk.
pub(crate) fn is_corrupt(&self, key: &[u8]) -> bool {
self.corrupt
.lock()
.map(|c| c.contains(key))
.unwrap_or(false)
}
pub(crate) fn corrupt_keys(&self) -> Vec<Vec<u8>> {
self.corrupt
.lock()
.map(|c| c.iter().cloned().collect())
.unwrap_or_default()
}
/// Note that `key` is stored but this locker is not holding its value.
///
/// The `corrupt` set answers that for bytes that would not decode at open
/// time; this one answers it for a key another tab wrote with a value this
/// tab cannot carry — too large to ride inside a coherence message, or
/// bytes it cannot decode — which [`crate::Event::Stale`] reports and the
/// sink drops from the resident map. The two are kept apart because
/// `corrupt_keys()` is public and means *unreadable*, and a stale key is
/// perfectly readable by the tab that wrote it.
pub(crate) fn note_dropped(&self, key: &[u8]) {
if let Ok(mut guard) = self.dropped.lock() {
guard.insert(key.to_vec());
}
}
/// Forget that, because this locker now knows what is under `key`.
pub(crate) fn forget_dropped(&self, key: &[u8]) {
if let Ok(mut guard) = self.dropped.lock() {
guard.remove(key);
}
}
/// Forget all of it, after something removed every record at once.
pub(crate) fn forget_all_dropped(&self) {
if let Ok(mut guard) = self.dropped.lock() {
guard.clear();
}
}
/// Whether a record is stored under `key` that this locker does not hold
/// the value of — unreadable bytes, or a value dropped as stale.
///
/// An eager locker treats this as *present*: the record is real, so a
/// delete has to reach storage and really is news to a watcher. Claiming
/// presence too eagerly costs a wasted backend op; claiming absence
/// wrongly leaves a record — and any chunks under it — behind for good.
pub(crate) fn stored_but_unheld(&self, key: &[u8]) -> bool {
if self.is_corrupt(key) {
return true;
}
self.dropped
.lock()
.map(|d| d.contains(key))
.unwrap_or(false)
}
/// Register this name with the cross-tab channel, once.
///
/// `make` is only called when nothing is registered yet, so a second
/// handle on the name does not build a sink it would have to throw away.
#[cfg(target_arch = "wasm32")]
pub(crate) fn join_coherence(&self, make: impl FnOnce() -> crate::coherence::SinkHandle) {
if !self.inner.shared.coherence.is_enabled() {
return;
}
let Ok(mut slot) = self.sink.lock() else {
return;
};
if slot.is_some() {
return;
}
let handle = make();
self.inner.shared.coherence.register(&handle);
*slot = Some(handle);
}
// ---- the key index -------------------------------------------------
pub(crate) fn read_index<R>(&self, f: impl FnOnce(&BTreeSet<Vec<u8>>) -> R) -> Option<R> {
let guard = self.index.as_ref()?.lock().ok()?;
Some(f(&guard))
}
pub(crate) fn touch_index(&self, f: impl FnOnce(&mut BTreeSet<Vec<u8>>)) {
if let Some(Ok(mut guard)) = self.index.as_ref().map(|i| i.lock()) {
f(&mut guard);
}
}
// ---- what is already stored under a key ----------------------------
/// What this handle can prove about the record currently under `key`.
///
/// Conservative by construction. It answers anything but
/// [`Prior::Unknown`] only when **all** of these hold:
///
/// * this locker keeps a key index at all (a lazy locker; an eager one
/// never writes chunks and has its own resident map);
/// * nothing is staged. A staged delete drops the key from the index while
/// the record is still stored, so a staged batch makes the index
/// over-claim *absence* — the one direction that loses data;
/// * this handle's index is authoritative — nobody this index will never
/// hear from can be writing the same stored data. Every handle on one
/// name shares this index, so that is about maintenance lockers and, on
/// the web, other tabs with coherence off: either could write a chunked
/// record this index has never heard of, whose chunks would then be
/// orphaned forever. See [`Inner::index_is_authoritative`].
///
/// `Inline` additionally requires that this handle wrote the record and
/// nothing has since invalidated that. See [`Resident::note_inline`].
pub(crate) fn prior(&self, key: &[u8]) -> Prior {
if self.pending_len().unwrap_or(usize::MAX) != 0 {
return Prior::Unknown;
}
if !self.inner.index_is_authoritative() {
return Prior::Unknown;
}
let Some(present) = self.read_index(|index| index.contains(key)) else {
return Prior::Unknown;
};
if !present {
return Prior::Absent;
}
match self.known_inline.as_ref().map(|k| k.lock()) {
Some(Ok(guard)) if guard.contains(key) => Prior::Inline,
_ => Prior::Unknown,
}
}
/// Record that `key` now holds an inline record (`true`) or that whatever
/// this handle knew about it is no longer trustworthy (`false`).
///
/// Call with `false` on every path that could have made the key chunked,
/// deleted it, or handed it to someone else.
pub(crate) fn note_inline(&self, key: &[u8], inline: bool) {
let Some(Ok(mut guard)) = self.known_inline.as_ref().map(|k| k.lock()) else {
return;
};
if inline {
guard.insert(key.to_vec());
} else {
guard.remove(key);
}
}
/// Forget every inline marker. The answer to anything wholesale — a
/// clear, a close, another tab clearing, a transaction — where tracking
/// each key individually would be more ways to be wrong.
pub(crate) fn forget_inline(&self) {
if let Some(Ok(mut guard)) = self.known_inline.as_ref().map(|k| k.lock()) {
guard.clear();
}
}
// ---- the byte budget -----------------------------------------------
fn lru_lock(&self) -> Option<std::sync::MutexGuard<'_, LruState>> {
self.lru.as_ref()?.lock().ok()
}
pub(crate) fn budget_used(&self) -> u64 {
self.lru_lock().map(|s| s.total()).unwrap_or(0)
}
/// Note that `key` was read. RAM only; the bump rides along with the next
/// commit, because a read must not write.
pub(crate) async fn note_read(&self, key: &[u8]) -> Result<()> {
if self.lru.is_none() {
return Ok(());
}
let tick = self
.inner
.shared
.ticks
.allocate(self.inner.backend.as_ref())
.await?;
if let Some(mut state) = self.lru_lock() {
state.touch(key, tick);
}
Ok(())
}
/// Everything one commit is about to do to the byte budget.
///
/// Computed before the commit, applied after it lands — so a commit that
/// fails leaves the accounting describing what is actually stored.
pub(crate) async fn budget_ops(
&self,
ops: &mut Vec<Op>,
updates: Vec<(Vec<u8>, u64)>,
removals: Vec<Vec<u8>>,
cleared: bool,
keep: &[Vec<u8>],
) -> Result<Budget> {
if self.lru.is_none() {
return Ok(Budget::default());
}
// Another tab's news may have named a key whose size this tab could
// not work out (see [`super::lazy::LazySink`]). Reload before planning
// rather than evicting against a total that is known to be wrong.
self.reload_lru_if_dirty().await?;
let tick = self
.inner
.shared
.ticks
.allocate(self.inner.backend.as_ref())
.await?;
let updates: Vec<(Vec<u8>, Entry)> = updates
.into_iter()
.map(|(key, bytes)| (key, Entry { tick, bytes }))
.collect();
// The lock is taken, used, and dropped before any await below. A
// `std` mutex held across an await would deadlock the moment two
// futures on one thread interleaved.
let (plan, pending, mut pending_ops) = {
let Some(state) = self.lru_lock() else {
return Ok(Budget::default());
};
let plan = state.plan(&updates, &removals, cleared, state.max_bytes, keep);
let skip: Vec<Vec<u8>> = updates.iter().map(|(k, _)| k.clone()).collect();
let (pending, pending_ops) = if cleared {
(Vec::new(), Vec::new())
} else {
state.pending_ops(self.inner.id, &skip)
};
(plan, pending, pending_ops)
};
let id = self.inner.id;
if cleared {
ops.push(lru::clear_op(id));
}
for (key, entry) in &updates {
ops.push(lru::put_op(id, key, *entry));
}
ops.append(&mut pending_ops);
for key in &removals {
ops.push(lru::delete_op(id, key));
}
for victim in &plan.victims {
ops.extend(self.inner.delete_value_ops(victim, Prior::Unknown).await?);
ops.push(lru::delete_op(id, victim));
}
ops.push(self.inner.shared.ticks.counter_op()?);
Ok(Budget {
updates,
removals,
cleared,
plan,
pending,
})
}
/// Apply the accounting, drop the evicted keys from the index, and say so.
pub(crate) fn apply_budget(&self, budget: &Budget) {
if let Some(mut state) = self.lru_lock() {
state.apply(
&budget.updates,
&budget.removals,
budget.cleared,
&budget.plan,
);
state.clear_pending(&budget.pending);
}
if !budget.plan.victims.is_empty() {
self.touch_index(|index| {
for victim in &budget.plan.victims {
index.remove(victim.as_slice());
}
});
for victim in &budget.plan.victims {
self.note_inline(victim, false);
}
}
for key in &budget.plan.victims {
self.inner.announce(Event::Evicted { key: key.clone() });
}
}
/// Shed least-recently-used keys until at most `bytes` remain accounted.
pub(crate) async fn evict_to(&self, bytes: u64) -> Result<usize> {
if self.lru.is_none() {
return Ok(0);
}
let _guard = self.inner.write_lock.lock().await;
let plan = {
let Some(state) = self.lru_lock() else {
return Ok(0);
};
state.plan(&[], &[], false, bytes, &[])
};
if plan.victims.is_empty() {
return Ok(0);
}
let mut ops = Vec::new();
for victim in &plan.victims {
ops.extend(self.inner.delete_value_ops(victim, Prior::Unknown).await?);
ops.push(lru::delete_op(self.inner.id, victim));
}
self.inner.commit(ops).await?;
let shed = plan.victims.len();
self.apply_budget(&Budget {
plan,
..Budget::default()
});
Ok(shed)
}
/// Reload the `lru::` prefix when a coherence callback could not account
/// for another tab's write. Cheap in the normal case: the flag is false.
async fn reload_lru_if_dirty(&self) -> Result<()> {
let (dirty, max_bytes) = match self.lru_lock() {
Some(state) => (state.is_dirty(), state.max_bytes),
None => return Ok(()),
};
if !dirty {
return Ok(());
}
let loaded = lru::load(
self.inner.backend.as_ref(),
self.inner.id,
max_bytes,
&self.inner.shared.ticks,
)
.await?;
if let Some(mut state) = self.lru_lock() {
state.adopt_loaded(loaded);
}
Ok(())
}
/// Fold another tab's news into the byte budget.
///
/// Synchronous by necessity — a coherence callback must never await — so
/// a size it cannot determine marks the accounting dirty instead of
/// guessing. See [`LruState::remote_put`].
pub(crate) fn remote_budget(&self, key: &[u8], bytes: Option<u64>, deleted: bool) {
let Some(mut state) = self.lru_lock() else {
return;
};
if deleted {
state.remote_delete(key);
} else {
state.remote_put(key, bytes);
}
}
/// Fold another tab's clear into the byte budget.
pub(crate) fn remote_budget_clear(&self) {
if let Some(mut state) = self.lru_lock() {
state.remote_clear();
}
}
// ---- staged writes -------------------------------------------------
/// How many writes must pile up before this locker commits by itself, or
/// `None` when every write commits immediately.
fn deferred_after(&self) -> Option<usize> {
match self.inner.config.commit {
Commit::Immediate => None,
// 0 and 1 both mean "commit on the next write", which is
// `Immediate` with extra steps — so treat them as it.
Commit::Deferred { after } if after <= 1 => None,
Commit::Deferred { after } => Some(after),
}
}
pub(crate) fn is_deferred(&self) -> bool {
self.deferred_after().is_some()
}
/// How many writes are staged.
///
/// `Err` on a poisoned lock rather than 0: reporting "nothing staged"
/// there would turn [`Resident::flush`] into a silent no-op and lose the
/// only copy of the batch.
pub(crate) fn pending_len(&self) -> Result<usize> {
self.staged
.lock()
.map(|s| s.len())
.map_err(|_| Error::backend("staged write lock was poisoned"))
}
pub(crate) fn pending_bytes(&self) -> Result<u64> {
self.staged
.lock()
.map(|s| {
s.iter()
.map(|p| match p {
Pending::Put { payload, .. } => payload.len() as u64,
Pending::Delete { .. } | Pending::Clear => 0,
})
.sum()
})
.map_err(|_| Error::backend("staged write lock was poisoned"))
}
/// Queue a write. Returns whether the batch is now full.
pub(crate) fn stage(&self, entry: Pending) -> Result<bool> {
let after = self.deferred_after().unwrap_or(usize::MAX);
let mut guard = self
.staged
.lock()
.map_err(|_| Error::backend("staged write lock was poisoned"))?;
guard.push(entry);
Ok(guard.len() >= after)
}
/// The staged payload for a key: `None` when nothing staged has touched
/// it, `Some(None)` when the last thing staged removed it.
pub(crate) fn staged_view(&self, key: &[u8]) -> Result<Option<Option<Vec<u8>>>> {
let guard = self
.staged
.lock()
.map_err(|_| Error::backend("staged write lock was poisoned"))?;
for entry in guard.iter().rev() {
match entry {
Pending::Put { key: k, payload } if k == key => {
return Ok(Some(Some(payload.clone())))
}
Pending::Delete { key: k } if k == key => return Ok(Some(None)),
Pending::Clear => return Ok(Some(None)),
_ => {}
}
}
Ok(None)
}
/// A copy of everything staged, oldest first.
///
/// Used by the listing paths, which walk storage and must then overlay
/// what this handle has staged but not committed.
pub(crate) fn staged_snapshot(&self) -> Result<Vec<Pending>> {
let guard = self
.staged
.lock()
.map_err(|_| Error::backend("staged write lock was poisoned"))?;
Ok(guard.clone())
}
/// Commit everything staged, taking the locker's write lock.
pub(crate) async fn flush(&self) -> Result<()> {
if self.pending_len()? == 0 {
return Ok(());
}
let _guard = self.inner.write_lock.lock().await;
self.flush_locked().await
}
/// As [`Resident::flush`], for a caller that already holds the write lock.
pub(crate) async fn flush_locked(&self) -> Result<()> {
let entries = self.take_staged()?;
if entries.is_empty() {
return Ok(());
}
let mut ops =
match super::transaction::ops_for_pending(&self.inner, &entries, self.mode).await {
Ok(ops) => ops,
Err(e) => {
// Put the batch back rather than dropping it on the floor: a
// flush that failed has not written anything, and the caller
// may well fix the cause and try again.
self.restage(entries);
return Err(e);
}
};
let (updates, removals, cleared) = accounting(&entries);
// The batch's own keys are `keep`: a commit must never evict a key it
// is writing in that same commit, which would GC the new chunks and
// leave the record pointing at nothing.
let keep: Vec<Vec<u8>> = updates.iter().map(|(k, _)| k.clone()).collect();
let budget = match self
.budget_ops(&mut ops, updates, removals, cleared, &keep)
.await
{
Ok(budget) => budget,
Err(e) => {
self.restage(entries);
return Err(e);
}
};
if let Err(e) = self.inner.commit(ops).await {
self.restage(entries);
return Err(e);
}
self.apply_budget(&budget);
Ok(())
}
/// Drain the staged batch. The caller owns it and must restage it if the
/// commit it was drained for does not land.
pub(crate) fn take_staged(&self) -> Result<Vec<Pending>> {
let mut guard = self
.staged
.lock()
.map_err(|_| Error::backend("staged write lock was poisoned"))?;
Ok(std::mem::take(&mut *guard))
}
/// Put a drained batch back at the front, ahead of anything staged since.
pub(crate) fn restage(&self, mut entries: Vec<Pending>) {
if let Ok(mut guard) = self.staged.lock() {
entries.append(&mut guard);
*guard = entries;
}
}
/// Drop everything staged. Used by `close`, after a flush has had its go.
pub(crate) fn discard_staged(&self) {
if let Ok(mut guard) = self.staged.lock() {
guard.clear();
}
}
}
/// Keys written with their payload sizes, keys removed, and whether the batch
/// began with a clear.
pub(crate) type Accounting = (Vec<(Vec<u8>, u64)>, Vec<Vec<u8>>, bool);
/// What a batch of staged writes does to the byte budget, collapsed.
pub(crate) fn accounting(entries: &[Pending]) -> Accounting {
let mut updates: Vec<(Vec<u8>, u64)> = Vec::new();
let mut removals: Vec<Vec<u8>> = Vec::new();
let mut cleared = false;
for entry in entries {
match entry {
Pending::Put { key, payload } => {
updates.retain(|(k, _)| k != key);
removals.retain(|k| k != key);
updates.push((key.clone(), payload.len() as u64));
}
Pending::Delete { key } => {
updates.retain(|(k, _)| k != key);
removals.push(key.clone());
}
Pending::Clear => {
updates.clear();
removals.clear();
cleared = true;
}
}
}
(updates, removals, cleared)
}
/// Build the LRU state a locker opens with, or `None` where it has no budget.
pub(crate) async fn open_lru(inner: &Inner, index: &BTreeSet<Vec<u8>>) -> Result<Option<LruState>> {
let Policy::Evictable { max_bytes } = inner.config.policy else {
return Ok(None);
};
let mut state = lru::load(
inner.backend.as_ref(),
inner.id,
max_bytes,
&inner.shared.ticks,
)
.await?;
// Reconcile with what storage actually holds. A locker first written as
// `Precious` and reopened as `Evictable` has keys with no accounting, and
// a crash between two commits could leave accounting with no key.
state.retain_keys(|k| index.contains(k));
for key in index {
state.adopt(key.clone());
}
Ok(Some(state))
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(target_arch = "wasm32"))]
fn resident() -> Resident {
let inner = Arc::new(Inner {
write_lock: futures::lock::Mutex::new(()),
backend: Arc::new(crate::backend::MemoryBackend::new()),
chain: Arc::new(crate::codec::default_chain()),
id: 1,
name: "test".into(),
config: super::super::policy::LockerConfig::default()
.with_commit(Commit::Deferred { after: 8 }),
shared: Default::default(),
watchers: Default::default(),
closed: std::sync::atomic::AtomicBool::new(false),
epochs: Default::default(),
name_shared: std::sync::atomic::AtomicBool::new(false),
});
Resident::new(inner, TxMode::Lazy, Some(BTreeSet::new()), None)
}
/// A poisoned staging lock must never read as "nothing staged".
///
/// It did, and `flush` returned `Ok(())` without writing anything: the
/// batch was still sitting in the buffer, the caller was told it had
/// landed, and the next `close` threw it away. Losing writes silently is
/// the one outcome a store may not have.
/// Native only: poisoning a lock needs a second thread to panic in, and
/// wasm32 has none.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_poisoned_staging_lock_fails_the_flush_rather_than_skipping_it() {
let res = Arc::new(resident());
res.stage(Pending::Put {
key: b"k".to_vec(),
payload: vec![1, 2, 3],
})
.expect("staged");
assert_eq!(res.pending_len().expect("healthy"), 1);
// Poison it exactly as a panicking writer would.
let poisoner = res.clone();
let _ = std::thread::spawn(move || {
let _guard = poisoner.staged.lock();
panic!("poison the staging lock");
})
.join();
assert!(
res.pending_len().is_err(),
"a poisoned lock must not answer 0"
);
let flushed = futures::executor::block_on(res.flush());
assert!(
matches!(flushed, Err(Error::Backend(_))),
"flush must report the poisoning, not silently do nothing: {flushed:?}"
);
}
#[test]
fn a_batch_of_one_is_not_deferral() {
// Both degenerate settings must read as `Immediate` rather than
// staging a write nobody will ever flush.
for after in [0usize, 1] {
let config = super::super::policy::LockerConfig::default()
.with_commit(Commit::Deferred { after });
assert!(matches!(config.commit, Commit::Deferred { .. }));
assert_eq!(
match config.commit {
Commit::Deferred { after } if after <= 1 => None,
Commit::Deferred { after } => Some(after),
Commit::Immediate => None,
},
None
);
}
}
#[test]
fn accounting_collapses_a_batch() {
let entries = vec![
Pending::Put {
key: b"a".to_vec(),
payload: vec![0; 10],
},
Pending::Put {
key: b"a".to_vec(),
payload: vec![0; 20],
},
Pending::Delete { key: b"b".to_vec() },
];
let (updates, removals, cleared) = accounting(&entries);
assert_eq!(updates, vec![(b"a".to_vec(), 20)]);
assert_eq!(removals, vec![b"b".to_vec()]);
assert!(!cleared);
}
#[test]
fn a_clear_wipes_the_batch_before_it() {
let entries = vec![
Pending::Put {
key: b"a".to_vec(),
payload: vec![0; 10],
},
Pending::Clear,
Pending::Put {
key: b"c".to_vec(),
payload: vec![0; 5],
},
];
let (updates, removals, cleared) = accounting(&entries);
assert!(cleared);
assert!(removals.is_empty());
assert_eq!(updates, vec![(b"c".to_vec(), 5)]);
}
}