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}
29
30fn puffin_metadata_weight(k: &str, v: &Arc<FileMetadata>) -> u32 {
31    (k.len() + v.memory_usage()) as u32
32}
33
34impl PuffinMetadataCache {
35    pub fn new(capacity: u64, cache_bytes: &'static IntGaugeVec) -> Self {
36        common_telemetry::debug!("Building PuffinMetadataCache with capacity: {capacity}");
37        Self {
38            cache: moka::sync::CacheBuilder::new(capacity)
39                .name("puffin_metadata")
40                .weigher(|k: &String, v| puffin_metadata_weight(k, v))
41                .eviction_listener(|k, v, _cause| {
42                    let size = puffin_metadata_weight(&k, &v);
43                    cache_bytes
44                        .with_label_values(&[PUFFIN_METADATA_TYPE])
45                        .sub(size.into());
46                })
47                .build(),
48        }
49    }
50
51    /// Gets the metadata from the cache.
52    pub fn get_metadata(&self, file_id: &str) -> Option<Arc<FileMetadata>> {
53        self.cache.get(file_id)
54    }
55
56    /// Puts the metadata into the cache.
57    pub fn put_metadata(&self, file_id: String, metadata: Arc<FileMetadata>) {
58        self.cache.insert(file_id, metadata);
59    }
60}