common_meta/cache/table/
table_schema.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
15//! Cache for table id to schema name mapping.
16
17use std::sync::Arc;
18
19use futures_util::future::BoxFuture;
20use moka::future::Cache;
21use snafu::OptionExt;
22use store_api::storage::TableId;
23
24use crate::cache::{CacheContainer, Initializer};
25use crate::error;
26use crate::instruction::CacheIdent;
27use crate::key::schema_name::SchemaName;
28use crate::key::table_info::TableInfoManager;
29use crate::kv_backend::KvBackendRef;
30
31pub type TableSchemaCache = CacheContainer<TableId, Arc<SchemaName>, CacheIdent>;
32pub type TableSchemaCacheRef = Arc<TableSchemaCache>;
33
34/// Constructs a [TableSchemaCache].
35pub fn new_table_schema_cache(
36    name: String,
37    cache: Cache<TableId, Arc<SchemaName>>,
38    kv_backend: KvBackendRef,
39) -> TableSchemaCache {
40    let table_info_manager = TableInfoManager::new(kv_backend);
41    let init = init_factory(table_info_manager);
42
43    CacheContainer::new(name, cache, Box::new(invalidator), init, filter)
44}
45
46fn init_factory(table_info_manager: TableInfoManager) -> Initializer<TableId, Arc<SchemaName>> {
47    Arc::new(move |table_id| {
48        let table_info_manager = table_info_manager.clone();
49        Box::pin(async move {
50            let raw_table_info = table_info_manager
51                .get(*table_id)
52                .await?
53                .context(error::ValueNotExistSnafu)?
54                .into_inner()
55                .table_info;
56
57            Ok(Some(Arc::new(SchemaName {
58                catalog_name: raw_table_info.catalog_name,
59                schema_name: raw_table_info.schema_name,
60            })))
61        })
62    })
63}
64
65/// Never invalidates table id schema cache.
66fn invalidator<'a>(
67    _cache: &'a Cache<TableId, Arc<SchemaName>>,
68    _ident: &'a CacheIdent,
69) -> BoxFuture<'a, error::Result<()>> {
70    Box::pin(std::future::ready(Ok(())))
71}
72
73/// Never invalidates table id schema cache.
74fn filter(_ident: &CacheIdent) -> bool {
75    false
76}