puffin/puffin_manager/
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 prometheus::IntGaugeVec;
18
19use crate::file_metadata::FileMetadata;
20/// Metrics for index metadata.
21const PUFFIN_METADATA_TYPE: &str = "puffin_metadata";
22
23pub type PuffinMetadataCacheRef = Arc<PuffinMetadataCache>;
24
25/// A cache for storing the metadata of the index files.
26pub struct PuffinMetadataCache {
27    cache: moka::sync::Cache<String, Arc<FileMetadata>>,
28    cache_bytes: IntGaugeVec,
29}
30
31fn puffin_metadata_weight(k: &str, v: &Arc<FileMetadata>) -> u32 {
32    (k.len() + v.memory_usage()) as u32
33}
34
35impl PuffinMetadataCache {
36    pub fn new(capacity: u64, cache_bytes: &'static IntGaugeVec) -> Self {
37        common_telemetry::debug!("Building PuffinMetadataCache with capacity: {capacity}");
38        Self {
39            cache: moka::sync::CacheBuilder::new(capacity)
40                .name("puffin_metadata")
41                .weigher(|k: &String, v| puffin_metadata_weight(k, v))
42                .eviction_listener(move |k, v, _cause| {
43                    let size = puffin_metadata_weight(&k, &v);
44                    cache_bytes
45                        .with_label_values(&[PUFFIN_METADATA_TYPE])
46                        .sub(size.into());
47                })
48                .build(),
49            cache_bytes: cache_bytes.clone(),
50        }
51    }
52
53    /// Gets the metadata from the cache.
54    pub fn get_metadata(&self, file_id: &str) -> Option<Arc<FileMetadata>> {
55        self.cache.get(file_id)
56    }
57
58    /// Puts the metadata into the cache.
59    pub fn put_metadata(&self, file_id: String, metadata: Arc<FileMetadata>) {
60        let size = puffin_metadata_weight(&file_id, &metadata);
61        self.cache_bytes
62            .with_label_values(&[PUFFIN_METADATA_TYPE])
63            .add(size.into());
64        self.cache.insert(file_id, metadata);
65    }
66
67    /// Removes the metadata of the given file from the cache, if present.
68    pub fn remove(&self, file_id: &str) {
69        self.cache.invalidate(file_id);
70    }
71}