-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathbase_cache.rs
3487 lines (3136 loc) · 116 KB
/
base_cache.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
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 super::{
housekeeper::{Housekeeper, InnerSync},
invalidator::{GetOrRemoveEntry, Invalidator, KeyDateLite, PredicateFun},
key_lock::{KeyLock, KeyLockMap},
notifier::RemovalNotifier,
InterruptedOp, PredicateId,
};
use crate::{
common::{
self,
concurrent::{
atomic_time::AtomicInstant,
constants::{
READ_LOG_FLUSH_POINT, READ_LOG_SIZE, WRITE_LOG_FLUSH_POINT, WRITE_LOG_SIZE,
},
deques::Deques,
entry_info::EntryInfo,
AccessTime, KeyHash, KeyHashDate, KvEntry, OldEntryInfo, ReadOp, ValueEntry, Weigher,
WriteOp,
},
deque::{DeqNode, Deque},
frequency_sketch::FrequencySketch,
time::{CheckedTimeOps, Clock, Instant},
timer_wheel::{ReschedulingResult, TimerWheel},
CacheRegion,
},
future::CancelGuard,
notification::{AsyncEvictionListener, RemovalCause},
policy::ExpirationPolicy,
sync_base::iter::ScanningGet,
Entry, Expiry, Policy, PredicateError,
};
#[cfg(feature = "unstable-debug-counters")]
use common::concurrent::debug_counters::CacheDebugStats;
use async_lock::{Mutex, MutexGuard, RwLock};
use async_trait::async_trait;
use crossbeam_channel::{Receiver, Sender, TrySendError};
use crossbeam_utils::atomic::AtomicCell;
use futures_util::future::BoxFuture;
use parking_lot::RwLock as SyncRwLock;
use smallvec::SmallVec;
use std::{
borrow::Borrow,
collections::hash_map::RandomState,
hash::{BuildHasher, Hash, Hasher},
sync::{
atomic::{AtomicBool, AtomicU8, Ordering},
Arc,
},
time::{Duration, Instant as StdInstant},
};
use triomphe::Arc as TrioArc;
pub(crate) type HouseKeeperArc = Arc<Housekeeper>;
pub(crate) struct BaseCache<K, V, S = RandomState> {
pub(crate) inner: Arc<Inner<K, V, S>>,
read_op_ch: Sender<ReadOp<K, V>>,
pub(crate) write_op_ch: Sender<WriteOp<K, V>>,
pub(crate) interrupted_op_ch_snd: Sender<InterruptedOp<K, V>>,
pub(crate) interrupted_op_ch_rcv: Receiver<InterruptedOp<K, V>>,
pub(crate) housekeeper: Option<HouseKeeperArc>,
}
impl<K, V, S> Clone for BaseCache<K, V, S> {
/// Makes a clone of this shared cache.
///
/// This operation is cheap as it only creates thread-safe reference counted
/// pointers to the shared internal data structures.
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
read_op_ch: self.read_op_ch.clone(),
write_op_ch: self.write_op_ch.clone(),
interrupted_op_ch_snd: self.interrupted_op_ch_snd.clone(),
interrupted_op_ch_rcv: self.interrupted_op_ch_rcv.clone(),
housekeeper: self.housekeeper.as_ref().map(Arc::clone),
}
}
}
impl<K, V, S> Drop for BaseCache<K, V, S> {
fn drop(&mut self) {
// The housekeeper needs to be dropped before the inner is dropped.
std::mem::drop(self.housekeeper.take());
}
}
impl<K, V, S> BaseCache<K, V, S> {
pub(crate) fn name(&self) -> Option<&str> {
self.inner.name()
}
pub(crate) fn policy(&self) -> Policy {
self.inner.policy()
}
pub(crate) fn entry_count(&self) -> u64 {
self.inner.entry_count()
}
pub(crate) fn weighted_size(&self) -> u64 {
self.inner.weighted_size()
}
pub(crate) fn is_map_disabled(&self) -> bool {
self.inner.max_capacity == Some(0)
}
#[inline]
pub(crate) fn is_removal_notifier_enabled(&self) -> bool {
self.inner.is_removal_notifier_enabled()
}
#[inline]
pub(crate) fn current_time_from_expiration_clock(&self) -> Instant {
self.inner.current_time_from_expiration_clock()
}
#[inline]
pub(crate) fn maintenance_task_lock(&self) -> &RwLock<()> {
&self.inner.maintenance_task_lock
}
pub(crate) fn notify_invalidate(
&self,
key: &Arc<K>,
entry: &TrioArc<ValueEntry<K, V>>,
) -> BoxFuture<'static, ()>
where
K: Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
{
self.inner.notify_invalidate(key, entry)
}
#[cfg(feature = "unstable-debug-counters")]
pub async fn debug_stats(&self) -> CacheDebugStats {
self.inner.debug_stats().await
}
}
impl<K, V, S> BaseCache<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
pub(crate) fn maybe_key_lock(&self, key: &Arc<K>) -> Option<KeyLock<'_, K, S>> {
self.inner.maybe_key_lock(key)
}
}
impl<K, V, S> BaseCache<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
// https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
name: Option<String>,
max_capacity: Option<u64>,
initial_capacity: Option<usize>,
build_hasher: S,
weigher: Option<Weigher<K, V>>,
eviction_listener: Option<AsyncEvictionListener<K, V>>,
expiration_policy: ExpirationPolicy<K, V>,
invalidator_enabled: bool,
) -> Self {
let (r_size, w_size) = if max_capacity == Some(0) {
(0, 0)
} else {
(READ_LOG_SIZE, WRITE_LOG_SIZE)
};
let (r_snd, r_rcv) = crossbeam_channel::bounded(r_size);
let (w_snd, w_rcv) = crossbeam_channel::bounded(w_size);
let (i_snd, i_rcv) = crossbeam_channel::unbounded();
let inner = Arc::new(Inner::new(
name,
max_capacity,
initial_capacity,
build_hasher,
weigher,
eviction_listener,
r_rcv,
w_rcv,
expiration_policy,
invalidator_enabled,
));
Self {
inner,
read_op_ch: r_snd,
write_op_ch: w_snd,
interrupted_op_ch_snd: i_snd,
interrupted_op_ch_rcv: i_rcv,
housekeeper: Some(Arc::new(Housekeeper::default())),
}
}
#[inline]
pub(crate) fn hash<Q>(&self, key: &Q) -> u64
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.inner.hash(key)
}
pub(crate) fn contains_key_with_hash<Q>(&self, key: &Q, hash: u64) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
// TODO: Maybe we can just call ScanningGet::scanning_get.
self.inner
.get_key_value_and(key, hash, |k, entry| {
let i = &self.inner;
let (ttl, tti, va) = (&i.time_to_live(), &i.time_to_idle(), &i.valid_after());
let now = self.current_time_from_expiration_clock();
!is_expired_by_per_entry_ttl(entry.entry_info(), now)
&& !is_expired_entry_wo(ttl, va, entry, now)
&& !is_expired_entry_ao(tti, va, entry, now)
&& !i.is_invalidated_entry(k, entry)
})
.unwrap_or_default() // `false` is the default for `bool` type.
}
pub(crate) async fn get_with_hash<Q, I>(
&self,
key: &Q,
hash: u64,
mut ignore_if: Option<&mut I>,
need_key: bool,
record_read: bool,
) -> Option<Entry<K, V>>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
I: FnMut(&V) -> bool,
{
if self.is_map_disabled() {
return None;
}
if record_read {
self.retry_interrupted_ops().await;
}
let mut now = self.current_time_from_expiration_clock();
let maybe_kv_and_op = self
.inner
.get_key_value_and_then(key, hash, move |k, entry| {
if let Some(ignore_if) = &mut ignore_if {
if ignore_if(&entry.value) {
// Ignore the entry.
return None;
}
}
let i = &self.inner;
let (ttl, tti, va) = (&i.time_to_live(), &i.time_to_idle(), &i.valid_after());
if is_expired_by_per_entry_ttl(entry.entry_info(), now)
|| is_expired_entry_wo(ttl, va, entry, now)
|| is_expired_entry_ao(tti, va, entry, now)
|| i.is_invalidated_entry(k, entry)
{
// Expired or invalidated entry.
None
} else {
// Valid entry.
let mut is_expiry_modified = false;
// Call the user supplied `expire_after_read` method if any.
if let Some(expiry) = &self.inner.expiration_policy.expiry() {
let lm = entry.last_modified().expect("Last modified is not set");
// Check if the `last_modified` of entry is earlier than or equals to
// `now`. If not, update the `now` to `last_modified`. This is needed
// because there is a small chance that other threads have inserted
// the entry _after_ we obtained `now`.
now = now.max(lm);
// Convert `last_modified` from `moka::common::time::Instant` to
// `std::time::Instant`.
let lm = self.inner.clocks().to_std_instant(lm);
// Call the user supplied `expire_after_read` method.
//
// We will put the return value (`is_expiry_modified: bool`) to a
// `ReadOp` so that `apply_reads` method can determine whether or not
// to reschedule the timer for the entry.
//
// NOTE: It is not guaranteed that the `ReadOp` is passed to
// `apply_reads`. Here are the corner cases that the `ReadOp` will
// not be passed to `apply_reads`:
//
// - If the bounded `read_op_ch` channel is full, the `ReadOp` will
// be discarded.
// - If we were called by `get_with_hash_without_recording` method,
// the `ReadOp` will not be recorded at all.
//
// These cases are okay because when the timer wheel tries to expire
// the entry, it will check if the entry is actually expired. If not,
// the timer wheel will reschedule the expiration timer for the
// entry.
is_expiry_modified = Self::expire_after_read_or_update(
|k, v, t, d| expiry.expire_after_read(k, v, t, d, lm),
&entry.entry_info().key_hash().key,
entry,
self.inner.expiration_policy.time_to_live(),
self.inner.expiration_policy.time_to_idle(),
now,
self.inner.clocks(),
);
}
let maybe_key = if need_key { Some(Arc::clone(k)) } else { None };
let ent = Entry::new(maybe_key, entry.value.clone(), false);
let maybe_op = if record_read {
Some(ReadOp::Hit {
value_entry: TrioArc::clone(entry),
timestamp: now,
is_expiry_modified,
})
} else {
None
};
Some((ent, maybe_op, now))
}
});
if let Some((ent, maybe_op, now)) = maybe_kv_and_op {
if let Some(op) = maybe_op {
self.record_read_op(op, now)
.await
.expect("Failed to record a get op");
}
Some(ent)
} else {
if record_read {
self.record_read_op(ReadOp::Miss(hash), now)
.await
.expect("Failed to record a get op");
}
None
}
}
pub(crate) fn get_key_with_hash<Q>(&self, key: &Q, hash: u64) -> Option<Arc<K>>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.inner
.get_key_value_and(key, hash, |k, _entry| Arc::clone(k))
}
#[inline]
pub(crate) fn remove_entry<Q>(&self, key: &Q, hash: u64) -> Option<KvEntry<K, V>>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.inner.remove_entry(key, hash)
}
#[inline]
pub(crate) async fn apply_reads_writes_if_needed(
inner: Arc<impl InnerSync + Send + Sync + 'static>,
ch: &Sender<WriteOp<K, V>>,
now: Instant,
housekeeper: Option<&HouseKeeperArc>,
) {
let w_len = ch.len();
if let Some(hk) = housekeeper {
if Self::should_apply_writes(hk, w_len, now) {
hk.try_run_pending_tasks(inner).await;
}
}
}
pub(crate) fn invalidate_all(&self) {
let now = self.current_time_from_expiration_clock();
self.inner.set_valid_after(now);
}
pub(crate) fn invalidate_entries_if(
&self,
predicate: PredicateFun<K, V>,
) -> Result<PredicateId, PredicateError> {
let now = self.current_time_from_expiration_clock();
self.inner.register_invalidation_predicate(predicate, now)
}
}
//
// Iterator support
//
impl<K, V, S> ScanningGet<K, V> for BaseCache<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
fn num_cht_segments(&self) -> usize {
self.inner.num_cht_segments()
}
fn scanning_get(&self, key: &Arc<K>) -> Option<V> {
let hash = self.hash(key);
self.inner.get_key_value_and_then(key, hash, |k, entry| {
let i = &self.inner;
let (ttl, tti, va) = (&i.time_to_live(), &i.time_to_idle(), &i.valid_after());
let now = self.current_time_from_expiration_clock();
if is_expired_by_per_entry_ttl(entry.entry_info(), now)
|| is_expired_entry_wo(ttl, va, entry, now)
|| is_expired_entry_ao(tti, va, entry, now)
|| i.is_invalidated_entry(k, entry)
{
// Expired or invalidated entry.
None
} else {
// Valid entry.
Some(entry.value.clone())
}
})
}
fn keys(&self, cht_segment: usize) -> Option<Vec<Arc<K>>> {
self.inner.keys(cht_segment)
}
}
//
// private methods
//
impl<K, V, S> BaseCache<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
#[inline]
async fn record_read_op(
&self,
op: ReadOp<K, V>,
now: Instant,
) -> Result<(), TrySendError<ReadOp<K, V>>> {
self.apply_reads_if_needed(Arc::clone(&self.inner), now)
.await;
let ch = &self.read_op_ch;
match ch.try_send(op) {
// Discard the ReadOp when the channel is full.
Ok(()) | Err(TrySendError::Full(_)) => Ok(()),
Err(e @ TrySendError::Disconnected(_)) => Err(e),
}
}
#[inline]
pub(crate) async fn do_insert_with_hash(
&self,
key: Arc<K>,
hash: u64,
value: V,
) -> (WriteOp<K, V>, Instant) {
self.retry_interrupted_ops().await;
let weight = self.inner.weigh(&key, &value);
let op_cnt1 = Arc::new(AtomicU8::new(0));
let op_cnt2 = Arc::clone(&op_cnt1);
let mut op1 = None;
let mut op2 = None;
// Lock the key for update if blocking removal notification is enabled.
let kl = self.maybe_key_lock(&key);
let _klg = if let Some(lock) = &kl {
Some(lock.lock().await)
} else {
None
};
let ts = self.current_time_from_expiration_clock();
// TODO: Instead using Arc<AtomicU8> to check if the actual operation was
// insert or update, check the return value of insert_with_or_modify. If it
// is_some, the value was updated, otherwise the value was inserted.
// Since the cache (cht::SegmentedHashMap) employs optimistic locking
// strategy, insert_with_or_modify() may get an insert/modify operation
// conflicted with other concurrent hash table operations. In that case, it
// has to retry the insertion or modification, so on_insert and/or on_modify
// closures can be executed more than once. In order to identify the last
// call of these closures, we use a shared counter (op_cnt{1,2}) here to
// record a serial number on a WriteOp, and consider the WriteOp with the
// largest serial number is the one made by the last call of the closures.
self.inner.cache.insert_with_or_modify(
Arc::clone(&key),
hash,
// on_insert
|| {
let entry = self.new_value_entry(&key, hash, value.clone(), ts, weight);
let ins_op = WriteOp::Upsert {
key_hash: KeyHash::new(Arc::clone(&key), hash),
value_entry: TrioArc::clone(&entry),
old_weight: 0,
new_weight: weight,
};
let cnt = op_cnt1.fetch_add(1, Ordering::Relaxed);
op1 = Some((cnt, ins_op));
entry
},
// on_modify
|_k, old_entry| {
let old_weight = old_entry.policy_weight();
// Create this OldEntryInfo _before_ creating a new ValueEntry, so
// that the OldEntryInfo can preserve the old EntryInfo's
// last_accessed and last_modified timestamps.
let old_info = OldEntryInfo::new(old_entry);
let entry = self.new_value_entry_from(value.clone(), ts, weight, old_entry);
let upd_op = WriteOp::Upsert {
key_hash: KeyHash::new(Arc::clone(&key), hash),
value_entry: TrioArc::clone(&entry),
old_weight,
new_weight: weight,
};
let cnt = op_cnt2.fetch_add(1, Ordering::Relaxed);
op2 = Some((cnt, old_info, upd_op));
entry
},
);
match (op1, op2) {
(Some((_cnt, ins_op)), None) => self.do_post_insert_steps(ts, &key, ins_op),
(Some((cnt1, ins_op)), Some((cnt2, ..))) if cnt1 > cnt2 => {
self.do_post_insert_steps(ts, &key, ins_op)
}
(_, Some((_cnt, old_entry, upd_op))) => {
self.do_post_update_steps(ts, key, old_entry, upd_op, &self.interrupted_op_ch_snd)
.await
}
(None, None) => unreachable!(),
}
}
fn do_post_insert_steps(
&self,
ts: Instant,
key: &Arc<K>,
ins_op: WriteOp<K, V>,
) -> (WriteOp<K, V>, Instant) {
if let (Some(expiry), WriteOp::Upsert { value_entry, .. }) =
(&self.inner.expiration_policy.expiry(), &ins_op)
{
Self::expire_after_create(expiry, key, value_entry, ts, self.inner.clocks());
}
(ins_op, ts)
}
async fn do_post_update_steps<'a>(
&self,
ts: Instant,
key: Arc<K>,
old_info: OldEntryInfo<K, V>,
upd_op: WriteOp<K, V>,
interrupted_op_ch: &'a Sender<InterruptedOp<K, V>>,
) -> (WriteOp<K, V>, Instant) {
use futures_util::FutureExt;
if let (Some(expiry), WriteOp::Upsert { value_entry, .. }) =
(&self.inner.expiration_policy.expiry(), &upd_op)
{
Self::expire_after_read_or_update(
|k, v, t, d| expiry.expire_after_update(k, v, t, d),
&key,
value_entry,
self.inner.expiration_policy.time_to_live(),
self.inner.expiration_policy.time_to_idle(),
ts,
self.inner.clocks(),
);
}
if self.is_removal_notifier_enabled() {
let future = self
.inner
.notify_upsert(
key,
&old_info.entry,
old_info.last_accessed,
old_info.last_modified,
)
.shared();
// Async Cancellation Safety: To ensure the above future should be
// executed even if our caller async task is cancelled, we create a
// cancel guard for the future (and the upd_op). If our caller is
// cancelled while we are awaiting for the future, the cancel guard will
// save the future and the upd_op to the interrupted_op_ch channel, so
// that we can resume/retry later.
let mut cancel_guard = CancelGuard::new(interrupted_op_ch, ts);
cancel_guard.set_future_and_op(future.clone(), upd_op.clone());
// Notify the eviction listener.
future.await;
cancel_guard.clear();
}
crossbeam_epoch::pin().flush();
(upd_op, ts)
}
#[inline]
pub(crate) async fn schedule_write_op(
inner: &Arc<impl InnerSync + Send + Sync + 'static>,
ch: &Sender<WriteOp<K, V>>,
maintenance_task_lock: &RwLock<()>,
op: WriteOp<K, V>,
ts: Instant,
housekeeper: Option<&HouseKeeperArc>,
// Used only for testing.
_should_block: bool,
) -> Result<(), TrySendError<WriteOp<K, V>>> {
// Testing stuff.
#[cfg(test)]
if _should_block {
// We are going to do a dead-lock here to simulate a full channel.
let mutex = Mutex::new(());
let _guard = mutex.lock().await;
// This should dead-lock.
mutex.lock().await;
}
let mut op = op;
let mut spin_loop_attempts = 0u8;
loop {
BaseCache::<K, V, S>::apply_reads_writes_if_needed(
Arc::clone(inner),
ch,
ts,
housekeeper,
)
.await;
match ch.try_send(op) {
Ok(()) => return Ok(()),
Err(TrySendError::Full(op1)) => {
op = op1;
}
Err(e @ TrySendError::Disconnected(_)) => return Err(e),
}
// We have got a `TrySendError::Full` above. Wait a moment and try again.
if spin_loop_attempts < 4 {
spin_loop_attempts += 1;
// Wastes some CPU time with a hint to indicate to the CPU that we
// are spinning. Adjust the SPIN_COUNT because the `PAUSE`
// instruction of recent x86_64 CPUs may have longer latency than the
// alternatives in other CPU architectures.
const SPIN_COUNT: usize = if cfg!(target_arch = "x86_64") { 8 } else { 32 };
for _ in 0..SPIN_COUNT {
std::hint::spin_loop();
}
} else {
// Wait for a shared reader lock to become available. The exclusive
// writer lock will be already held by another async task that is
// currently calling `do_run_pending_tasks` method via
// `apply_reads_writes_if_needed` method above.
//
// `do_run_pending_tasks` will receive some of the ops from the
// channel and apply them to the data structures for the cache
// policies, so the channel will have some room for the new ops.
//
// A shared lock will become available once the async task has
// returned from `do_run_pending_tasks`. We release the lock
// immediately after we acquire it.
let _ = maintenance_task_lock.read().await;
spin_loop_attempts = 0;
// We are going to retry. If the write op channel has enough room, we
// will be able to send our op to the channel and we are done. If
// not, we (or somebody else) will become the next exclusive writer
// when we (or somebody) call `apply_reads_writes_if_needed` above.
}
}
}
pub(crate) async fn retry_interrupted_ops(&self) {
while let Ok(op) = self.interrupted_op_ch_rcv.try_recv() {
// Async Cancellation Safety: Remember that we are in an async task here.
// If our caller is cancelled while we are awaiting for the future, we
// will be cancelled too at the await point. In that case, the cancel
// guard below will save the future and the op to the interrupted_op_ch
// channel, so that we can resume/retry later.
let mut cancel_guard;
// Resume an interrupted future if there is one.
match op {
InterruptedOp::CallEvictionListener { ts, future, op } => {
cancel_guard = CancelGuard::new(&self.interrupted_op_ch_snd, ts);
cancel_guard.set_future_and_op(future.clone(), op);
// Resume the interrupted future (which will notify an eviction
// to the eviction listener).
future.await;
// If we are here, it means the above future has been completed.
cancel_guard.unset_future();
}
InterruptedOp::SendWriteOp { ts, op } => {
cancel_guard = CancelGuard::new(&self.interrupted_op_ch_snd, ts);
cancel_guard.set_op(op);
}
}
// Retry to schedule the write op.
let ts = cancel_guard.ts;
let lock = self.maintenance_task_lock();
let op = cancel_guard.op.as_ref().cloned().unwrap();
let hk = self.housekeeper.as_ref();
Self::schedule_write_op(&self.inner, &self.write_op_ch, lock, op, ts, hk, false)
.await
.expect("Failed to reschedule a write op");
// If we are here, it means the above write op has been scheduled.
// We are all good now. Clear the cancel guard.
cancel_guard.clear();
}
}
#[inline]
async fn apply_reads_if_needed(&self, inner: Arc<Inner<K, V, S>>, now: Instant) {
let len = self.read_op_ch.len();
if let Some(hk) = &self.housekeeper {
if Self::should_apply_reads(hk, len, now) {
hk.try_run_pending_tasks(inner).await;
}
}
}
#[inline]
fn should_apply_reads(hk: &HouseKeeperArc, ch_len: usize, now: Instant) -> bool {
hk.should_apply_reads(ch_len, now)
}
#[inline]
fn should_apply_writes(hk: &HouseKeeperArc, ch_len: usize, now: Instant) -> bool {
hk.should_apply_writes(ch_len, now)
}
}
impl<K, V, S> BaseCache<K, V, S> {
#[inline]
fn new_value_entry(
&self,
key: &Arc<K>,
hash: u64,
value: V,
timestamp: Instant,
policy_weight: u32,
) -> TrioArc<ValueEntry<K, V>> {
let key_hash = KeyHash::new(Arc::clone(key), hash);
let info = TrioArc::new(EntryInfo::new(key_hash, timestamp, policy_weight));
TrioArc::new(ValueEntry::new(value, info))
}
#[inline]
fn new_value_entry_from(
&self,
value: V,
timestamp: Instant,
policy_weight: u32,
other: &ValueEntry<K, V>,
) -> TrioArc<ValueEntry<K, V>> {
let info = TrioArc::clone(other.entry_info());
// To prevent this updated ValueEntry from being evicted by an expiration policy,
// set the dirty flag to true. It will be reset to false when the write is applied.
info.set_dirty(true);
info.set_last_accessed(timestamp);
info.set_last_modified(timestamp);
info.set_policy_weight(policy_weight);
TrioArc::new(ValueEntry::new_from(value, info, other))
}
fn expire_after_create(
expiry: &Arc<dyn Expiry<K, V> + Send + Sync + 'static>,
key: &K,
value_entry: &ValueEntry<K, V>,
ts: Instant,
clocks: &Clocks,
) {
let duration =
expiry.expire_after_create(key, &value_entry.value, clocks.to_std_instant(ts));
let expiration_time = duration.map(|duration| ts.checked_add(duration).expect("Overflow"));
value_entry
.entry_info()
.set_expiration_time(expiration_time);
}
fn expire_after_read_or_update(
expiry: impl FnOnce(&K, &V, StdInstant, Option<Duration>) -> Option<Duration>,
key: &K,
value_entry: &ValueEntry<K, V>,
ttl: Option<Duration>,
tti: Option<Duration>,
ts: Instant,
clocks: &Clocks,
) -> bool {
let current_time = clocks.to_std_instant(ts);
let ei = &value_entry.entry_info();
let exp_time = IntoIterator::into_iter([
ei.expiration_time(),
ttl.and_then(|dur| ei.last_modified().and_then(|ts| ts.checked_add(dur))),
tti.and_then(|dur| ei.last_accessed().and_then(|ts| ts.checked_add(dur))),
])
.flatten()
.min();
let current_duration = exp_time.and_then(|time| {
let std_time = clocks.to_std_instant(time);
std_time.checked_duration_since(current_time)
});
let duration = expiry(key, &value_entry.value, current_time, current_duration);
if duration != current_duration {
let expiration_time =
duration.map(|duration| ts.checked_add(duration).expect("Overflow"));
value_entry
.entry_info()
.set_expiration_time(expiration_time);
// The `expiration_time` has changed from `None` to `Some` or vice versa.
true
} else {
false
}
}
}
//
// for testing
//
#[cfg(test)]
impl<K, V, S> BaseCache<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
pub(crate) fn invalidation_predicate_count(&self) -> usize {
self.inner.invalidation_predicate_count()
}
pub(crate) async fn reconfigure_for_testing(&mut self) {
// Enable the frequency sketch.
self.inner.enable_frequency_sketch_for_testing().await;
// Disable auto clean up of pending tasks.
if let Some(hk) = &self.housekeeper {
hk.disable_auto_run();
}
}
pub(crate) async fn set_expiration_clock(&self, clock: Option<Clock>) {
self.inner.set_expiration_clock(clock).await;
if let Some(hk) = &self.housekeeper {
let now = self.current_time_from_expiration_clock();
hk.reset_run_after(now);
}
}
pub(crate) fn key_locks_map_is_empty(&self) -> bool {
self.inner.key_locks_map_is_empty()
}
}
struct EvictionState<'a, K, V> {
counters: EvictionCounters,
notifier: Option<&'a Arc<RemovalNotifier<K, V>>>,
}
impl<'a, K, V> EvictionState<'a, K, V> {
fn new(
entry_count: u64,
weighted_size: u64,
notifier: Option<&'a Arc<RemovalNotifier<K, V>>>,
) -> Self {
Self {
counters: EvictionCounters::new(entry_count, weighted_size),
notifier,
}
}
fn is_notifier_enabled(&self) -> bool {
self.notifier.is_some()
}
async fn add_removed_entry(
&mut self,
key: Arc<K>,
entry: &TrioArc<ValueEntry<K, V>>,
cause: RemovalCause,
) where
K: Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
{
debug_assert!(self.is_notifier_enabled());
if let Some(notifier) = self.notifier {
notifier.notify(key, entry.value.clone(), cause).await;
}
}
}
struct EvictionCounters {
entry_count: u64,
weighted_size: u64,
}
impl EvictionCounters {
#[inline]
fn new(entry_count: u64, weighted_size: u64) -> Self {
Self {
entry_count,
weighted_size,
}
}
#[inline]
fn saturating_add(&mut self, entry_count: u64, weight: u32) {
self.entry_count += entry_count;
let total = &mut self.weighted_size;
*total = total.saturating_add(weight as u64);
}
#[inline]
fn saturating_sub(&mut self, entry_count: u64, weight: u32) {
self.entry_count -= entry_count;
let total = &mut self.weighted_size;
*total = total.saturating_sub(weight as u64);
}
}
#[derive(Default)]
struct EntrySizeAndFrequency {
policy_weight: u64,
freq: u32,
}
impl EntrySizeAndFrequency {
fn new(policy_weight: u32) -> Self {
Self {
policy_weight: policy_weight as u64,
..Default::default()
}
}
fn add_policy_weight(&mut self, weight: u32) {
self.policy_weight += weight as u64;
}
fn add_frequency(&mut self, freq: &FrequencySketch, hash: u64) {
self.freq += freq.frequency(hash) as u32;
}
}
enum AdmissionResult<K> {
Admitted {
victim_keys: SmallVec<[KeyHash<K>; 8]>,
},
Rejected,
}
type CacheStore<K, V, S> = crate::cht::SegmentedHashMap<Arc<K>, TrioArc<ValueEntry<K, V>>, S>;
struct Clocks {
// Lock for this Clocks instance. Used when the `expiration_clock` is set.
_lock: Mutex<()>,
has_expiration_clock: AtomicBool,
expiration_clock: SyncRwLock<Option<Clock>>,
/// The time (`moka::common::time`) when this timer wheel was created.
origin: Instant,
/// The time (`StdInstant`) when this timer wheel was created.
origin_std: StdInstant,
/// Mutable version of `origin` and `origin_std`. Used when the
/// `expiration_clock` is set.
mutable_origin: SyncRwLock<Option<(Instant, StdInstant)>>,
}
impl Clocks {