Skip to main content

common_meta/cache/
container.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::collections::HashMap;
17use std::hash::Hash;
18use std::sync::Arc;
19use std::sync::atomic::{AtomicUsize, Ordering};
20
21use common_cache::batch;
22use futures::future::{BoxFuture, try_join_all};
23use moka::future::Cache;
24use moka::ops::compute::Op;
25use snafu::{OptionExt, ResultExt};
26
27use crate::cache_invalidator::{CacheInvalidator, Context};
28use crate::error::{self, Error, Result};
29use crate::instruction::CacheIdent;
30use crate::metrics;
31
32/// Initializes value (i.e., fetches from remote).
33pub type Initializer<K, V> = Arc<dyn Fn(&'_ K) -> BoxFuture<'_, Result<Option<V>>> + Send + Sync>;
34
35/// Loads missing keys in one backend request. Absent keys are omitted from the result.
36pub type BatchInitializer<K, V> =
37    Arc<dyn Fn(Vec<K>) -> BoxFuture<'static, Result<HashMap<K, V>>> + Send + Sync>;
38
39pub(crate) type EventHandler<K, V, T> =
40    Box<dyn for<'a> Fn(CacheEntries<'a, K, V>, &'a [T]) -> BoxFuture<'a, ()> + Send + Sync>;
41
42pub(crate) enum Invalidation<K, V, T> {
43    Key(fn(&T) -> Option<&K>),
44    Events(EventHandler<K, V, T>),
45}
46
47/// Event handlers use the same epoch and per-key compute lock as cache loads.
48pub(crate) struct CacheEntries<'a, K, V> {
49    cache: &'a Cache<(usize, K), V>,
50    epoch: &'a AtomicUsize,
51}
52
53impl<K, V> CacheEntries<'_, K, V>
54where
55    K: Clone + Eq + Hash + Send + Sync + 'static,
56    V: Clone + Send + Sync + 'static,
57{
58    pub(crate) async fn compute(&self, key: &K, update: impl FnOnce(Option<V>) -> Op<V>) {
59        let key = (self.epoch.load(Ordering::Acquire), key.clone());
60        self.cache
61            .entry(key.clone())
62            .and_compute_with(|entry| async move {
63                match update(entry.map(|entry| entry.into_value())) {
64                    Op::Put(value) => self.cache.insert(key, value).await,
65                    Op::Remove => self.cache.invalidate(&key).await,
66                    Op::Nop => {}
67                }
68                Op::Nop
69            })
70            .await;
71    }
72
73    pub(crate) fn invalidate_all(&self) {
74        self.epoch.fetch_add(1, Ordering::AcqRel);
75        self.cache.invalidate_all();
76    }
77}
78
79/// Caches metadata and coalesces backend reads for concurrent callers.
80pub struct CacheContainer<K, V, CacheToken> {
81    name: String,
82    cache: Cache<(usize, K), V>,
83    invalidation: Invalidation<K, V, CacheToken>,
84    initializer: Initializer<K, V>,
85    batch_initializer: Option<BatchInitializer<K, V>>,
86    epoch: AtomicUsize,
87}
88
89impl<K, V, CacheToken> CacheContainer<K, V, CacheToken>
90where
91    K: Clone + Hash + Eq + Send + Sync + 'static,
92    V: Clone + Send + Sync + 'static,
93    CacheToken: Send + Sync,
94{
95    /// Coordinates misses and targeted invalidation through Moka's per-key compute lock.
96    /// Invalidation can wait for a backend read. An overlapping reader may return its
97    /// old result, but a read started after invalidation returns cannot hit that result.
98    /// A synchronous full clear advances the epoch, isolating any late publication.
99    pub fn new(
100        name: String,
101        cache: Cache<(usize, K), V>,
102        initializer: Initializer<K, V>,
103        key: fn(&CacheToken) -> Option<&K>,
104    ) -> Self {
105        Self::with_invalidation(name, cache, initializer, Invalidation::Key(key))
106    }
107
108    pub(crate) fn with_invalidation(
109        name: String,
110        cache: Cache<(usize, K), V>,
111        initializer: Initializer<K, V>,
112        invalidation: Invalidation<K, V, CacheToken>,
113    ) -> Self {
114        Self {
115            name,
116            cache,
117            invalidation,
118            initializer,
119            batch_initializer: None,
120            epoch: AtomicUsize::default(),
121        }
122    }
123
124    /// Uses the supplied loader for [`get_many`](Self::get_many).
125    pub fn with_batch_initializer(mut self, initializer: BatchInitializer<K, V>) -> Self {
126        self.batch_initializer = Some(initializer);
127        self
128    }
129
130    /// Returns the `name`.
131    pub fn name(&self) -> &str {
132        &self.name
133    }
134}
135
136async fn init<'a, K, V>(init: Initializer<K, V>, key: K, cache_name: &'a str) -> Result<V>
137where
138    K: Send + Sync + 'a,
139    V: Send + 'a,
140{
141    metrics::CACHE_CONTAINER_CACHE_MISS
142        .with_label_values(&[cache_name])
143        .inc();
144    let _timer = metrics::CACHE_CONTAINER_LOAD_CACHE
145        .with_label_values(&[cache_name])
146        .start_timer();
147    init(&key)
148        .await
149        .transpose()
150        .context(error::ValueNotExistSnafu)?
151}
152
153#[async_trait::async_trait]
154impl<K, V> CacheInvalidator for CacheContainer<K, V, CacheIdent>
155where
156    K: Clone + Hash + Eq + Send + Sync + 'static,
157    V: Clone + Send + Sync + 'static,
158{
159    async fn invalidate(&self, _ctx: &Context, caches: &[CacheIdent]) -> Result<()> {
160        self.invalidate(caches).await
161    }
162
163    fn invalidate_all(&self) -> Result<()> {
164        self.entries().invalidate_all();
165        Ok(())
166    }
167}
168
169impl<K, V, CacheToken> CacheContainer<K, V, CacheToken>
170where
171    K: Clone + Hash + Eq + Send + Sync + 'static,
172    V: Clone + Send + Sync + 'static,
173    CacheToken: Send + Sync,
174{
175    fn entries(&self) -> CacheEntries<'_, K, V> {
176        CacheEntries {
177            cache: &self.cache,
178            epoch: &self.epoch,
179        }
180    }
181
182    /// Applies matching invalidations, waiting for active loads of the affected keys.
183    pub async fn invalidate(&self, tokens: &[CacheToken]) -> Result<()> {
184        let entries = self.entries();
185        match &self.invalidation {
186            Invalidation::Key(key_of) => {
187                for key in tokens.iter().filter_map(key_of) {
188                    entries.compute(key, |_| Op::Remove).await;
189                }
190            }
191            Invalidation::Events(handler) => handler(entries, tokens).await,
192        }
193        Ok(())
194    }
195
196    /// Tests membership in the current cache epoch.
197    pub fn contains_key<Q>(&self, key: &Q) -> bool
198    where
199        K: Borrow<Q>,
200        Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
201    {
202        self.cache
203            .contains_key(&(self.epoch.load(Ordering::Acquire), key.to_owned()))
204    }
205
206    /// Returns the cached value or initializes it.
207    pub async fn get(&self, key: K) -> Result<Option<V>> {
208        self.get_by_ref(&key).await
209    }
210
211    /// Looks up a borrowed key with the same loading semantics as [Self::get].
212    pub async fn get_by_ref<Q>(&self, key: &Q) -> Result<Option<V>>
213    where
214        K: Borrow<Q>,
215        Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
216    {
217        self.get_by_ref_with(key, self.initializer.clone()).await
218    }
219
220    async fn cached<Q>(&self, key: &Q) -> Option<V>
221    where
222        K: Borrow<Q>,
223        Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
224    {
225        self.cache
226            .get(&(self.epoch.load(Ordering::Acquire), key.to_owned()))
227            .await
228    }
229
230    async fn get_by_ref_with<Q>(&self, key: &Q, initializer: Initializer<K, V>) -> Result<Option<V>>
231    where
232        K: Borrow<Q>,
233        Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
234    {
235        metrics::CACHE_CONTAINER_CACHE_GET
236            .with_label_values(&[&self.name])
237            .inc();
238        let cache = &self.cache;
239        let storage_key = (self.epoch.load(Ordering::Acquire), key.to_owned());
240        if let Some(value) = cache.get(&storage_key).await {
241            return Ok(Some(value));
242        }
243        let load = init(initializer, key.to_owned(), &self.name);
244        let mut loaded = None;
245        let output = &mut loaded;
246        let result = cache
247            .entry(storage_key.clone())
248            .and_try_compute_with(|entry| async move {
249                if entry.is_none() {
250                    let value = load.await?;
251                    // Moka 0.12.10 releases the compute lock before applying Op::Put
252                    // or Op::Remove. Publish here, while removals still wait.
253                    cache.insert(storage_key, value.clone()).await;
254                    *output = Some(value);
255                }
256                Ok(Op::Nop)
257            })
258            .await;
259        match result {
260            Ok(result) => Ok(loaded.or_else(|| result.into_entry().map(|e| e.into_value()))),
261            Err(Error::ValueNotExist { .. }) => Ok(None),
262            Err(err) => Err(Arc::new(err)).context(error::GetCacheSnafu),
263        }
264    }
265
266    /// Returns values in input order, preserving duplicates and missing keys.
267    ///
268    /// A key omitted by the loader returns `None` and is not cached, so a
269    /// subsequent lookup loads it again. Backend errors are propagated.
270    /// Cache hits do not reach the batch loader. Misses use the same Moka
271    /// initialization entries as single-key reads. Only the keys whose loaders
272    /// this call owns are submitted to its batch loader. Results do not form a multi-key
273    /// snapshot. A waiter may retry a failed or missing load.
274    pub async fn get_many(&self, keys: &[K]) -> Result<Vec<Option<V>>> {
275        let Some(batch_initializer) = &self.batch_initializer else {
276            return try_join_all(keys.iter().map(|key| self.get_by_ref(key))).await;
277        };
278        let mut values = Vec::with_capacity(keys.len());
279        let mut misses = HashMap::new();
280        let mut duplicates = Vec::new();
281        for (index, key) in keys.iter().enumerate() {
282            let value = self.cached(key).await;
283            if value.is_none() {
284                let first = *misses.entry(key).or_insert(index);
285                if first != index {
286                    duplicates.push((index, first));
287                }
288            }
289            values.push(value);
290        }
291        metrics::CACHE_CONTAINER_CACHE_GET
292            .with_label_values(&[&self.name])
293            .inc_by((keys.len() - misses.len() - duplicates.len()) as u64);
294        if misses.is_empty() {
295            return Ok(values);
296        }
297
298        let loads = |requests| {
299            let initializer = Self::queued_initializer(requests);
300            misses.into_values().map(move |index| {
301                let read = self.get_by_ref_with(&keys[index], initializer.clone());
302                async move { read.await.map(|value| (index, value)) }
303            })
304        };
305        batch::load(
306            loads,
307            |keys, replies| async move {
308                let values = batch_initializer(keys)
309                    .await
310                    .map(Arc::new)
311                    .map_err(Arc::new);
312                for reply in replies {
313                    let _ = reply.send(values.clone());
314                }
315            },
316            |(index, value)| values[index] = value,
317        )
318        .await?;
319        for (index, first) in duplicates {
320            values[index] = values[first].clone();
321        }
322        Ok(values)
323    }
324
325    fn queued_initializer(requests: batch::BatchSender<K, BatchResult<K, V>>) -> Initializer<K, V> {
326        Arc::new(move |key| {
327            let requests = requests.clone();
328            Box::pin(async move {
329                let values =
330                    requests
331                        .request(key.clone())
332                        .await
333                        .context(error::UnexpectedSnafu {
334                            err_msg: "Cache batch reply dropped",
335                        })?;
336                Ok(values.context(error::GetCacheSnafu)?.get(key).cloned())
337            })
338        })
339    }
340}
341
342type BatchResult<K, V> = std::result::Result<Arc<HashMap<K, V>>, Arc<Error>>;
343
344#[cfg(test)]
345mod tests {
346    use std::sync::Arc;
347    use std::sync::atomic::{AtomicI32, Ordering};
348
349    use super::*;
350
351    use std::time::Duration;
352
353    fn batch_test_cache(
354        initializer: Initializer<u32, u32>,
355    ) -> CacheContainer<u32, u32, CacheIdent> {
356        CacheContainer::new(
357            "batch_test".into(),
358            Cache::new(64),
359            initializer,
360            CacheIdent::table_id_key,
361        )
362    }
363
364    #[tokio::test]
365    async fn test_get_many_hits_missing_duplicates_and_invalidation() {
366        let batches = Arc::new(std::sync::Mutex::new(Vec::new()));
367        let observed = batches.clone();
368        let cache = batch_test_cache(Arc::new(|_| {
369            Box::pin(async { panic!("unexpected single load") })
370        }))
371        .with_batch_initializer(Arc::new(move |mut keys| {
372            let observed = observed.clone();
373            Box::pin(async move {
374                keys.sort_unstable();
375                observed.lock().unwrap().push(keys.clone());
376                Ok(keys
377                    .into_iter()
378                    .filter(|&k| k != 3)
379                    .map(|k| (k, k * 10))
380                    .collect())
381            })
382        }));
383        assert_eq!(cache.get_many(&[1]).await.unwrap(), [Some(10)]);
384        batches.lock().unwrap().clear();
385        assert_eq!(
386            cache.get_many(&[2, 1, 2, 3]).await.unwrap(),
387            vec![Some(20), Some(10), Some(20), None]
388        );
389        assert_eq!(*batches.lock().unwrap(), vec![vec![2, 3]]);
390        assert_eq!(
391            cache.get_many(&[2, 1]).await.unwrap(),
392            vec![Some(20), Some(10)]
393        );
394        assert!(cache.get_many(&[]).await.unwrap().is_empty());
395        assert_eq!(batches.lock().unwrap().len(), 1);
396        cache.invalidate(&[CacheIdent::TableId(1)]).await.unwrap();
397        assert_eq!(
398            cache.get_many(&[1, 2]).await.unwrap(),
399            vec![Some(10), Some(20)]
400        );
401        assert_eq!(*batches.lock().unwrap(), vec![vec![2, 3], vec![1]]);
402        // Missing values are batch-local, so a subsequent request loads them again.
403        assert_eq!(cache.get_many(&[3]).await.unwrap(), vec![None]);
404        assert_eq!(batches.lock().unwrap().last().unwrap(), &vec![3]);
405    }
406
407    #[tokio::test]
408    async fn test_get_many_without_batch_initializer() {
409        let cache = batch_test_cache(Arc::new(|&key| {
410            Box::pin(async move { Ok((key != 3).then_some(key * 10)) })
411        }));
412        assert_eq!(cache.get(1).await.unwrap(), Some(10));
413        assert_eq!(
414            cache.get_many(&[2, 1, 3, 2]).await.unwrap(),
415            [Some(20), Some(10), None, Some(20)]
416        );
417    }
418
419    type BatchGate = (Vec<u32>, tokio::sync::oneshot::Sender<Result<()>>);
420
421    fn gated_batch_cache() -> (
422        CacheContainer<u32, u32, CacheIdent>,
423        tokio::sync::mpsc::UnboundedReceiver<BatchGate>,
424    ) {
425        let (observed, batches) = tokio::sync::mpsc::unbounded_channel();
426        let init: Initializer<u32, u32> =
427            Arc::new(|_| Box::pin(async { panic!("unexpected single load") }));
428        let cache = batch_test_cache(init).with_batch_initializer(Arc::new(move |mut keys| {
429            let (resume, gate) = tokio::sync::oneshot::channel();
430            keys.sort_unstable();
431            observed.send((keys.clone(), resume)).unwrap();
432            Box::pin(async move {
433                gate.await.unwrap()?;
434                Ok(keys.into_iter().map(|key| (key, key)).collect())
435            })
436        }));
437        (cache, batches)
438    }
439
440    #[tokio::test]
441    async fn test_overlapping_batches_load_each_key_once() {
442        let (cache, mut batches) = gated_batch_cache();
443        let mut first = Box::pin(cache.get_many(&[1, 2]));
444        assert!(futures::poll!(&mut first).is_pending());
445        let (keys, resume_first) = batches.try_recv().unwrap();
446        assert_eq!(keys, [1, 2]);
447
448        let mut second = Box::pin(cache.get_many(&[2, 3]));
449        assert!(futures::poll!(&mut second).is_pending());
450        let (keys, resume_second) = batches.try_recv().unwrap();
451        assert_eq!(keys, [3]);
452
453        resume_first.send(Ok(())).unwrap();
454        resume_second.send(Ok(())).unwrap();
455        let (first, second) = futures::try_join!(first, second).unwrap();
456        assert_eq!(first, [Some(1), Some(2)]);
457        assert_eq!(second, [Some(2), Some(3)]);
458    }
459
460    #[tokio::test]
461    async fn test_batch_waiter_promoted_after_cancellation() {
462        let (cache, mut batches) = gated_batch_cache();
463        let mut owner = Box::pin(cache.get_many(&[1]));
464        assert!(futures::poll!(&mut owner).is_pending());
465        let (keys, cancelled) = batches.try_recv().unwrap();
466        assert_eq!(keys, [1]);
467
468        let mut waiter = Box::pin(cache.get_many(&[1, 2]));
469        assert!(futures::poll!(&mut waiter).is_pending());
470        let (keys, resume) = batches.try_recv().unwrap();
471        assert_eq!(keys, [2]);
472        drop(owner);
473        assert!(cancelled.send(Ok(())).is_err());
474        resume.send(Ok(())).unwrap();
475
476        let promoted = async {
477            let (keys, resume) = batches.recv().await.unwrap();
478            assert_eq!(keys, [1]);
479            resume.send(Ok(())).unwrap();
480        };
481        let (result, ()) = tokio::time::timeout(Duration::from_secs(5), async {
482            tokio::join!(waiter, promoted)
483        })
484        .await
485        .unwrap();
486        assert_eq!(result.unwrap(), [Some(1), Some(2)]);
487    }
488
489    #[tokio::test]
490    async fn test_waiter_reloads_after_owner_error() {
491        let (cache, mut batches) = gated_batch_cache();
492        let mut owner = Box::pin(cache.get_many(&[1]));
493        assert!(futures::poll!(&mut owner).is_pending());
494        let (_, fail) = batches.try_recv().unwrap();
495        let mut waiter = Box::pin(cache.get_many(&[1]));
496        assert!(futures::poll!(&mut waiter).is_pending());
497        assert!(batches.try_recv().is_err());
498
499        fail.send(error::GetLatestCacheRetryExceededSnafu { attempts: 1usize }.fail())
500            .unwrap();
501        assert!(owner.await.is_err());
502        assert!(futures::poll!(&mut waiter).is_pending());
503        let (keys, resume) = batches.try_recv().unwrap();
504        assert_eq!(keys, [1]);
505        resume.send(Ok(())).unwrap();
506        assert_eq!(waiter.await.unwrap(), [Some(1)]);
507    }
508
509    #[tokio::test]
510    async fn test_large_cold_batch_loads_ready_keys_together() {
511        let (cache, mut batches) = gated_batch_cache();
512        let keys: Vec<_> = (0..128).collect();
513        let mut read = Box::pin(cache.get_many(&keys));
514        assert!(futures::poll!(&mut read).is_pending());
515        let (loaded, resume) = batches.try_recv().unwrap();
516        assert_eq!(loaded, keys);
517        resume.send(Ok(())).unwrap();
518        assert_eq!(
519            read.await.unwrap(),
520            keys.into_iter().map(Some).collect::<Vec<_>>()
521        );
522    }
523
524    #[tokio::test]
525    async fn test_get_many_coalesces_with_single_key_load() {
526        let started = Arc::new(tokio::sync::Notify::new());
527        let resume = Arc::new(tokio::sync::Notify::new());
528        let cache = Arc::new(
529            batch_test_cache(Arc::new({
530                let started = started.clone();
531                let resume = resume.clone();
532                move |_| {
533                    let started = started.clone();
534                    let resume = resume.clone();
535                    Box::pin(async move {
536                        started.notify_one();
537                        resume.notified().await;
538                        Ok(Some(10))
539                    })
540                }
541            }))
542            .with_batch_initializer(Arc::new(|keys| {
543                assert_eq!(keys, [2]);
544                Box::pin(async { Ok(HashMap::from([(2, 20)])) })
545            })),
546        );
547        let single = tokio::spawn({
548            let cache = cache.clone();
549            async move { cache.get(1).await }
550        });
551        started.notified().await;
552        let mut batch = Box::pin(cache.get_many(&[1, 2]));
553        assert!(futures::poll!(&mut batch).is_pending());
554        resume.notify_one();
555        assert_eq!(batch.await.unwrap(), vec![Some(10), Some(20)]);
556        assert_eq!(single.await.unwrap().unwrap(), Some(10));
557    }
558
559    #[tokio::test]
560    async fn test_get_many_reloads_after_backend_error() {
561        let attempts = Arc::new(AtomicUsize::new(0));
562        let loads = attempts.clone();
563        let cache = batch_test_cache(Arc::new(|_| {
564            Box::pin(async { panic!("unexpected single load") })
565        }))
566        .with_batch_initializer(Arc::new(move |keys| {
567            let loads = loads.clone();
568            Box::pin(async move {
569                if loads.fetch_add(1, Ordering::SeqCst) == 0 {
570                    return error::GetLatestCacheRetryExceededSnafu { attempts: 1usize }.fail();
571                }
572                Ok(keys.into_iter().map(|k| (k, k * 10)).collect())
573            })
574        }));
575        assert!(cache.get_many(&[1, 2]).await.is_err());
576        assert!(!cache.contains_key(&1));
577        assert_eq!(
578            cache.get_many(&[1, 2]).await.unwrap(),
579            vec![Some(10), Some(20)]
580        );
581        assert_eq!(attempts.load(Ordering::SeqCst), 2);
582    }
583
584    #[tokio::test]
585    async fn test_cancelled_batch_releases_single_key_waiter() {
586        let started = Arc::new(tokio::sync::Notify::new());
587        let cache = Arc::new(
588            batch_test_cache(Arc::new(|_| Box::pin(async { Ok(Some(20)) })))
589                .with_batch_initializer(Arc::new({
590                    let started = started.clone();
591                    move |_| {
592                        let started = started.clone();
593                        Box::pin(async move {
594                            started.notify_one();
595                            std::future::pending().await
596                        })
597                    }
598                })),
599        );
600        let batch = tokio::spawn({
601            let cache = cache.clone();
602            async move { cache.get_many(&[1, 2]).await }
603        });
604        started.notified().await;
605        let mut single = Box::pin(cache.get(1));
606        assert!(futures::poll!(&mut single).is_pending());
607        batch.abort();
608        assert!(batch.await.unwrap_err().is_cancelled());
609        assert_eq!(
610            tokio::time::timeout(Duration::from_secs(5), single)
611                .await
612                .unwrap()
613                .unwrap(),
614            Some(20)
615        );
616    }
617
618    #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
619    struct NameKey<'a> {
620        name: &'a str,
621    }
622
623    #[tokio::test]
624    async fn test_get() {
625        let cache = Cache::new(128);
626        let counter = Arc::new(AtomicI32::new(0));
627        let moved_counter = counter.clone();
628        let init: Initializer<NameKey, String> = Arc::new(move |_| {
629            moved_counter.fetch_add(1, Ordering::Relaxed);
630            Box::pin(async { Ok(Some("hi".to_string())) })
631        });
632        let cache = CacheContainer::new("test".to_string(), cache, init, |_: &String| None);
633        let key = NameKey { name: "key" };
634        let value = cache.get(key).await.unwrap().unwrap();
635        assert_eq!(value, "hi");
636        assert_eq!(counter.load(Ordering::Relaxed), 1);
637        let key = NameKey { name: "key" };
638        let value = cache.get(key).await.unwrap().unwrap();
639        assert_eq!(value, "hi");
640        assert_eq!(counter.load(Ordering::Relaxed), 1);
641    }
642
643    #[tokio::test]
644    async fn test_get_by_ref() {
645        let cache = Cache::new(128);
646        let counter = Arc::new(AtomicI32::new(0));
647        let moved_counter = counter.clone();
648        let init: Initializer<String, String> = Arc::new(move |_| {
649            moved_counter.fetch_add(1, Ordering::Relaxed);
650            Box::pin(async { Ok(Some("hi".to_string())) })
651        });
652        let cache = CacheContainer::new("test".to_string(), cache, init, |_: &String| None);
653        let value = cache.get_by_ref("foo").await.unwrap().unwrap();
654        assert_eq!(value, "hi");
655        let value = cache.get_by_ref("foo").await.unwrap().unwrap();
656        assert_eq!(value, "hi");
657        assert_eq!(counter.load(Ordering::Relaxed), 1);
658        let value = cache.get_by_ref("bar").await.unwrap().unwrap();
659        assert_eq!(value, "hi");
660        assert_eq!(counter.load(Ordering::Relaxed), 2);
661    }
662
663    #[tokio::test]
664    async fn test_get_value_not_exits() {
665        let cache = Cache::new(128);
666        let init: Initializer<String, String> =
667            Arc::new(move |_| Box::pin(async { error::ValueNotExistSnafu {}.fail() }));
668        let cache = CacheContainer::new("test".to_string(), cache, init, |_: &String| None);
669        let value = cache.get_by_ref("foo").await.unwrap();
670        assert!(value.is_none());
671    }
672
673    #[tokio::test]
674    async fn test_invalidate_with_borrowed_keys() {
675        let foo = String::from("foo");
676        let bar = String::from("bar");
677        let cache = Cache::new(128);
678        let counter = Arc::new(AtomicI32::new(0));
679        let moved_counter = counter.clone();
680        let init: Initializer<String, String> = Arc::new(move |_| {
681            moved_counter.fetch_add(1, Ordering::Relaxed);
682            Box::pin(async { Ok(Some("hi".to_string())) })
683        });
684        let cache =
685            CacheContainer::new("test".to_string(), cache, init, |key: &&String| Some(*key));
686        let value = cache.get_by_ref("foo").await.unwrap().unwrap();
687        assert_eq!(value, "hi");
688        let value = cache.get_by_ref("foo").await.unwrap().unwrap();
689        assert_eq!(value, "hi");
690        assert_eq!(counter.load(Ordering::Relaxed), 1);
691        cache.invalidate(&[&foo, &bar]).await.unwrap();
692        let value = cache.get_by_ref("foo").await.unwrap().unwrap();
693        assert_eq!(value, "hi");
694        assert_eq!(counter.load(Ordering::Relaxed), 2);
695    }
696
697    #[tokio::test]
698    async fn removal_waits_for_publication() {
699        let (cache, mut batches) = gated_batch_cache();
700        let mut reader = Box::pin(cache.get_many(&[1]));
701        assert!(futures::poll!(&mut reader).is_pending());
702        let (_, resume) = batches.try_recv().unwrap();
703
704        cache.invalidate(&[CacheIdent::TableId(2)]).await.unwrap();
705        let tokens = [CacheIdent::TableId(1)];
706        let mut removal = Box::pin(cache.invalidate(&tokens));
707        assert!(futures::poll!(&mut removal).is_pending());
708        resume.send(Ok(())).unwrap();
709        assert_eq!(reader.await.unwrap(), [Some(1)]);
710        removal.await.unwrap();
711        assert!(!cache.contains_key(&1));
712    }
713
714    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
715    async fn invalidation_during_publication_removes_old_value() {
716        use std::sync::{Mutex, mpsc};
717
718        struct Value {
719            id: i32,
720            in_batch_reply: bool,
721            before_publish: Arc<Mutex<Option<mpsc::Sender<()>>>>,
722            resume: Arc<Mutex<mpsc::Receiver<()>>>,
723        }
724        impl Clone for Value {
725            fn clone(&self) -> Self {
726                // Batch replies first clone the value out of the result map.
727                if !self.in_batch_reply
728                    && let Some(started) = self.before_publish.lock().unwrap().take()
729                {
730                    started.send(()).unwrap();
731                    self.resume
732                        .lock()
733                        .unwrap()
734                        .recv_timeout(Duration::from_secs(5))
735                        .unwrap();
736                }
737                Self {
738                    id: self.id,
739                    in_batch_reply: false,
740                    before_publish: self.before_publish.clone(),
741                    resume: self.resume.clone(),
742                }
743            }
744        }
745
746        for batch in [false, true] {
747            let (started, publishing) = mpsc::channel();
748            let (resume, gate) = mpsc::channel();
749            let before_publish = Arc::new(Mutex::new(Some(started)));
750            let gate = Arc::new(Mutex::new(gate));
751            let backend = Arc::new(AtomicI32::new(10));
752            let current = backend.clone();
753            let read = move |in_batch_reply| Value {
754                id: current.load(Ordering::SeqCst),
755                in_batch_reply,
756                before_publish: before_publish.clone(),
757                resume: gate.clone(),
758            };
759            let single = read.clone();
760            let cache = Arc::new(
761                CacheContainer::new(
762                    "test".into(),
763                    Cache::new(8),
764                    Arc::new(move |_| {
765                        let value = single(false);
766                        Box::pin(async move { Ok(Some(value)) })
767                    }),
768                    CacheIdent::table_id_key,
769                )
770                .with_batch_initializer(Arc::new(move |keys| {
771                    let values = keys.into_iter().map(|k| (k, read(true))).collect();
772                    Box::pin(async move { Ok(values) })
773                })),
774            );
775            let reader = tokio::spawn({
776                let cache = cache.clone();
777                async move {
778                    if batch {
779                        cache.get_many(&[1]).await.unwrap()[0].as_ref().unwrap().id
780                    } else {
781                        cache.get(1).await.unwrap().unwrap().id
782                    }
783                }
784            });
785            publishing.recv_timeout(Duration::from_secs(5)).unwrap();
786            backend.store(20, Ordering::SeqCst);
787            let tokens = [CacheIdent::TableId(1)];
788            let mut removal = Box::pin(cache.invalidate(&tokens));
789            let result = futures::poll!(&mut removal);
790            resume.send(()).unwrap();
791            assert!(result.is_pending());
792            removal.await.unwrap();
793            assert_eq!(reader.await.unwrap(), 10);
794            assert_eq!(cache.get(1).await.unwrap().unwrap().id, 20);
795        }
796    }
797
798    #[tokio::test]
799    async fn full_clear_isolates_an_inflight_batch_load() {
800        let (cache, mut batches) = gated_batch_cache();
801        let mut old = Box::pin(cache.get_many(&[1]));
802        assert!(futures::poll!(&mut old).is_pending());
803        let (_, resume) = batches.try_recv().unwrap();
804        cache.invalidate_all().unwrap();
805        resume.send(Ok(())).unwrap();
806        assert_eq!(old.await.unwrap(), [Some(1)]);
807        assert!(!cache.contains_key(&1));
808    }
809
810    #[tokio::test]
811    async fn full_clear_isolates_an_inflight_single_load() {
812        let (send, mut recv) = tokio::sync::mpsc::unbounded_channel();
813        let cache = batch_test_cache(Arc::new(move |_| {
814            let (resume, gate) = tokio::sync::oneshot::channel();
815            send.send(resume).unwrap();
816            Box::pin(async move { Ok(Some(gate.await.unwrap())) })
817        }));
818        let mut old = Box::pin(cache.get_by_ref(&1));
819        assert!(futures::poll!(&mut old).is_pending());
820        let first = recv.try_recv().unwrap();
821        cache.invalidate_all().unwrap();
822        let mut new = Box::pin(cache.get(1));
823        assert!(futures::poll!(&mut new).is_pending());
824        recv.try_recv().unwrap().send(20).unwrap();
825        assert_eq!(new.await.unwrap(), Some(20));
826        first.send(10).unwrap();
827        assert_eq!(old.await.unwrap(), Some(10));
828        assert_eq!(cache.get_many(&[1]).await.unwrap(), [Some(20)]);
829    }
830}