Skip to main content

catalog/kvbackend/
table_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::sync::Arc;
16
17use common_meta::cache::{CacheContainer, Initializer, TableInfoCacheRef, TableNameCacheRef};
18use common_meta::error::ValueNotExistSnafu;
19use common_meta::instruction::CacheIdent;
20use moka::future::Cache;
21use snafu::OptionExt;
22use table::TableRef;
23use table::dist_table::DistTable;
24use table::table_name::TableName;
25
26pub type TableCacheRef = Arc<TableCache>;
27
28/// [TableCache] caches the [TableName] to [TableRef] mapping.
29pub type TableCache = CacheContainer<TableName, TableRef, CacheIdent>;
30
31/// Constructs a [TableCache].
32pub fn new_table_cache(
33    name: String,
34    cache: Cache<(usize, TableName), TableRef>,
35    table_info_cache: TableInfoCacheRef,
36    table_name_cache: TableNameCacheRef,
37) -> TableCache {
38    let init = init_factory(table_info_cache, table_name_cache);
39
40    CacheContainer::new(name, cache, init, CacheIdent::table_name_key)
41}
42
43fn init_factory(
44    table_info_cache: TableInfoCacheRef,
45    table_name_cache: TableNameCacheRef,
46) -> Initializer<TableName, TableRef> {
47    Arc::new(move |table_name| {
48        let table_info_cache = table_info_cache.clone();
49        let table_name_cache = table_name_cache.clone();
50        Box::pin(async move {
51            let table_id = table_name_cache
52                .get_by_ref(table_name)
53                .await?
54                .context(ValueNotExistSnafu)?;
55            let table_info = table_info_cache
56                .get_by_ref(&table_id)
57                .await?
58                .context(ValueNotExistSnafu)?;
59
60            Ok(Some(DistTable::table(table_info)))
61        })
62    })
63}