Skip to main content

common_meta/
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
15mod container;
16mod flow;
17mod registry;
18mod table;
19
20use std::collections::HashMap;
21use std::hash::Hash;
22use std::sync::Arc;
23
24pub use container::{BatchInitializer, CacheContainer, Initializer};
25pub use flow::{
26    FlowInfoCache, FlowInfoCacheRef, TableFlownodeSetCache, TableFlownodeSetCacheRef,
27    load_shared_flow_infos, new_flow_info_cache, new_table_flownode_set_cache,
28};
29pub use registry::{
30    CacheRegistry, CacheRegistryBuilder, CacheRegistryRef, LayeredCacheRegistry,
31    LayeredCacheRegistryBuilder, LayeredCacheRegistryRef,
32};
33pub use table::{
34    SchemaCache, SchemaCacheRef, TableInfoCache, TableInfoCacheRef, TableNameCache,
35    TableNameCacheRef, TableRoute, TableRouteCache, TableRouteCacheRef, TableSchemaCache,
36    TableSchemaCacheRef, ViewInfoCache, ViewInfoCacheRef, new_schema_cache, new_table_info_cache,
37    new_table_name_cache, new_table_route_cache, new_table_schema_cache, new_view_info_cache,
38};
39
40fn share_batch_values<K: Eq + Hash, V>(values: HashMap<K, V>) -> HashMap<K, Arc<V>> {
41    values
42        .into_iter()
43        .map(|(key, value)| (key, Arc::new(value)))
44        .collect()
45}
46
47#[cfg(test)]
48pub(crate) mod test_util {
49    use std::collections::BTreeMap;
50    use std::sync::Arc;
51    use std::sync::atomic::{AtomicUsize, Ordering};
52
53    use moka::future::Cache;
54
55    use crate::cache::CacheContainer;
56    use crate::instruction::CacheIdent;
57    use crate::kv_backend::KvBackendRef;
58    use crate::kv_backend::test_util::MockKvBackendBuilder;
59    use crate::rpc::KeyValue;
60    use crate::rpc::store::BatchGetResponse;
61
62    /// Exercises a real cache constructor with a backend that permits only the cold batch.
63    pub(crate) async fn assert_batch_cache_reads<V: Send + Sync + 'static>(
64        new_cache: impl FnOnce(
65            String,
66            Cache<(usize, u32), Arc<V>>,
67            KvBackendRef,
68        ) -> CacheContainer<u32, Arc<V>, CacheIdent>,
69        fixture: impl Fn(u32) -> (Vec<u8>, Vec<u8>),
70    ) {
71        let records: BTreeMap<_, _> = [10, 11].into_iter().map(fixture).collect();
72        let calls = Arc::new(AtomicUsize::new(0));
73        let observed = calls.clone();
74        let backend = MockKvBackendBuilder::default()
75            .max_txn_ops(128)
76            .range_fn(Arc::new(|_| panic!("unexpected metadata point read")))
77            .batch_get_fn(Arc::new(move |req| {
78                let mut keys = req.keys;
79                keys.sort();
80                assert!(keys.iter().eq(records.keys()));
81                observed.fetch_add(1, Ordering::Relaxed);
82                Ok(BatchGetResponse {
83                    kvs: keys
84                        .into_iter()
85                        .map(|key| KeyValue {
86                            value: records[&key].clone(),
87                            key,
88                        })
89                        .collect(),
90                })
91            }))
92            .build()
93            .unwrap();
94        let cache = new_cache("test".into(), Cache::new(8), Arc::new(backend));
95        for _ in 0..2 {
96            let values = cache.get_many(&[11, 10, 11]).await.unwrap();
97            assert_eq!(values.len(), 3);
98            assert!(values.iter().all(Option::is_some));
99            assert_eq!(calls.load(Ordering::Relaxed), 1);
100        }
101    }
102}