Skip to main content

common_cache/
cache.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::borrow::Borrow;
16use std::hash::Hash;
17use std::num::NonZeroUsize;
18use std::sync::Arc;
19use std::time::Duration;
20
21use futures::FutureExt;
22use futures::future::BoxFuture;
23use tokio::sync::{Mutex, Notify, mpsc};
24
25use crate::metrics::{CacheMetrics, CacheSizeMetric, CacheSizeRegistration};
26
27/// Bounded workers that drive cache misses independently of downstream readers.
28pub struct LoadPool {
29    jobs: mpsc::Sender<BoxFuture<'static, ()>>,
30    space: Arc<Notify>,
31}
32
33impl LoadPool {
34    /// Starts a fixed number of workers and buffers up to one job per worker.
35    /// Dropping the pool closes the queue and lets the workers exit.
36    pub fn new(
37        workers: NonZeroUsize,
38        mut spawn: impl FnMut(BoxFuture<'static, ()>) -> tokio::task::JoinHandle<()>,
39    ) -> Self {
40        let (jobs, receiver) = mpsc::channel::<BoxFuture<'static, ()>>(workers.get());
41        let receiver = Arc::new(Mutex::new(receiver));
42        let space = Arc::new(Notify::new());
43        for _ in 0..workers.get() {
44            let space = space.clone();
45            let receiver = receiver.clone();
46            spawn(Box::pin(async move {
47                loop {
48                    let job = receiver.lock().await.recv().await;
49                    let Some(job) = job else { break };
50                    space.notify_waiters();
51                    job.await;
52                }
53            }));
54        }
55        Self { jobs, space }
56    }
57
58    /// Drives a load until it returns or its caller is dropped. A closed queue
59    /// or lost worker reply lets the caller retry directly from storage.
60    pub async fn run<T: Send + 'static>(
61        &self,
62        job: impl Future<Output = T> + Send + 'static,
63    ) -> Option<T> {
64        let slot = self.reserve().await?;
65        let (mut reply, result) = tokio::sync::oneshot::channel();
66        slot.send(
67            async move {
68                tokio::select! {
69                    biased;
70                    _ = reply.closed() => {}
71                    output = std::panic::AssertUnwindSafe(job).catch_unwind() => {
72                        if let Ok(value) = output {
73                            let _ = reply.send(value);
74                        }
75                    }
76                }
77            }
78            .boxed(),
79        );
80        result.await.ok()
81    }
82
83    async fn reserve(&self) -> Option<mpsc::Permit<'_, BoxFuture<'static, ()>>> {
84        loop {
85            // Subscribe before checking capacity so a concurrent dequeue wakes us.
86            // An async channel reservation could grant the only free slot to a
87            // paused reader. Reserve only in the poll that actually submits the job.
88            let space = self.space.notified();
89            match self.jobs.try_reserve() {
90                Ok(slot) => return Some(slot),
91                Err(mpsc::error::TrySendError::Closed(_)) => return None,
92                Err(mpsc::error::TrySendError::Full(_)) => {
93                    tokio::select! {
94                        _ = space => (),
95                        _ = self.jobs.closed() => return None,
96                    }
97                }
98            }
99        }
100    }
101}
102
103/// Reason for releasing an entry from the cache.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum RemovalCause {
106    /// The entry reached its expiration time.
107    Expired,
108    /// The entry was explicitly invalidated.
109    Explicit,
110    /// A new value replaced the entry.
111    Replaced,
112    /// The entry was removed to satisfy the capacity policy.
113    Size,
114}
115
116impl RemovalCause {
117    /// Returns the established eviction metric label.
118    pub fn as_str(self) -> &'static str {
119        match self {
120            Self::Expired => "expired",
121            Self::Explicit => "explicit",
122            Self::Replaced => "replaced",
123            Self::Size => "size",
124        }
125    }
126}
127
128impl From<moka::notification::RemovalCause> for RemovalCause {
129    fn from(value: moka::notification::RemovalCause) -> Self {
130        match value {
131            moka::notification::RemovalCause::Expired => Self::Expired,
132            moka::notification::RemovalCause::Explicit => Self::Explicit,
133            moka::notification::RemovalCause::Replaced => Self::Replaced,
134            moka::notification::RemovalCause::Size => Self::Size,
135        }
136    }
137}
138
139/// A weighted memory cache with backend-provided asynchronous load deduplication.
140/// Values should be inexpensive to clone, such as `Arc<T>` or `Bytes`.
141/// Capacity is maintained asynchronously; insertion does not guarantee retention.
142#[derive(Clone)]
143pub struct Cache<K, V> {
144    inner: moka::future::Cache<K, V>,
145    capacity: u64,
146    size_registration: Option<CacheSizeRegistration>,
147    metrics: Option<Arc<CacheMetrics>>,
148}
149
150impl<K, V> Cache<K, V>
151where
152    K: Eq + Hash + Send + Sync + 'static,
153    V: Clone + Send + Sync + 'static,
154{
155    /// Creates a cache with the caller's weight and eviction accounting.
156    pub fn new<W, L>(name: &str, capacity: u64, weigher: W, listener: L) -> Self
157    where
158        W: Fn(&K, &V) -> u32 + Send + Sync + 'static,
159        L: Fn(Arc<K>, V, RemovalCause) + Send + Sync + 'static,
160    {
161        Self::new_with_ttl(name, capacity, weigher, listener, None)
162    }
163
164    /// Creates a cache with an optional write-based expiration time.
165    pub fn new_with_ttl<W, L>(
166        name: &str,
167        capacity: u64,
168        weigher: W,
169        listener: L,
170        ttl: Option<Duration>,
171    ) -> Self
172    where
173        W: Fn(&K, &V) -> u32 + Send + Sync + 'static,
174        L: Fn(Arc<K>, V, RemovalCause) + Send + Sync + 'static,
175    {
176        let mut builder = moka::future::Cache::builder()
177            .name(name)
178            .max_capacity(capacity)
179            .support_invalidation_closures()
180            .weigher(weigher)
181            .eviction_listener(move |key, value, cause| listener(key, value, cause.into()));
182        if let Some(ttl) = ttl {
183            builder = builder.time_to_live(ttl);
184        }
185        Self {
186            inner: builder.build(),
187            capacity,
188            size_registration: None,
189            metrics: None,
190        }
191    }
192
193    /// Attaches caller-bound metrics without changing existing hit/miss accounting.
194    pub fn with_metrics(mut self, metrics: Arc<CacheMetrics>) -> Self {
195        self.metrics = Some(metrics);
196        self
197    }
198
199    /// Samples this cache's retained weight when the caller collects byte metrics.
200    pub fn with_size_metric(mut self, metric: CacheSizeMetric) -> Self {
201        let cache = self.inner.clone();
202        self.size_registration = Some(metric.register(move || cache.weighted_size()));
203        self
204    }
205
206    /// Gets a completed value without starting a load.
207    pub fn get<'a, Q>(&'a self, key: &'a Q) -> impl Future<Output = Option<V>> + Send + 'a
208    where
209        K: Borrow<Q>,
210        Q: Hash + Eq + Sync + ?Sized,
211    {
212        self.inner.get(key)
213    }
214
215    /// Shares a successful load among concurrent callers with the same key and error type.
216    /// Errors are shared with current waiters but are not retained as cached values.
217    /// Cancelling the active loader lets a remaining caller execute its own loader.
218    pub async fn try_get_with<Q, F, E>(&self, key: &Q, load: F) -> Result<V, Arc<E>>
219    where
220        K: Borrow<Q>,
221        Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
222        F: Future<Output = Result<V, E>>,
223        E: Send + Sync + 'static,
224    {
225        let request = self
226            .metrics
227            .as_ref()
228            .map(|metrics| metrics.requests.start());
229        let result = self
230            .inner
231            .try_get_with_by_ref(key, async {
232                // Only the backend-selected loader contributes physical load metrics.
233                let operation = self.metrics.as_ref().map(|metrics| metrics.loads.start());
234                let result = load.await;
235                if let Some(operation) = operation {
236                    operation.finish(&result);
237                }
238                result
239            })
240            .await;
241        if let Some(request) = request {
242            request.finish(&result);
243        }
244        result
245    }
246
247    /// Shares a load whose caller tracks its own metrics and admission outcomes.
248    pub async fn try_get_with_unobserved<E: Send + Sync + 'static>(
249        &self,
250        key: K,
251        load: impl Future<Output = Result<V, E>>,
252    ) -> Result<V, Arc<E>> {
253        self.inner.try_get_with(key, load).await
254    }
255
256    /// Submits a completed value to the cache's admission and eviction policy.
257    pub async fn insert(&self, key: K, value: V) {
258        self.inner.insert(key, value).await;
259    }
260
261    /// Invalidates a completed entry. This does not cancel a concurrent loader.
262    pub async fn invalidate<Q>(&self, key: &Q)
263    where
264        K: Borrow<Q>,
265        Q: Hash + Eq + ?Sized,
266    {
267        self.inner.invalidate(key).await;
268    }
269
270    /// Invalidates completed entries matching a predicate. Pending loaders are not fenced.
271    /// Physical removal and eviction accounting run asynchronously.
272    pub fn invalidate_if<F>(&self, predicate: F) -> std::io::Result<()>
273    where
274        F: Fn(&K, &V) -> bool + Send + Sync + 'static,
275    {
276        self.inner
277            .invalidate_entries_if(predicate)
278            .map(|_| ())
279            .map_err(std::io::Error::other)
280    }
281
282    /// Returns the configured weight capacity.
283    pub fn capacity(&self) -> u64 {
284        self.capacity
285    }
286
287    /// Returns the approximate number of retained entries.
288    pub fn entry_count(&self) -> u64 {
289        self.inner.entry_count()
290    }
291
292    /// Returns the approximate total retained weight.
293    pub fn weighted_size(&self) -> u64 {
294        self.inner.weighted_size()
295    }
296
297    /// Applies pending admission, eviction, and accounting work.
298    pub async fn run_pending_tasks(&self) {
299        self.inner.run_pending_tasks().await;
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use std::sync::atomic::{AtomicUsize, Ordering};
306
307    use super::*;
308
309    // This is also a compile-time contract for generic callers crossing async-trait boundaries.
310    fn send_lookup<'a, K, V, Q>(
311        cache: &'a Cache<K, V>,
312        key: &'a Q,
313    ) -> impl Future<Output = Option<V>> + Send + 'a
314    where
315        K: Borrow<Q> + Eq + Hash + Send + Sync + 'static,
316        V: Clone + Send + Sync + 'static,
317        Q: Hash + Eq + Sync + ?Sized,
318    {
319        cache.get(key)
320    }
321
322    #[tokio::test]
323    async fn test_borrowed_lookup_has_a_send_future() {
324        let cache = cache(1024);
325        cache
326            .insert("key".to_string(), Arc::new("value".to_string()))
327            .await;
328        let future: futures::future::BoxFuture<'_, Option<Arc<String>>> =
329            Box::pin(send_lookup(&cache, "key"));
330        assert_eq!(future.await.as_deref().map(String::as_str), Some("value"));
331    }
332
333    #[tokio::test]
334    async fn parked_sender_cannot_reserve_the_next_load_slot() {
335        let pool = LoadPool::new(NonZeroUsize::MIN, tokio::spawn);
336        let (started, running) = tokio::sync::oneshot::channel();
337        let (release, wait) = tokio::sync::oneshot::channel();
338        let mut first = Box::pin(pool.run(async move {
339            started.send(()).unwrap();
340            wait.await.unwrap();
341        }));
342        assert!(futures::poll!(&mut first).is_pending());
343        running.await.unwrap();
344        let mut queued = Box::pin(pool.run(async { 2 }));
345        assert!(futures::poll!(&mut queued).is_pending());
346        assert_eq!(pool.jobs.capacity(), 0);
347        let mut parked = Box::pin(pool.run(async { 3 }));
348        assert!(futures::poll!(&mut parked).is_pending());
349
350        release.send(()).unwrap();
351        assert_eq!(queued.await, Some(2));
352        // Neither the original caller nor the waiting sender is polled here.
353        let later = tokio::time::timeout(Duration::from_secs(5), pool.run(async { 4 }))
354            .await
355            .unwrap();
356        assert_eq!(later, Some(4));
357        assert_eq!(first.await, Some(()));
358    }
359
360    #[tokio::test]
361    async fn test_predicate_invalidation_preserves_other_entries() {
362        let cache = cache(1024);
363        cache
364            .insert("old".to_string(), Arc::new("a".to_string()))
365            .await;
366        cache
367            .insert("keep".to_string(), Arc::new("b".to_string()))
368            .await;
369        cache.run_pending_tasks().await;
370        cache.invalidate_if(|key, _| key == "old").unwrap();
371        assert!(cache.get("old").await.is_none());
372        assert_eq!(
373            cache.get("keep").await.as_deref().map(String::as_str),
374            Some("b")
375        );
376    }
377
378    fn cache(capacity: u64) -> Cache<String, Arc<String>> {
379        Cache::new(
380            "test",
381            capacity,
382            |_, value: &Arc<String>| value.len() as u32,
383            |_, _, _| {},
384        )
385    }
386
387    fn operation_metrics(name: &str) -> crate::metrics::OperationMetrics {
388        use prometheus::{Histogram, HistogramOpts, IntCounter, IntGauge};
389
390        crate::metrics::OperationMetrics {
391            started: IntCounter::new(format!("{name}_started"), "test").unwrap(),
392            succeeded: IntCounter::new(format!("{name}_succeeded"), "test").unwrap(),
393            failed: IntCounter::new(format!("{name}_failed"), "test").unwrap(),
394            cancelled: IntCounter::new(format!("{name}_cancelled"), "test").unwrap(),
395            active: IntGauge::new(format!("{name}_active"), "test").unwrap(),
396            elapsed: Histogram::with_opts(HistogramOpts::new(format!("{name}_seconds"), "test"))
397                .unwrap(),
398        }
399    }
400
401    fn instrumented_cache() -> (Cache<String, Arc<String>>, Arc<CacheMetrics>) {
402        let metrics = Arc::new(CacheMetrics {
403            requests: operation_metrics("requests"),
404            loads: operation_metrics("loads"),
405        });
406        (cache(1024).with_metrics(metrics.clone()), metrics)
407    }
408
409    #[tokio::test]
410    async fn test_metrics_distinguish_requests_from_executed_loads() {
411        let (cache, metrics) = instrumented_cache();
412        // Merely constructing an async call does not start an operation.
413        drop(cache.try_get_with("unused", async { Ok::<_, ()>(Arc::new(String::new())) }));
414        assert_eq!(0, metrics.requests.started.get());
415        let gate = Notify::new();
416        let mut first = Box::pin(cache.try_get_with("key", async {
417            gate.notified().await;
418            Ok::<_, ()>(Arc::new("value".to_string()))
419        }));
420        let mut second = Box::pin(cache.try_get_with("key", async { Err::<Arc<String>, _>(()) }));
421        assert!(futures::poll!(&mut first).is_pending());
422        assert!(futures::poll!(&mut second).is_pending());
423        assert_eq!(2, metrics.requests.active.get());
424        assert_eq!(1, metrics.loads.active.get());
425        gate.notify_waiters();
426        let (first, second) = tokio::join!(first, second);
427        assert!(Arc::ptr_eq(&first.unwrap(), &second.unwrap()));
428        cache
429            .try_get_with("key", async { Err::<Arc<String>, _>(()) })
430            .await
431            .unwrap();
432        assert_eq!(3, metrics.requests.started.get());
433        assert_eq!(3, metrics.requests.succeeded.get());
434        assert_eq!(1, metrics.loads.started.get());
435        assert_eq!(1, metrics.loads.succeeded.get());
436        assert_eq!(0, metrics.requests.active.get());
437        assert_eq!(0, metrics.loads.active.get());
438        assert_eq!(3, metrics.requests.elapsed.get_sample_count());
439        assert_eq!(1, metrics.loads.elapsed.get_sample_count());
440        assert_eq!(0, metrics.requests.failed.get());
441        assert_eq!(0, metrics.requests.cancelled.get());
442    }
443
444    #[tokio::test]
445    async fn test_metrics_release_active_work_on_cancellation_and_error() {
446        let (cache, metrics) = instrumented_cache();
447        let mut producer =
448            Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
449        let mut waiter =
450            Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
451        assert!(futures::poll!(&mut producer).is_pending());
452        assert!(futures::poll!(&mut waiter).is_pending());
453        drop(waiter);
454        assert_eq!(1, metrics.requests.cancelled.get());
455        assert_eq!(0, metrics.loads.cancelled.get());
456        drop(producer);
457        assert_eq!(2, metrics.requests.cancelled.get());
458        assert_eq!(1, metrics.loads.cancelled.get());
459        let result = cache
460            .try_get_with("key", async { Err::<Arc<String>, _>(()) })
461            .await;
462        assert!(result.is_err());
463        assert_eq!(1, metrics.requests.failed.get());
464        assert_eq!(1, metrics.loads.failed.get());
465        assert_eq!(0, metrics.requests.active.get());
466        assert_eq!(0, metrics.loads.active.get());
467        assert_eq!(3, metrics.requests.elapsed.get_sample_count());
468        assert_eq!(2, metrics.loads.elapsed.get_sample_count());
469    }
470
471    #[tokio::test]
472    async fn test_instrumented_loading_future_is_send() {
473        fn assert_send<T: Send>(value: T) -> T {
474            value
475        }
476
477        let (cache, _) = instrumented_cache();
478        assert_send(
479            cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("value".to_string())) }),
480        )
481        .await
482        .unwrap();
483    }
484
485    #[tokio::test]
486    async fn test_shares_load_and_bypasses_loader_on_hit() {
487        let cache = cache(1024);
488        let calls = AtomicUsize::new(0);
489        let gate = Notify::new();
490        let load = || async {
491            calls.fetch_add(1, Ordering::Relaxed);
492            gate.notified().await;
493            Ok::<_, ()>(Arc::new("value".to_string()))
494        };
495        let mut first = Box::pin(cache.try_get_with("key", load()));
496        let mut second = Box::pin(cache.try_get_with("key", load()));
497        assert!(futures::poll!(&mut first).is_pending());
498        assert!(futures::poll!(&mut second).is_pending());
499        assert_eq!(1, calls.load(Ordering::Relaxed));
500        gate.notify_waiters();
501        let (first, second) = tokio::join!(first, second);
502        let first = first.unwrap();
503        assert!(Arc::ptr_eq(&first, &second.unwrap()));
504        let hit = cache
505            .try_get_with("key", async { Err::<Arc<String>, _>(()) })
506            .await
507            .unwrap();
508        assert!(Arc::ptr_eq(&first, &hit));
509    }
510
511    #[tokio::test]
512    async fn test_remaining_waiter_loads_after_producer_cancellation() {
513        let (cache, metrics) = instrumented_cache();
514        let mut first =
515            Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
516        assert!(futures::poll!(&mut first).is_pending());
517        let mut second = Box::pin(
518            cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("retry".to_string())) }),
519        );
520        assert!(futures::poll!(&mut second).is_pending());
521        drop(first);
522        assert_eq!("retry", second.await.unwrap().as_str());
523        assert_eq!(2, metrics.requests.started.get());
524        assert_eq!(1, metrics.requests.cancelled.get());
525        assert_eq!(1, metrics.requests.succeeded.get());
526        assert_eq!(2, metrics.loads.started.get());
527        assert_eq!(1, metrics.loads.cancelled.get());
528        assert_eq!(1, metrics.loads.succeeded.get());
529        assert_eq!(0, metrics.requests.active.get());
530        assert_eq!(0, metrics.loads.active.get());
531    }
532
533    #[tokio::test]
534    async fn test_errors_are_shared_but_not_cached() {
535        let (cache, metrics) = instrumented_cache();
536        let calls = AtomicUsize::new(0);
537        let gate = Notify::new();
538        let load = || async {
539            calls.fetch_add(1, Ordering::Relaxed);
540            gate.notified().await;
541            Err::<Arc<String>, _>("read failed")
542        };
543        let mut first = Box::pin(cache.try_get_with("key", load()));
544        let mut second = Box::pin(cache.try_get_with("key", load()));
545        assert!(futures::poll!(&mut first).is_pending());
546        assert!(futures::poll!(&mut second).is_pending());
547        gate.notify_waiters();
548        let (first, second) = tokio::join!(first, second);
549        assert!(Arc::ptr_eq(&first.unwrap_err(), &second.unwrap_err()));
550        assert_eq!(2, metrics.requests.failed.get());
551        assert_eq!(1, metrics.loads.failed.get());
552        assert_eq!(0, metrics.requests.active.get());
553        assert_eq!(0, metrics.loads.active.get());
554        assert_eq!(1, calls.load(Ordering::Relaxed));
555        assert!(cache.get("key").await.is_none());
556        assert_eq!(
557            "retry",
558            cache
559                .try_get_with("key", async {
560                    Ok::<_, &'static str>(Arc::new("retry".to_string()))
561                })
562                .await
563                .unwrap()
564                .as_str()
565        );
566    }
567
568    #[tokio::test]
569    async fn test_sampled_size_sums_instances_and_preserves_manual_bytes() {
570        use crate::metrics::CacheSizeMetrics;
571        use prometheus::Opts;
572        use prometheus::core::Collector;
573
574        let metrics =
575            CacheSizeMetrics::new(Opts::new("test_cache_bytes", "test"), &["type"]).unwrap();
576        let manual = metrics.with_label_values(&["shared"]);
577        manual.set(3);
578        let make_cache = || {
579            Cache::new("sampled", 100, |_: &u64, _: &Arc<String>| 7, |_, _, _| {})
580                .with_size_metric(metrics.bind(&["shared"]))
581        };
582        let a = make_cache();
583        let b = make_cache();
584        let sample = || {
585            metrics.collect()[0].get_metric()[0]
586                .get_gauge()
587                .as_ref()
588                .map_or(0.0, |gauge| gauge.value())
589        };
590        a.insert(1, Arc::new("one".into())).await;
591        b.insert(2, Arc::new("two".into())).await;
592        a.run_pending_tasks().await;
593        b.run_pending_tasks().await;
594        assert_eq!(17.0, sample());
595        assert_eq!(3, manual.get());
596        let consumer = a.get(&1).await.unwrap();
597        a.invalidate(&1).await;
598        a.run_pending_tasks().await;
599        assert_eq!(10.0, sample());
600        drop(consumer);
601        let cloned = b.clone();
602        drop(b);
603        assert_eq!(10.0, sample());
604        drop(cloned);
605        assert_eq!(3.0, sample());
606    }
607}