Skip to main content

common_meta/cache/
flow.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 table_flownode;
16pub use table_flownode::{
17    TableFlownodeSetCache, TableFlownodeSetCacheRef, new_table_flownode_set_cache,
18};
19
20use std::collections::HashMap;
21use std::sync::Arc;
22
23use moka::future::Cache;
24
25use crate::cache::CacheContainer;
26use crate::instruction::CacheIdent;
27use crate::key::FlowId;
28use crate::key::flow::flow_info::{FlowInfoManager, FlowInfoValue};
29use crate::kv_backend::KvBackendRef;
30
31/// Caches flow definitions by flow ID.
32pub type FlowInfoCache = CacheContainer<FlowId, Arc<FlowInfoValue>, CacheIdent>;
33pub type FlowInfoCacheRef = Arc<FlowInfoCache>;
34
35/// Builds a cache for individual and batched flow lookups.
36pub fn new_flow_info_cache(
37    name: String,
38    cache: Cache<(usize, FlowId), Arc<FlowInfoValue>>,
39    backend: KvBackendRef,
40) -> FlowInfoCache {
41    let manager = Arc::new(FlowInfoManager::new(backend));
42    let single = manager.clone();
43    CacheContainer::new(
44        name,
45        cache,
46        Arc::new(move |id| {
47            let manager = single.clone();
48            Box::pin(async move { Ok(manager.get(*id).await?.map(Arc::new)) })
49        }),
50        CacheIdent::flow_id_key,
51    )
52    .with_batch_initializer(Arc::new(move |ids| {
53        let manager = manager.clone();
54        Box::pin(async move { load_shared_flow_infos(&manager, &ids).await })
55    }))
56}
57
58/// Loads each returned definition into an Arc shared by duplicate IDs in a scan.
59pub async fn load_shared_flow_infos(
60    manager: &FlowInfoManager,
61    ids: &[FlowId],
62) -> crate::error::Result<HashMap<FlowId, Arc<FlowInfoValue>>> {
63    manager
64        .batch_get(ids)
65        .await
66        .map(crate::cache::share_batch_values)
67}