-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathcache.rs
4014 lines (3625 loc) · 145 KB
/
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::{
value_initializer::{InitResult, ValueInitializer},
CacheBuilder, ConcurrentCacheExt, Iter, OwnedKeyEntrySelector, PredicateId,
RefKeyEntrySelector,
};
use crate::{
common::{
concurrent::{
constants::{MAX_SYNC_REPEATS, WRITE_RETRY_INTERVAL_MICROS},
housekeeper::{self, InnerSync},
Weigher, WriteOp,
},
time::Instant,
},
notification::{self, EvictionListener},
sync_base::base_cache::{BaseCache, HouseKeeperArc},
Entry, Policy, PredicateError,
};
#[cfg(feature = "unstable-debug-counters")]
use crate::common::concurrent::debug_counters::CacheDebugStats;
use crossbeam_channel::{Sender, TrySendError};
use std::{
borrow::Borrow,
collections::hash_map::RandomState,
fmt,
future::Future,
hash::{BuildHasher, Hash},
sync::Arc,
time::Duration,
};
/// A thread-safe, futures-aware concurrent in-memory cache.
///
/// `Cache` supports full concurrency of retrievals and a high expected concurrency
/// for updates. It can be accessed inside and outside of asynchronous contexts.
///
/// `Cache` utilizes a lock-free concurrent hash table as the central key-value
/// storage. `Cache` performs a best-effort bounding of the map using an entry
/// replacement algorithm to determine which entries to evict when the capacity is
/// exceeded.
///
/// To use this cache, enable a crate feature called "future".
///
/// # Table of Contents
///
/// - [Example: `insert`, `get` and `invalidate`](#example-insert-get-and-invalidate)
/// - [Avoiding to clone the value at `get`](#avoiding-to-clone-the-value-at-get)
/// - [Example: Size-based Eviction](#example-size-based-eviction)
/// - [Example: Time-based Expirations](#example-time-based-expirations)
/// - [Example: Eviction Listener](#example-eviction-listener)
/// - [You should avoid eviction listener to panic](#you-should-avoid-eviction-listener-to-panic)
/// - [Delivery Modes for Eviction Listener](#delivery-modes-for-eviction-listener)
/// - [Thread Safety](#thread-safety)
/// - [Sharing a cache across threads](#sharing-a-cache-across-threads)
/// - [Hashing Algorithm](#hashing-algorithm)
///
/// # Example: `insert`, `get` and `invalidate`
///
/// Cache entries are manually added using an insert method, and are stored in the
/// cache until either evicted or manually invalidated:
///
/// - Inside an async context (`async fn` or `async` block), use
/// [`insert`](#method.insert), [`get_with`](#method.get_with) or
/// [`invalidate`](#method.invalidate) methods for updating the cache and `await`
/// them.
/// - Outside any async context, use [`blocking`](#method.blocking) method to access
/// blocking version of [`insert`](./struct.BlockingOp.html#method.insert) or
/// [`invalidate`](struct.BlockingOp.html#method.invalidate) methods.
///
/// Here's an example of reading and updating a cache by using multiple asynchronous
/// tasks with [Tokio][tokio-crate] runtime:
///
/// [tokio-crate]: https://crates.io/crates/tokio
///
///```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.9", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
/// // futures-util = "0.3"
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// const NUM_TASKS: usize = 16;
/// const NUM_KEYS_PER_TASK: usize = 64;
///
/// fn value(n: usize) -> String {
/// format!("value {}", n)
/// }
///
/// // Create a cache that can store up to 10,000 entries.
/// let cache = Cache::new(10_000);
///
/// // Spawn async tasks and write to and read from the cache.
/// let tasks: Vec<_> = (0..NUM_TASKS)
/// .map(|i| {
/// // To share the same cache across the async tasks, clone it.
/// // This is a cheap operation.
/// let my_cache = cache.clone();
/// let start = i * NUM_KEYS_PER_TASK;
/// let end = (i + 1) * NUM_KEYS_PER_TASK;
///
/// tokio::spawn(async move {
/// // Insert 64 entries. (NUM_KEYS_PER_TASK = 64)
/// for key in start..end {
/// // insert() is an async method, so await it.
/// my_cache.insert(key, value(key)).await;
/// // get() returns Option<String>, a clone of the stored value.
/// assert_eq!(my_cache.get(&key), Some(value(key)));
/// }
///
/// // Invalidate every 4 element of the inserted entries.
/// for key in (start..end).step_by(4) {
/// // invalidate() is an async method, so await it.
/// my_cache.invalidate(&key).await;
/// }
/// })
/// })
/// .collect();
///
/// // Wait for all tasks to complete.
/// futures_util::future::join_all(tasks).await;
///
/// // Verify the result.
/// for key in 0..(NUM_TASKS * NUM_KEYS_PER_TASK) {
/// if key % 4 == 0 {
/// assert_eq!(cache.get(&key), None);
/// } else {
/// assert_eq!(cache.get(&key), Some(value(key)));
/// }
/// }
/// }
/// ```
///
/// If you want to atomically initialize and insert a value when the key is not
/// present, you might want to check other insertion methods
/// [`get_with`](#method.get_with) and [`try_get_with`](#method.try_get_with).
///
/// # Avoiding to clone the value at `get`
///
/// The return type of `get` method is `Option<V>` instead of `Option<&V>`. Every
/// time `get` is called for an existing key, it creates a clone of the stored value
/// `V` and returns it. This is because the `Cache` allows concurrent updates from
/// threads so a value stored in the cache can be dropped or replaced at any time by
/// any other thread. `get` cannot return a reference `&V` as it is impossible to
/// guarantee the value outlives the reference.
///
/// If you want to store values that will be expensive to clone, wrap them by
/// `std::sync::Arc` before storing in a cache. [`Arc`][rustdoc-std-arc] is a
/// thread-safe reference-counted pointer and its `clone()` method is cheap.
///
/// [rustdoc-std-arc]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
///
/// # Example: Size-based Eviction
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.9", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
/// // futures-util = "0.3"
///
/// use std::convert::TryInto;
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// // Evict based on the number of entries in the cache.
/// let cache = Cache::builder()
/// // Up to 10,000 entries.
/// .max_capacity(10_000)
/// // Create the cache.
/// .build();
/// cache.insert(1, "one".to_string()).await;
///
/// // Evict based on the byte length of strings in the cache.
/// let cache = Cache::builder()
/// // A weigher closure takes &K and &V and returns a u32
/// // representing the relative size of the entry.
/// .weigher(|_key, value: &String| -> u32 {
/// value.len().try_into().unwrap_or(u32::MAX)
/// })
/// // This cache will hold up to 32MiB of values.
/// .max_capacity(32 * 1024 * 1024)
/// .build();
/// cache.insert(2, "two".to_string()).await;
/// }
/// ```
///
/// If your cache should not grow beyond a certain size, use the `max_capacity`
/// method of the [`CacheBuilder`][builder-struct] to set the upper bound. The cache
/// will try to evict entries that have not been used recently or very often.
///
/// At the cache creation time, a weigher closure can be set by the `weigher` method
/// of the `CacheBuilder`. A weigher closure takes `&K` and `&V` as the arguments and
/// returns a `u32` representing the relative size of the entry:
///
/// - If the `weigher` is _not_ set, the cache will treat each entry has the same
/// size of `1`. This means the cache will be bounded by the number of entries.
/// - If the `weigher` is set, the cache will call the weigher to calculate the
/// weighted size (relative size) on an entry. This means the cache will be bounded
/// by the total weighted size of entries.
///
/// Note that weighted sizes are not used when making eviction selections.
///
/// [builder-struct]: ./struct.CacheBuilder.html
///
/// # Example: Time-based Expirations
///
/// `Cache` supports the following expiration policies:
///
/// - **Time to live**: A cached entry will be expired after the specified duration
/// past from `insert`.
/// - **Time to idle**: A cached entry will be expired after the specified duration
/// past from `get` or `insert`.
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.9", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
/// // futures-util = "0.3"
///
/// use moka::future::Cache;
/// use std::time::Duration;
///
/// #[tokio::main]
/// async fn main() {
/// let cache = Cache::builder()
/// // Time to live (TTL): 30 minutes
/// .time_to_live(Duration::from_secs(30 * 60))
/// // Time to idle (TTI): 5 minutes
/// .time_to_idle(Duration::from_secs( 5 * 60))
/// // Create the cache.
/// .build();
///
/// // This entry will expire after 5 minutes (TTI) if there is no get().
/// cache.insert(0, "zero").await;
///
/// // This get() will extend the entry life for another 5 minutes.
/// cache.get(&0);
///
/// // Even though we keep calling get(), the entry will expire
/// // after 30 minutes (TTL) from the insert().
/// }
/// ```
///
/// # Example: Eviction Listener
///
/// A `Cache` can be configured with an eviction listener, a closure that is called
/// every time there is a cache eviction. The listener takes three parameters: the
/// key and value of the evicted entry, and the
/// [`RemovalCause`](../notification/enum.RemovalCause.html) to indicate why the
/// entry was evicted.
///
/// An eviction listener can be used to keep other data structures in sync with the
/// cache, for example.
///
/// The following example demonstrates how to use an eviction listener with
/// time-to-live expiration to manage the lifecycle of temporary files on a
/// filesystem. The cache stores the paths of the files, and when one of them has
/// expired, the eviction lister will be called with the path, so it can remove the
/// file from the filesystem.
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // anyhow = "1.0"
/// // uuid = { version = "1.1", features = ["v4"] }
/// // tokio = { version = "1.18", features = ["fs", "macros", "rt-multi-thread", "sync", "time"] }
///
/// use moka::future::Cache;
///
/// use anyhow::{anyhow, Context};
/// use std::{
/// io,
/// path::{Path, PathBuf},
/// sync::Arc,
/// time::Duration,
/// };
/// use tokio::{fs, sync::RwLock};
/// use uuid::Uuid;
///
/// /// The DataFileManager writes, reads and removes data files.
/// struct DataFileManager {
/// base_dir: PathBuf,
/// file_count: usize,
/// }
///
/// impl DataFileManager {
/// fn new(base_dir: PathBuf) -> Self {
/// Self {
/// base_dir,
/// file_count: 0,
/// }
/// }
///
/// async fn write_data_file(&mut self, contents: String) -> io::Result<PathBuf> {
/// loop {
/// // Generate a unique file path.
/// let mut path = self.base_dir.to_path_buf();
/// path.push(Uuid::new_v4().as_hyphenated().to_string());
///
/// if path.exists() {
/// continue; // This path is already taken by others. Retry.
/// }
///
/// // We have got a unique file path, so create the file at
/// // the path and write the contents to the file.
/// fs::write(&path, contents).await?;
/// self.file_count += 1;
/// println!(
/// "Created a data file at {:?} (file count: {})",
/// path, self.file_count
/// );
///
/// // Return the path.
/// return Ok(path);
/// }
/// }
///
/// async fn read_data_file(&self, path: impl AsRef<Path>) -> io::Result<String> {
/// // Reads the contents of the file at the path, and return the contents.
/// fs::read_to_string(path).await
/// }
///
/// async fn remove_data_file(&mut self, path: impl AsRef<Path>) -> io::Result<()> {
/// // Remove the file at the path.
/// fs::remove_file(path.as_ref()).await?;
/// self.file_count -= 1;
/// println!(
/// "Removed a data file at {:?} (file count: {})",
/// path.as_ref(),
/// self.file_count
/// );
///
/// Ok(())
/// }
/// }
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
/// // Create an instance of the DataFileManager and wrap it with
/// // Arc<RwLock<_>> so it can be shared across threads.
/// let file_mgr = DataFileManager::new(std::env::temp_dir());
/// let file_mgr = Arc::new(RwLock::new(file_mgr));
///
/// let file_mgr1 = Arc::clone(&file_mgr);
/// let rt = tokio::runtime::Handle::current();
///
/// // Create an eviction lister closure.
/// let listener = move |k, v: PathBuf, cause| {
/// // Try to remove the data file at the path `v`.
/// println!(
/// "\n== An entry has been evicted. k: {:?}, v: {:?}, cause: {:?}",
/// k, v, cause
/// );
/// rt.block_on(async {
/// // Acquire the write lock of the DataFileManager.
/// let mut mgr = file_mgr1.write().await;
/// // Remove the data file. We must handle error cases here to
/// // prevent the listener from panicking.
/// if let Err(_e) = mgr.remove_data_file(v.as_path()).await {
/// eprintln!("Failed to remove a data file at {:?}", v);
/// }
/// });
/// };
///
/// // Create the cache. Set time to live for two seconds and set the
/// // eviction listener.
/// let cache = Cache::builder()
/// .max_capacity(100)
/// .time_to_live(Duration::from_secs(2))
/// .eviction_listener_with_queued_delivery_mode(listener)
/// .build();
///
/// // Insert an entry to the cache.
/// // This will create and write a data file for the key "user1", store the
/// // path of the file to the cache, and return it.
/// println!("== try_get_with()");
/// let path = cache
/// .try_get_with("user1", async {
/// let mut mgr = file_mgr.write().await;
/// let path = mgr
/// .write_data_file("user data".into())
/// .await
/// .with_context(|| format!("Failed to create a data file"))?;
/// Ok(path) as anyhow::Result<_>
/// })
/// .await
/// .map_err(|e| anyhow!("{}", e))?;
///
/// // Read the data file at the path and print the contents.
/// println!("\n== read_data_file()");
/// {
/// let mgr = file_mgr.read().await;
/// let contents = mgr
/// .read_data_file(path.as_path())
/// .await
/// .with_context(|| format!("Failed to read data from {:?}", path))?;
/// println!("contents: {}", contents);
/// }
///
/// // Sleep for five seconds. While sleeping, the cache entry for key "user1"
/// // will be expired and evicted, so the eviction lister will be called to
/// // remove the file.
/// tokio::time::sleep(Duration::from_secs(5)).await;
///
/// Ok(())
/// }
/// ```
///
/// ## You should avoid eviction listener to panic
///
/// It is very important to make an eviction listener closure not to panic.
/// Otherwise, the cache will stop calling the listener after a panic. This is an
/// intended behavior because the cache cannot know whether it is memory safe or not
/// to call the panicked lister again.
///
/// When a listener panics, the cache will swallow the panic and disable the
/// listener. If you want to know when a listener panics and the reason of the panic,
/// you can enable an optional `logging` feature of Moka and check error-level logs.
///
/// To enable the `logging`, do the followings:
///
/// 1. In `Cargo.toml`, add the crate feature `logging` for `moka`.
/// 2. Set the logging level for `moka` to `error` or any lower levels (`warn`,
/// `info`, ...):
/// - If you are using the `env_logger` crate, you can achieve this by setting
/// `RUST_LOG` environment variable to `moka=error`.
/// 3. If you have more than one caches, you may want to set a distinct name for each
/// cache by using cache builder's [`name`][builder-name-method] method. The name
/// will appear in the log.
///
/// [builder-name-method]: ./struct.CacheBuilder.html#method.name
///
/// ## Delivery Modes for Eviction Listener
///
/// The [`DeliveryMode`][delivery-mode] specifies how and when an eviction
/// notification should be delivered to an eviction listener. Currently, the
/// `future::Cache` supports only one delivery mode: `Queued` mode.
///
/// A future version of `future::Cache` will support `Immediate` mode, which will be
/// easier to use in many use cases than queued mode. Unlike the `future::Cache`,
/// the `sync::Cache` already supports it.
///
/// Once `future::Cache` supports the immediate mode, the `eviction_listener` and
/// `eviction_listener_with_conf` methods will be added to the
/// `future::CacheBuilder`. The former will use the immediate mode, and the latter
/// will take a custom configurations to specify the queued mode. The current method
/// `eviction_listener_with_queued_delivery_mode` will be deprecated.
///
/// For more details about the delivery modes, see [this section][sync-delivery-modes]
/// of `sync::Cache` documentation.
///
/// [delivery-mode]: ../notification/enum.DeliveryMode.html
/// [sync-delivery-modes]: ../sync/struct.Cache.html#delivery-modes-for-eviction-listener
///
/// # Thread Safety
///
/// All methods provided by the `Cache` are considered thread-safe, and can be safely
/// accessed by multiple concurrent threads.
///
/// - `Cache<K, V, S>` requires trait bounds `Send`, `Sync` and `'static` for `K`
/// (key), `V` (value) and `S` (hasher state).
/// - `Cache<K, V, S>` will implement `Send` and `Sync`.
///
/// # Sharing a cache across asynchronous tasks
///
/// To share a cache across async tasks (or OS threads), do one of the followings:
///
/// - Create a clone of the cache by calling its `clone` method and pass it to other
/// task.
/// - Wrap the cache by a `sync::OnceCell` or `sync::Lazy` from
/// [once_cell][once-cell-crate] create, and set it to a `static` variable.
///
/// Cloning is a cheap operation for `Cache` as it only creates thread-safe
/// reference-counted pointers to the internal data structures.
///
/// [once-cell-crate]: https://crates.io/crates/once_cell
///
/// # Hashing Algorithm
///
/// By default, `Cache` uses a hashing algorithm selected to provide resistance
/// against HashDoS attacks. It will be the same one used by
/// `std::collections::HashMap`, which is currently SipHash 1-3.
///
/// While SipHash's performance is very competitive for medium sized keys, other
/// hashing algorithms will outperform it for small keys such as integers as well as
/// large keys such as long strings. However those algorithms will typically not
/// protect against attacks such as HashDoS.
///
/// The hashing algorithm can be replaced on a per-`Cache` basis using the
/// [`build_with_hasher`][build-with-hasher-method] method of the `CacheBuilder`.
/// Many alternative algorithms are available on crates.io, such as the
/// [aHash][ahash-crate] crate.
///
/// [build-with-hasher-method]: ./struct.CacheBuilder.html#method.build_with_hasher
/// [ahash-crate]: https://crates.io/crates/ahash
///
pub struct Cache<K, V, S = RandomState> {
base: BaseCache<K, V, S>,
value_initializer: Arc<ValueInitializer<K, V, S>>,
}
// TODO: https://github.com/moka-rs/moka/issues/54
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<K, V, S> Send for Cache<K, V, S>
where
K: Send + Sync,
V: Send + Sync,
S: Send,
{
}
unsafe impl<K, V, S> Sync for Cache<K, V, S>
where
K: Send + Sync,
V: Send + Sync,
S: Sync,
{
}
// NOTE: We cannot do `#[derive(Clone)]` because it will add `Clone` bound to `K`.
impl<K, V, S> Clone for Cache<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 {
base: self.base.clone(),
value_initializer: Arc::clone(&self.value_initializer),
}
}
}
impl<K, V, S> fmt::Debug for Cache<K, V, S>
where
K: fmt::Debug + Eq + Hash + Send + Sync + 'static,
V: fmt::Debug + Clone + Send + Sync + 'static,
// TODO: Remove these bounds from S.
S: BuildHasher + Clone + Send + Sync + 'static,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d_map = f.debug_map();
for (k, v) in self.iter() {
d_map.entry(&k, &v);
}
d_map.finish()
}
}
impl<K, V, S> Cache<K, V, S> {
/// Returns cache’s name.
pub fn name(&self) -> Option<&str> {
self.base.name()
}
/// Returns a read-only cache policy of this cache.
///
/// At this time, cache policy cannot be modified after cache creation.
/// A future version may support to modify it.
pub fn policy(&self) -> Policy {
self.base.policy()
}
/// Returns an approximate number of entries in this cache.
///
/// The value returned is _an estimate_; the actual count may differ if there are
/// concurrent insertions or removals, or if some entries are pending removal due
/// to expiration. This inaccuracy can be mitigated by performing a `sync()`
/// first.
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.9", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache = Cache::new(10);
/// cache.insert('n', "Netherland Dwarf").await;
/// cache.insert('l', "Lop Eared").await;
/// cache.insert('d', "Dutch").await;
///
/// // Ensure an entry exists.
/// assert!(cache.contains_key(&'n'));
///
/// // However, followings may print stale number zeros instead of threes.
/// println!("{}", cache.entry_count()); // -> 0
/// println!("{}", cache.weighted_size()); // -> 0
///
/// // To mitigate the inaccuracy, bring `ConcurrentCacheExt` trait to
/// // the scope so we can use `sync` method.
/// use moka::future::ConcurrentCacheExt;
/// // Call `sync` to run pending internal tasks.
/// cache.sync();
///
/// // Followings will print the actual numbers.
/// println!("{}", cache.entry_count()); // -> 3
/// println!("{}", cache.weighted_size()); // -> 3
/// }
/// ```
///
pub fn entry_count(&self) -> u64 {
self.base.entry_count()
}
/// Returns an approximate total weighted size of entries in this cache.
///
/// The value returned is _an estimate_; the actual size may differ if there are
/// concurrent insertions or removals, or if some entries are pending removal due
/// to expiration. This inaccuracy can be mitigated by performing a `sync()`
/// first. See [`entry_count`](#method.entry_count) for a sample code.
pub fn weighted_size(&self) -> u64 {
self.base.weighted_size()
}
#[cfg(feature = "unstable-debug-counters")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-debug-counters")))]
pub fn debug_stats(&self) -> CacheDebugStats {
self.base.debug_stats()
}
}
impl<K, V> Cache<K, V, RandomState>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
{
/// Constructs a new `Cache<K, V>` that will store up to the `max_capacity`.
///
/// To adjust various configuration knobs such as `initial_capacity` or
/// `time_to_live`, use the [`CacheBuilder`][builder-struct].
///
/// [builder-struct]: ./struct.CacheBuilder.html
pub fn new(max_capacity: u64) -> Self {
let build_hasher = RandomState::default();
Self::with_everything(
None,
Some(max_capacity),
None,
build_hasher,
None,
None,
None,
None,
None,
false,
housekeeper::Configuration::new_thread_pool(true),
)
}
/// Returns a [`CacheBuilder`][builder-struct], which can builds a `Cache` with
/// various configuration knobs.
///
/// [builder-struct]: ./struct.CacheBuilder.html
pub fn builder() -> CacheBuilder<K, V, Cache<K, V, RandomState>> {
CacheBuilder::default()
}
}
impl<K, V, S> Cache<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 with_everything(
name: Option<String>,
max_capacity: Option<u64>,
initial_capacity: Option<usize>,
build_hasher: S,
weigher: Option<Weigher<K, V>>,
eviction_listener: Option<EvictionListener<K, V>>,
eviction_listener_conf: Option<notification::Configuration>,
time_to_live: Option<Duration>,
time_to_idle: Option<Duration>,
invalidator_enabled: bool,
housekeeper_conf: housekeeper::Configuration,
) -> Self {
Self {
base: BaseCache::new(
name,
max_capacity,
initial_capacity,
build_hasher.clone(),
weigher,
eviction_listener,
eviction_listener_conf,
time_to_live,
time_to_idle,
invalidator_enabled,
housekeeper_conf,
),
value_initializer: Arc::new(ValueInitializer::with_hasher(build_hasher)),
}
}
/// Returns `true` if the cache contains a value for the key.
///
/// Unlike the `get` method, this method is not considered a cache read operation,
/// so it does not update the historic popularity estimator or reset the idle
/// timer for the key.
///
/// The key may be any borrowed form of the cache's key type, but `Hash` and `Eq`
/// on the borrowed form _must_ match those for the key type.
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.base.contains_key_with_hash(key, self.base.hash(key))
}
/// Returns a _clone_ of the value corresponding to the key.
///
/// If you want to store values that will be expensive to clone, wrap them by
/// `std::sync::Arc` before storing in a cache. [`Arc`][rustdoc-std-arc] is a
/// thread-safe reference-counted pointer and its `clone()` method is cheap.
///
/// The key may be any borrowed form of the cache's key type, but `Hash` and `Eq`
/// on the borrowed form _must_ match those for the key type.
///
/// [rustdoc-std-arc]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
pub fn get<Q>(&self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.base
.get_with_hash(key, self.base.hash(key), false)
.map(Entry::into_value)
}
/// Takes a key `K` and returns an [`OwnedKeyEntrySelector`] that can be used to
/// select or insert an entry.
///
/// [`OwnedKeyEntrySelector`]: ./struct.OwnedKeyEntrySelector.html
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.10", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry(key.clone()).or_insert(3).await;
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let entry = cache.entry(key).or_insert(6).await;
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// }
/// ```
pub fn entry(&self, key: K) -> OwnedKeyEntrySelector<'_, K, V, S>
where
K: Hash + Eq,
{
let hash = self.base.hash(&key);
OwnedKeyEntrySelector::new(key, hash, self)
}
/// Takes a reference `&Q` of a key and returns an [`RefKeyEntrySelector`] that
/// can be used to select or insert an entry.
///
/// [`RefKeyEntrySelector`]: ./struct.RefKeyEntrySelector.html
///
/// # Example
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.10", features = ["future"] }
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
///
/// use moka::future::Cache;
///
/// #[tokio::main]
/// async fn main() {
/// let cache: Cache<String, u32> = Cache::new(100);
/// let key = "key1".to_string();
///
/// let entry = cache.entry_by_ref(&key).or_insert(3).await;
/// assert!(entry.is_fresh());
/// assert_eq!(entry.key(), &key);
/// assert_eq!(entry.into_value(), 3);
///
/// let entry = cache.entry_by_ref(&key).or_insert(6).await;
/// // Not fresh because the value was already in the cache.
/// assert!(!entry.is_fresh());
/// assert_eq!(entry.into_value(), 3);
/// }
/// ```
pub fn entry_by_ref<'a, Q>(&'a self, key: &'a Q) -> RefKeyEntrySelector<'a, K, Q, V, S>
where
K: Borrow<Q>,
Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
{
let hash = self.base.hash(key);
RefKeyEntrySelector::new(key, hash, self)
}
/// Returns a _clone_ of the value corresponding to the key. If the value does
/// not exist, resolve the `init` future and inserts the output.
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing key are
/// coalesced into one evaluation of the `init` future. Only one of the calls
/// evaluates its future, and other calls wait for that future to resolve.
///
/// The following code snippet demonstrates this behavior:
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.9", features = ["future"] }
/// // futures-util = "0.3"
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
/// use moka::future::Cache;
/// use std::sync::Arc;
///
/// #[tokio::main]
/// async fn main() {
/// const TEN_MIB: usize = 10 * 1024 * 1024; // 10MiB
/// let cache = Cache::new(100);
///
/// // Spawn four async tasks.
/// let tasks: Vec<_> = (0..4_u8)
/// .map(|task_id| {
/// let my_cache = cache.clone();
/// tokio::spawn(async move {
/// println!("Task {} started.", task_id);
///
/// // Insert and get the value for key1. Although all four async tasks
/// // will call `get_with` at the same time, the `init` async
/// // block must be resolved only once.
/// let value = my_cache
/// .get_with("key1", async move {
/// println!("Task {} inserting a value.", task_id);
/// Arc::new(vec![0u8; TEN_MIB])
/// })
/// .await;
///
/// // Ensure the value exists now.
/// assert_eq!(value.len(), TEN_MIB);
/// assert!(my_cache.get(&"key1").is_some());
///
/// println!("Task {} got the value. (len: {})", task_id, value.len());
/// })
/// })
/// .collect();
///
/// // Run all tasks concurrently and wait for them to complete.
/// futures_util::future::join_all(tasks).await;
/// }
/// ```
///
/// **A Sample Result**
///
/// - The `init` future (async black) was resolved exactly once by task 3.
/// - Other tasks were blocked until task 3 inserted the value.
///
/// ```console
/// Task 0 started.
/// Task 3 started.
/// Task 1 started.
/// Task 2 started.
/// Task 3 inserting a value.
/// Task 3 got the value. (len: 10485760)
/// Task 0 got the value. (len: 10485760)
/// Task 1 got the value. (len: 10485760)
/// Task 2 got the value. (len: 10485760)
/// ```
///
/// # Panics
///
/// This method panics when the `init` future has panicked. When it happens, only
/// the caller whose `init` future panicked will get the panic (e.g. only task 3
/// in the above sample). If there are other calls in progress (e.g. task 0, 1
/// and 2 above), this method will restart and resolve one of the remaining
/// `init` futures.
///
pub async fn get_with(&self, key: K, init: impl Future<Output = V>) -> V {
let hash = self.base.hash(&key);
let key = Arc::new(key);
let replace_if = None as Option<fn(&V) -> bool>;
self.get_or_insert_with_hash_and_fun(key, hash, init, replace_if, false)
.await
.into_value()
}
/// Similar to [`get_with`](#method.get_with), but instead of passing an owned
/// key, you can pass a reference to the key. If the key does not exist in the
/// cache, the key will be cloned to create new entry in the cache.
pub async fn get_with_by_ref<Q>(&self, key: &Q, init: impl Future<Output = V>) -> V
where
K: Borrow<Q>,
Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
{
let hash = self.base.hash(key);
let replace_if = None as Option<fn(&V) -> bool>;
self.get_or_insert_with_hash_by_ref_and_fun(key, hash, init, replace_if, false)
.await
.into_value()
}
/// Deprecated, replaced with
/// [`entry()::or_insert_with_if()`](./struct.OwnedKeyEntrySelector.html#method.or_insert_with_if)
#[deprecated(since = "0.10.0", note = "Replaced with `entry().or_insert_with_if()`")]
pub async fn get_with_if(
&self,
key: K,
init: impl Future<Output = V>,
replace_if: impl FnMut(&V) -> bool,
) -> V {
let hash = self.base.hash(&key);
let key = Arc::new(key);
self.get_or_insert_with_hash_and_fun(key, hash, init, Some(replace_if), false)
.await
.into_value()
}
/// Returns a _clone_ of the value corresponding to the key. If the value does
/// not exist, resolves the `init` future, and inserts the value if `Some(value)`
/// was returned. If `None` was returned from the future, this method does not
/// insert a value and returns `None`.
///
/// # Concurrent calls on the same key
///
/// This method guarantees that concurrent calls on the same not-existing key are
/// coalesced into one evaluation of the `init` future. Only one of the calls
/// evaluates its future, and other calls wait for that future to resolve.
///
/// The following code snippet demonstrates this behavior:
///
/// ```rust
/// // Cargo.toml
/// //
/// // [dependencies]
/// // moka = { version = "0.9", features = ["future"] }
/// // futures-util = "0.3"
/// // reqwest = "0.11"
/// // tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
/// use moka::future::Cache;
///
/// // This async function tries to get HTML from the given URI.
/// async fn get_html(task_id: u8, uri: &str) -> Option<String> {
/// println!("get_html() called by task {}.", task_id);
/// reqwest::get(uri).await.ok()?.text().await.ok()
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let cache = Cache::new(100);
///
/// // Spawn four async tasks.
/// let tasks: Vec<_> = (0..4_u8)
/// .map(|task_id| {
/// let my_cache = cache.clone();
/// tokio::spawn(async move {
/// println!("Task {} started.", task_id);
///
/// // Try to insert and get the value for key1. Although
/// // all four async tasks will call `try_get_with`
/// // at the same time, get_html() must be called only once.