Skip to main content

mito2/cache/
file_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
15//! A cache for files.
16
17use std::fmt;
18use std::ops::Range;
19use std::sync::Arc;
20use std::time::{Duration, Instant};
21
22use bytes::Bytes;
23use common_base::readable_size::ReadableSize;
24use common_runtime::Runtime;
25use common_telemetry::{debug, error, info, warn};
26use futures::{AsyncWriteExt, FutureExt, TryStreamExt};
27use moka::future::Cache;
28use moka::notification::RemovalCause;
29use moka::policy::EvictionPolicy;
30use object_store::util::join_path;
31use object_store::{ErrorKind, ObjectStore, Reader};
32use parquet::file::metadata::{PageIndexPolicy, ParquetMetaData};
33use snafu::ResultExt;
34use store_api::storage::{FileId, RegionId};
35use tokio::sync::mpsc::{Sender, UnboundedReceiver};
36
37use crate::access_layer::TempFileCleaner;
38use crate::cache::{
39    CachedSstMeta, FILE_TYPE, INDEX_TYPE, SstMetaPreparation, decode_sst_meta, prepare_sst_meta,
40};
41use crate::error::{self, OpenDalSnafu, Result};
42use crate::metrics::{
43    CACHE_BYTES, CACHE_HIT, CACHE_MISS, WRITE_CACHE_DOWNLOAD_BYTES_TOTAL,
44    WRITE_CACHE_DOWNLOAD_ELAPSED,
45};
46use crate::region::opener::RegionLoadCacheTask;
47use crate::sst::parquet::helper::fetch_byte_ranges;
48use crate::sst::parquet::metadata::MetadataLoader;
49use crate::sst::parquet::reader::MetadataCacheMetrics;
50
51/// Subdirectory of cached files for write.
52///
53/// This must contain three layers, corresponding to [`build_prometheus_metrics_layer`](object_store::layers::build_prometheus_metrics_layer).
54const FILE_DIR: &str = "cache/object/write/";
55
56/// Default percentage for index (puffin) cache (20% of total capacity).
57pub(crate) const DEFAULT_INDEX_CACHE_PERCENT: u8 = 20;
58
59/// Minimum capacity for each cache (512MB).
60const MIN_CACHE_CAPACITY: u64 = 512 * 1024 * 1024;
61
62/// Channel capacity for background download tasks.
63const DOWNLOAD_TASK_CHANNEL_SIZE: usize = 64;
64
65/// A task to download a file in the background.
66struct DownloadTask {
67    _pin: Option<crate::sst::file::FileHandle>,
68    index_key: IndexKey,
69    remote_path: String,
70    remote_store: ObjectStore,
71    file_size: u64,
72}
73
74/// Inner struct for FileCache that can be used in spawned tasks.
75#[derive(Debug)]
76struct FileCacheInner {
77    /// Local store to cache files.
78    local_store: ObjectStore,
79    /// Index to track cached Parquet files.
80    parquet_index: Cache<IndexKey, IndexValue>,
81    /// Index to track cached Puffin files.
82    puffin_index: Cache<IndexKey, IndexValue>,
83}
84
85impl FileCacheInner {
86    /// Returns the appropriate memory index for the given file type.
87    fn memory_index(&self, file_type: FileType) -> &Cache<IndexKey, IndexValue> {
88        match file_type {
89            FileType::Parquet | FileType::Samples(_) => &self.parquet_index,
90            FileType::Puffin(_) | FileType::Series(_) => &self.puffin_index,
91        }
92    }
93
94    /// Returns the cache file path for the key.
95    fn cache_file_path(&self, key: IndexKey) -> String {
96        cache_file_path(FILE_DIR, key)
97    }
98
99    /// Puts a file into the cache index.
100    ///
101    /// The `WriteCache` should ensure the file is in the correct path.
102    async fn put(&self, key: IndexKey, value: IndexValue) {
103        CACHE_BYTES
104            .with_label_values(&[key.file_type.metric_label()])
105            .add(value.file_size.into());
106        let index = self.memory_index(key.file_type);
107        index.insert(key, value).await;
108
109        // Since files are large items, we run the pending tasks immediately.
110        index.run_pending_tasks().await;
111    }
112
113    /// Recovers the index from local store.
114    async fn recover(&self) -> Result<()> {
115        let now = Instant::now();
116        let mut lister = self
117            .local_store
118            .lister_with(FILE_DIR)
119            .await
120            .context(OpenDalSnafu)?;
121        // Use i64 for total_size to reduce the risk of overflow.
122        // It is possible that the total size of the cache is larger than i32::MAX.
123        let (mut total_size, mut total_keys) = (0i64, 0);
124        let (mut parquet_size, mut puffin_size) = (0i64, 0i64);
125        while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? {
126            let meta = entry.metadata();
127            if !meta.is_file() {
128                continue;
129            }
130            let Some(key) = parse_index_key(entry.name()) else {
131                continue;
132            };
133
134            let meta = self
135                .local_store
136                .stat(entry.path())
137                .await
138                .context(OpenDalSnafu)?;
139            let file_size = meta.content_length() as u32;
140            let index = self.memory_index(key.file_type);
141            index.insert(key, IndexValue { file_size }).await;
142            let size = i64::from(file_size);
143            total_size += size;
144            total_keys += 1;
145
146            // Track sizes separately for each file type
147            match key.file_type {
148                FileType::Parquet | FileType::Samples(_) => parquet_size += size,
149                FileType::Puffin(_) | FileType::Series(_) => puffin_size += size,
150            }
151        }
152        // The metrics is a signed int gauge so we can updates it finally.
153        CACHE_BYTES
154            .with_label_values(&[FILE_TYPE])
155            .add(parquet_size);
156        CACHE_BYTES
157            .with_label_values(&[INDEX_TYPE])
158            .add(puffin_size);
159
160        // Run all pending tasks of the moka cache so that the cache size is updated
161        // and the eviction policy is applied.
162        self.parquet_index.run_pending_tasks().await;
163        self.puffin_index.run_pending_tasks().await;
164
165        let parquet_weight = self.parquet_index.weighted_size();
166        let parquet_count = self.parquet_index.entry_count();
167        let puffin_weight = self.puffin_index.weighted_size();
168        let puffin_count = self.puffin_index.entry_count();
169        info!(
170            "Recovered file cache, num_keys: {}, num_bytes: {}, parquet(count: {}, weight: {}), puffin(count: {}, weight: {}), cost: {:?}",
171            total_keys,
172            total_size,
173            parquet_count,
174            parquet_weight,
175            puffin_count,
176            puffin_weight,
177            now.elapsed()
178        );
179        Ok(())
180    }
181
182    /// Downloads a file without cleaning up on error.
183    async fn download_without_cleaning(
184        &self,
185        index_key: IndexKey,
186        remote_path: &str,
187        remote_store: &ObjectStore,
188        file_size: u64,
189        concurrency: usize,
190    ) -> Result<()> {
191        const DOWNLOAD_READER_CHUNK_SIZE: ReadableSize = ReadableSize::mb(8);
192
193        let file_type = index_key.file_type;
194        let timer = WRITE_CACHE_DOWNLOAD_ELAPSED
195            .with_label_values(&[match file_type {
196                FileType::Parquet => "download_parquet",
197                FileType::Series(_) => "download_series",
198                FileType::Samples(_) => "download_samples",
199                FileType::Puffin { .. } => "download_puffin",
200            }])
201            .start_timer();
202
203        let reader = remote_store
204            .reader_with(remote_path)
205            .concurrent(concurrency)
206            .chunk(DOWNLOAD_READER_CHUNK_SIZE.as_bytes() as usize)
207            .await
208            .context(error::OpenDalSnafu)?
209            .into_futures_async_read(0..file_size)
210            .await
211            .context(error::OpenDalSnafu)?;
212
213        let cache_path = self.cache_file_path(index_key);
214        let mut writer = self
215            .local_store
216            .writer(&cache_path)
217            .await
218            .context(error::OpenDalSnafu)?
219            .into_futures_async_write();
220
221        let region_id = index_key.region_id;
222        let file_id = index_key.file_id;
223        let bytes_written =
224            futures::io::copy(reader, &mut writer)
225                .await
226                .context(error::DownloadSnafu {
227                    region_id,
228                    file_id,
229                    file_type,
230                })?;
231        writer.close().await.context(error::DownloadSnafu {
232            region_id,
233            file_id,
234            file_type,
235        })?;
236
237        WRITE_CACHE_DOWNLOAD_BYTES_TOTAL.inc_by(bytes_written);
238
239        let elapsed = timer.stop_and_record();
240        debug!(
241            "Successfully download file '{}' to local '{}', file size: {}, region: {}, cost: {:?}s",
242            remote_path, cache_path, bytes_written, region_id, elapsed,
243        );
244
245        let index_value = IndexValue {
246            file_size: bytes_written as _,
247        };
248        self.put(index_key, index_value).await;
249        Ok(())
250    }
251
252    /// Downloads a file from remote store to local cache.
253    async fn download(
254        &self,
255        index_key: IndexKey,
256        remote_path: &str,
257        remote_store: &ObjectStore,
258        file_size: u64,
259        concurrency: usize,
260    ) -> Result<()> {
261        if let Err(e) = self
262            .download_without_cleaning(index_key, remote_path, remote_store, file_size, concurrency)
263            .await
264        {
265            error!(e; "Failed to download file '{}' for region {}", remote_path, index_key.region_id);
266
267            let filename = index_key.to_string();
268            TempFileCleaner::clean_atomic_dir_files(&self.local_store, &[&filename]).await;
269
270            return Err(e);
271        }
272
273        Ok(())
274    }
275
276    /// Checks if the key is in the file cache.
277    fn contains_key(&self, key: &IndexKey) -> bool {
278        self.memory_index(key.file_type).contains_key(key)
279    }
280}
281
282/// A file cache manages files on local store and evict files based
283/// on size.
284#[derive(Debug, Clone)]
285pub(crate) struct FileCache {
286    /// Inner cache state shared with background worker.
287    inner: Arc<FileCacheInner>,
288    /// Capacity of the puffin (index) cache in bytes.
289    puffin_capacity: u64,
290    /// Channel for background download tasks. None if background worker is disabled.
291    download_task_tx: Option<Sender<DownloadTask>>,
292}
293
294pub(crate) type FileCacheRef = Arc<FileCache>;
295
296impl FileCache {
297    /// Splits the configured total capacity between parquet and puffin caches
298    /// without exceeding the requested overall budget.
299    fn split_cache_capacities(total_capacity: u64, index_percent: u8) -> (u64, u64) {
300        let desired_puffin_capacity = total_capacity * u64::from(index_percent) / 100;
301        let min_cache_capacity = MIN_CACHE_CAPACITY.min(total_capacity / 2);
302        let puffin_capacity =
303            desired_puffin_capacity.clamp(min_cache_capacity, total_capacity - min_cache_capacity);
304        let parquet_capacity = total_capacity - puffin_capacity;
305        (parquet_capacity, puffin_capacity)
306    }
307
308    /// Creates a new file cache.
309    pub(crate) fn new(
310        local_store: ObjectStore,
311        capacity: ReadableSize,
312        ttl: Option<Duration>,
313        index_cache_percent: Option<u8>,
314        enable_background_worker: bool,
315    ) -> FileCache {
316        // Validate and use the provided percent or default
317        let index_percent = index_cache_percent
318            .filter(|&percent| percent > 0 && percent < 100)
319            .unwrap_or(DEFAULT_INDEX_CACHE_PERCENT);
320        let total_capacity = capacity.as_bytes();
321
322        let (parquet_capacity, puffin_capacity) =
323            Self::split_cache_capacities(total_capacity, index_percent);
324
325        info!(
326            "Initializing file cache with index_percent: {}%, total_capacity: {}, parquet_capacity: {}, puffin_capacity: {}",
327            index_percent,
328            ReadableSize(total_capacity),
329            ReadableSize(parquet_capacity),
330            ReadableSize(puffin_capacity)
331        );
332
333        let parquet_index = Self::build_cache(local_store.clone(), parquet_capacity, ttl, "file");
334        let puffin_index = Self::build_cache(local_store.clone(), puffin_capacity, ttl, "index");
335
336        // Create inner cache shared with background worker
337        let inner = Arc::new(FileCacheInner {
338            local_store,
339            parquet_index,
340            puffin_index,
341        });
342
343        // Only create channel and spawn worker if background download is enabled
344        let download_task_tx = if enable_background_worker {
345            let (tx, rx) = tokio::sync::mpsc::channel(DOWNLOAD_TASK_CHANNEL_SIZE);
346            Self::spawn_download_worker(inner.clone(), rx);
347            Some(tx)
348        } else {
349            None
350        };
351
352        FileCache {
353            inner,
354            puffin_capacity,
355            download_task_tx,
356        }
357    }
358
359    /// Spawns a background worker to process download tasks.
360    fn spawn_download_worker(
361        inner: Arc<FileCacheInner>,
362        mut download_task_rx: tokio::sync::mpsc::Receiver<DownloadTask>,
363    ) {
364        tokio::spawn(async move {
365            info!("Background download worker started");
366            while let Some(task) = download_task_rx.recv().await {
367                // Check if the file is already in the cache
368                if inner.contains_key(&task.index_key) {
369                    debug!(
370                        "Skipping background download for region {}, file {} - already in cache",
371                        task.index_key.region_id, task.index_key.file_id
372                    );
373                    continue;
374                }
375
376                // Ignores background download errors.
377                let _ = inner
378                    .download(
379                        task.index_key,
380                        &task.remote_path,
381                        &task.remote_store,
382                        task.file_size,
383                        1, // Background downloads use concurrency=1
384                    )
385                    .await;
386            }
387            info!("Background download worker stopped");
388        });
389    }
390
391    /// Builds a cache for a specific file type.
392    fn build_cache(
393        local_store: ObjectStore,
394        capacity: u64,
395        ttl: Option<Duration>,
396        label: &'static str,
397    ) -> Cache<IndexKey, IndexValue> {
398        let cache_store = local_store;
399        let mut builder = Cache::builder()
400            .eviction_policy(EvictionPolicy::lru())
401            .weigher(|_key, value: &IndexValue| -> u32 {
402                // We only measure space on local store.
403                value.file_size
404            })
405            .max_capacity(capacity)
406            .async_eviction_listener(move |key, value, cause| {
407                let store = cache_store.clone();
408                // Stores files under FILE_DIR.
409                let file_path = cache_file_path(FILE_DIR, *key);
410                async move {
411                    if let RemovalCause::Replaced = cause {
412                        // The cache is replaced by another file (maybe download again). We don't remove the same
413                        // file but updates the metrics as the file is already replaced by users.
414                        CACHE_BYTES.with_label_values(&[label]).sub(value.file_size.into());
415                        return;
416                    }
417
418                    match store.delete(&file_path).await {
419                        Ok(()) => {
420                            CACHE_BYTES.with_label_values(&[label]).sub(value.file_size.into());
421                        }
422                        Err(e) => {
423                            warn!(e; "Failed to delete cached file {} for region {}", file_path, key.region_id);
424                        }
425                    }
426                }
427                .boxed()
428            });
429        if let Some(ttl) = ttl {
430            builder = builder.time_to_idle(ttl);
431        }
432        builder.build()
433    }
434
435    /// Puts a file into the cache index.
436    ///
437    /// The `WriteCache` should ensure the file is in the correct path.
438    pub(crate) async fn put(&self, key: IndexKey, value: IndexValue) {
439        self.inner.put(key, value).await
440    }
441
442    pub(crate) async fn get(&self, key: IndexKey) -> Option<IndexValue> {
443        self.inner.memory_index(key.file_type).get(&key).await
444    }
445
446    /// Reads a file from the cache.
447    #[allow(unused)]
448    pub(crate) async fn reader(&self, key: IndexKey) -> Option<Reader> {
449        // We must use `get()` to update the estimator of the cache.
450        // See https://docs.rs/moka/latest/moka/future/struct.Cache.html#method.contains_key
451        let index = self.inner.memory_index(key.file_type);
452        if index.get(&key).await.is_none() {
453            CACHE_MISS
454                .with_label_values(&[key.file_type.metric_label()])
455                .inc();
456            return None;
457        }
458
459        let file_path = self.inner.cache_file_path(key);
460        match self.get_reader(&file_path).await {
461            Ok(Some(reader)) => {
462                CACHE_HIT
463                    .with_label_values(&[key.file_type.metric_label()])
464                    .inc();
465                return Some(reader);
466            }
467            Err(e) => {
468                if e.kind() != ErrorKind::NotFound {
469                    warn!(e; "Failed to get file for key {:?}", key);
470                }
471            }
472            Ok(None) => {}
473        }
474
475        // We removes the file from the index.
476        index.remove(&key).await;
477        CACHE_MISS
478            .with_label_values(&[key.file_type.metric_label()])
479            .inc();
480        None
481    }
482
483    /// Reads ranges from the cache.
484    pub(crate) async fn read_ranges(
485        &self,
486        key: IndexKey,
487        ranges: &[Range<u64>],
488    ) -> Option<Vec<Bytes>> {
489        let index = self.inner.memory_index(key.file_type);
490        if index.get(&key).await.is_none() {
491            CACHE_MISS
492                .with_label_values(&[key.file_type.metric_label()])
493                .inc();
494            return None;
495        }
496
497        let file_path = self.inner.cache_file_path(key);
498        // In most cases, it will use blocking read,
499        // because FileCache is normally based on local file system, which supports blocking read.
500        // The samples reader coalesces and reserves its own I/O windows.
501        let bytes_result = if matches!(key.file_type, FileType::Samples(_)) {
502            crate::sst::parquet::helper::fetch_byte_ranges_with_gap(
503                &file_path,
504                self.inner.local_store.clone(),
505                ranges,
506                0,
507            )
508            .await
509        } else {
510            fetch_byte_ranges(&file_path, self.inner.local_store.clone(), ranges).await
511        };
512        match bytes_result {
513            Ok(bytes)
514                if bytes.len() == ranges.len()
515                    && bytes
516                        .iter()
517                        .zip(ranges)
518                        .all(|(b, r)| b.len() as u64 == r.end - r.start) =>
519            {
520                CACHE_HIT
521                    .with_label_values(&[key.file_type.metric_label()])
522                    .inc();
523                Some(bytes)
524            }
525            result => {
526                if let Err(e) = result
527                    && e.kind() != ErrorKind::NotFound
528                {
529                    warn!(e; "Failed to get file for key {:?}", key);
530                }
531
532                // We removes the file from the index.
533                index.remove(&key).await;
534                CACHE_MISS
535                    .with_label_values(&[key.file_type.metric_label()])
536                    .inc();
537                None
538            }
539        }
540    }
541
542    /// Removes a file from the cache explicitly.
543    /// It always tries to remove the file from the local store because we may not have the file
544    /// in the memory index if upload is failed.
545    pub(crate) async fn remove(&self, key: IndexKey) {
546        let file_path = self.inner.cache_file_path(key);
547        self.inner.memory_index(key.file_type).remove(&key).await;
548        // Always delete the file from the local store.
549        if let Err(e) = self.inner.local_store.delete(&file_path).await {
550            warn!(e; "Failed to delete a cached file {}", file_path);
551        }
552    }
553
554    /// Recovers the index from local store.
555    ///
556    /// If `task_receiver` is provided, spawns a background task after recovery
557    /// to process `RegionLoadCacheTask` messages for loading files into the cache.
558    pub(crate) async fn recover(
559        &self,
560        sync: bool,
561        task_receiver: Option<UnboundedReceiver<RegionLoadCacheTask>>,
562    ) {
563        let moved_self = self.clone();
564        let handle = tokio::spawn(async move {
565            if let Err(err) = moved_self.inner.recover().await {
566                error!(err; "Failed to recover file cache.")
567            }
568
569            // Spawns background task to process region load cache tasks after recovery.
570            // So it won't block the recovery when `sync` is true.
571            if let Some(mut receiver) = task_receiver {
572                info!("Spawning background task for processing region load cache tasks");
573                tokio::spawn(async move {
574                    while let Some(task) = receiver.recv().await {
575                        task.fill_cache(&moved_self).await;
576                    }
577                    info!("Background task for processing region load cache tasks stopped");
578                });
579            }
580        });
581
582        if sync {
583            let _ = handle.await;
584        }
585    }
586
587    /// Returns the cache file path for the key.
588    pub(crate) fn cache_file_path(&self, key: IndexKey) -> String {
589        self.inner.cache_file_path(key)
590    }
591
592    /// Returns the local store of the file cache.
593    pub(crate) fn local_store(&self) -> ObjectStore {
594        self.inner.local_store.clone()
595    }
596
597    /// Get the parquet metadata in file cache.
598    /// If the file is not in the cache or fail to load metadata, return None.
599    pub(crate) async fn get_parquet_meta_data(
600        &self,
601        key: IndexKey,
602        cache_metrics: &mut MetadataCacheMetrics,
603        page_index_policy: PageIndexPolicy,
604    ) -> Option<ParquetMetaData> {
605        // Check if file cache contains the key
606        if let Some(index_value) = self.inner.parquet_index.get(&key).await {
607            // Load metadata from file cache
608            let local_store = self.local_store();
609            let file_path = self.inner.cache_file_path(key);
610            let file_size = index_value.file_size as u64;
611            let mut metadata_loader = MetadataLoader::new(local_store, &file_path, file_size);
612            metadata_loader.with_page_index_policy(page_index_policy);
613
614            match metadata_loader.load(cache_metrics).await {
615                Ok(metadata) => {
616                    CACHE_HIT
617                        .with_label_values(&[key.file_type.metric_label()])
618                        .inc();
619                    Some(metadata)
620                }
621                Err(e) => {
622                    if !e.is_object_not_found() {
623                        warn!(
624                            e; "Failed to get parquet metadata for key {:?}",
625                            key
626                        );
627                    }
628                    // We removes the file from the index.
629                    self.inner.parquet_index.remove(&key).await;
630                    CACHE_MISS
631                        .with_label_values(&[key.file_type.metric_label()])
632                        .inc();
633                    None
634                }
635            }
636        } else {
637            CACHE_MISS
638                .with_label_values(&[key.file_type.metric_label()])
639                .inc();
640            None
641        }
642    }
643
644    /// Get fused SST metadata from the file cache.
645    /// If the file is not in the cache, or metadata loading/decoding fails, return None.
646    /// Compact cache encoding failures return decoded-only metadata to the caller.
647    pub(crate) async fn get_sst_meta_data(
648        &self,
649        key: IndexKey,
650        cache_metrics: &mut MetadataCacheMetrics,
651        page_index_policy: PageIndexPolicy,
652        runtime: &Runtime,
653    ) -> Option<SstMetaPreparation> {
654        let file_path = self.inner.cache_file_path(key);
655        let metadata = self
656            .get_parquet_meta_data(key, cache_metrics, page_index_policy)
657            .await?;
658        match prepare_sst_meta(&file_path, metadata, None, page_index_policy, runtime).await {
659            Ok(metadata) => Some(metadata),
660            Err(err) => {
661                CACHE_MISS
662                    .with_label_values(&[key.file_type.metric_label()])
663                    .inc();
664                warn!(
665                    err; "Failed to prepare cached parquet metadata for key {:?}",
666                    key
667                );
668                None
669            }
670        }
671    }
672
673    /// Gets decoded SST metadata without preparing an in-memory cache entry.
674    pub(crate) async fn get_decoded_sst_meta_data(
675        &self,
676        key: IndexKey,
677        cache_metrics: &mut MetadataCacheMetrics,
678        page_index_policy: PageIndexPolicy,
679        runtime: &Runtime,
680    ) -> Option<Arc<CachedSstMeta>> {
681        let file_path = self.inner.cache_file_path(key);
682        let metadata = self
683            .get_parquet_meta_data(key, cache_metrics, page_index_policy)
684            .await?;
685        match decode_sst_meta(&file_path, metadata, None, page_index_policy, runtime).await {
686            Ok(metadata) => Some(metadata),
687            Err(err) => {
688                CACHE_MISS
689                    .with_label_values(&[key.file_type.metric_label()])
690                    .inc();
691                warn!(
692                    err; "Failed to decode cached parquet metadata for key {:?}",
693                    key
694                );
695                None
696            }
697        }
698    }
699
700    async fn get_reader(&self, file_path: &str) -> object_store::Result<Option<Reader>> {
701        if self.inner.local_store.exists(file_path).await? {
702            Ok(Some(self.inner.local_store.reader(file_path).await?))
703        } else {
704            Ok(None)
705        }
706    }
707
708    /// Checks if the key is in the file cache.
709    pub(crate) fn contains_key(&self, key: &IndexKey) -> bool {
710        self.inner.contains_key(key)
711    }
712
713    pub(crate) fn can_retain(&self, key: IndexKey, size: u64) -> bool {
714        size <= self
715            .inner
716            .memory_index(key.file_type)
717            .policy()
718            .max_capacity()
719            .unwrap_or(0)
720    }
721
722    /// Returns the capacity of the puffin (index) cache in bytes.
723    pub(crate) fn puffin_cache_capacity(&self) -> u64 {
724        self.puffin_capacity
725    }
726
727    /// Returns the current weighted size (used bytes) of the puffin (index) cache.
728    pub(crate) fn puffin_cache_size(&self) -> u64 {
729        self.inner.puffin_index.weighted_size()
730    }
731
732    /// Downloads the target file into write cache only when it is not cached.
733    ///
734    /// Returns `Ok(true)` if this call performs a download, or `Ok(false)` if the
735    /// file is already present in write cache and download is skipped.
736    pub(crate) async fn download_if_absent(
737        &self,
738        index_key: IndexKey,
739        remote_path: &str,
740        remote_store: &ObjectStore,
741        file_size: u64,
742    ) -> Result<bool> {
743        if self.contains_key(&index_key) {
744            debug!(
745                "Skip downloading file already in write cache, region: {}, file: {}",
746                index_key.region_id, index_key.file_id
747            );
748            return Ok(false);
749        }
750
751        self.download(index_key, remote_path, remote_store, file_size)
752            .await?;
753        Ok(true)
754    }
755
756    /// Downloads a file in `remote_path` from the remote object store to the local cache
757    /// (specified by `index_key`).
758    pub(crate) async fn download(
759        &self,
760        index_key: IndexKey,
761        remote_path: &str,
762        remote_store: &ObjectStore,
763        file_size: u64,
764    ) -> Result<()> {
765        self.inner
766            .download(index_key, remote_path, remote_store, file_size, 8) // Foreground uses concurrency=8
767            .await
768    }
769
770    /// Downloads a file in `remote_path` from the remote object store to the local cache
771    /// (specified by `index_key`) in the background. Errors are logged but not returned.
772    ///
773    /// This method attempts to send a download task to the background worker.
774    /// If the channel is full, the task is silently dropped.
775    pub(crate) fn maybe_download_background(
776        &self,
777        index_key: IndexKey,
778        remote_path: String,
779        remote_store: ObjectStore,
780        file_size: u64,
781    ) {
782        self.queue_download(index_key, remote_path, remote_store, file_size, None);
783    }
784
785    pub(crate) fn queue_download(
786        &self,
787        index_key: IndexKey,
788        remote_path: String,
789        remote_store: ObjectStore,
790        file_size: u64,
791        pin: Option<crate::sst::file::FileHandle>,
792    ) {
793        // Do nothing if background worker is disabled (channel is None)
794        let Some(tx) = &self.download_task_tx else {
795            return;
796        };
797
798        if !self.can_retain(index_key, file_size) {
799            return;
800        }
801        let task = DownloadTask {
802            _pin: pin,
803            index_key,
804            remote_path,
805            remote_store,
806            file_size,
807        };
808
809        // Try to send the task; if the channel is full, just drop it
810        if let Err(e) = tx.try_send(task) {
811            debug!(
812                "Failed to queue background download task for region {}, file {}: {:?}",
813                index_key.region_id, index_key.file_id, e
814            );
815        }
816    }
817}
818
819/// Key of file cache index.
820#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
821pub struct IndexKey {
822    pub region_id: RegionId,
823    pub file_id: FileId,
824    pub file_type: FileType,
825}
826
827impl IndexKey {
828    /// The Narthex inventory ends with its manifest; all preceding objects are in part-ID order.
829    pub(crate) fn narthex_objects(
830        file: &crate::sst::file::FileMeta,
831        region_dir: &str,
832    ) -> Vec<(Self, crate::series_index::artifact::ArtifactObject)> {
833        let Some(objects) = file.narthex_objects(region_dir) else {
834            return Vec::new();
835        };
836        let manifest_index = objects.len() - 1;
837        objects
838            .into_iter()
839            .enumerate()
840            .map(|(i, object)| {
841                let part = (i != manifest_index).then_some(i as u32);
842                let kind = match &file.format {
843                    crate::sst::file::FileFormat::NarthexSamples(_) => FileType::Samples(part),
844                    crate::sst::file::FileFormat::NarthexSeriesIndex(_) => FileType::Series(part),
845                    _ => unreachable!(),
846                };
847                (Self::new(file.region_id, file.file_id, kind), object)
848            })
849            .collect()
850    }
851
852    /// Creates a new index key.
853    pub fn new(region_id: RegionId, file_id: FileId, file_type: FileType) -> IndexKey {
854        IndexKey {
855            region_id,
856            file_id,
857            file_type,
858        }
859    }
860}
861
862impl fmt::Display for IndexKey {
863    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864        write!(
865            f,
866            "{}.{}.{}",
867            self.region_id.as_u64(),
868            self.file_id,
869            self.file_type
870        )
871    }
872}
873
874/// Type of the file.
875#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
876pub enum FileType {
877    /// Parquet file.
878    Parquet,
879    /// Puffin file.
880    Puffin(u64),
881    /// Immutable part, or the manifest when the part ID is absent.
882    Series(Option<u32>),
883    Samples(Option<u32>),
884}
885
886impl From<crate::sst::location::SstObjectType> for FileType {
887    fn from(kind: crate::sst::location::SstObjectType) -> Self {
888        match kind {
889            crate::sst::location::SstObjectType::Parquet => Self::Parquet,
890            crate::sst::location::SstObjectType::Puffin(version) => Self::Puffin(version),
891        }
892    }
893}
894
895impl fmt::Display for FileType {
896    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897        match self {
898            FileType::Samples(None) => f.write_str("samples"),
899            FileType::Series(None) => f.write_str("series"),
900            FileType::Samples(Some(part)) => write!(f, "{part}.samples"),
901            FileType::Series(Some(part)) => write!(f, "{part}.series"),
902            FileType::Parquet => write!(f, "parquet"),
903            FileType::Puffin(version) => write!(f, "{}.puffin", version),
904        }
905    }
906}
907
908impl FileType {
909    /// Parses the file type from string.
910    pub(crate) fn parse(s: &str) -> Option<FileType> {
911        match s {
912            "series" => Some(Self::Series(None)),
913            "samples" => Some(Self::Samples(None)),
914            _ if s.ends_with(".series") => {
915                Some(Self::Series(Some(s.strip_suffix(".series")?.parse().ok()?)))
916            }
917            _ if s.ends_with(".samples") => Some(Self::Samples(Some(
918                s.strip_suffix(".samples")?.parse().ok()?,
919            ))),
920            other => crate::sst::location::SstObjectType::parse(other).map(Self::from),
921        }
922    }
923
924    /// Returns the metric label for this file type.
925    fn metric_label(&self) -> &'static str {
926        match self {
927            FileType::Parquet | FileType::Samples(_) => FILE_TYPE,
928            FileType::Puffin(_) | FileType::Series(_) => INDEX_TYPE,
929        }
930    }
931}
932
933/// An entity that describes the file in the file cache.
934///
935/// It should only keep minimal information needed by the cache.
936#[derive(Debug, Clone)]
937pub(crate) struct IndexValue {
938    /// Size of the file in bytes.
939    pub(crate) file_size: u32,
940}
941
942/// Generates the path to the cached file.
943///
944/// The file name format is `{region_id}.{file_id}.{file_type}`
945fn cache_file_path(cache_file_dir: &str, key: IndexKey) -> String {
946    join_path(cache_file_dir, &key.to_string())
947}
948
949/// Parse index key from the file name.
950fn parse_index_key(name: &str) -> Option<IndexKey> {
951    let mut split = name.splitn(3, '.');
952    let region_id = split.next().and_then(|s| {
953        let id = s.parse::<u64>().ok()?;
954        Some(RegionId::from_u64(id))
955    })?;
956    let file_id = split.next().and_then(|s| FileId::parse_str(s).ok())?;
957    let file_type = split.next().and_then(FileType::parse)?;
958
959    Some(IndexKey::new(region_id, file_id, file_type))
960}
961
962#[cfg(test)]
963mod tests {
964    use common_test_util::temp_dir::create_temp_dir;
965    use object_store::services::Fs;
966
967    use super::*;
968
969    fn new_fs_store(path: &str) -> ObjectStore {
970        let builder = Fs::default().root(path);
971        ObjectStore::new(builder).unwrap()
972    }
973
974    #[tokio::test]
975    async fn test_file_cache_ttl() {
976        let dir = create_temp_dir("");
977        let local_store = new_fs_store(dir.path().to_str().unwrap());
978
979        let cache = FileCache::new(
980            local_store.clone(),
981            ReadableSize::mb(10),
982            Some(Duration::from_millis(10)),
983            None,
984            true, // enable_background_worker
985        );
986        let region_id = RegionId::new(2000, 0);
987        let file_id = FileId::random();
988        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
989        let file_path = cache.cache_file_path(key);
990
991        // Get an empty file.
992        assert!(cache.reader(key).await.is_none());
993
994        // Write a file.
995        local_store
996            .write(&file_path, b"hello".as_slice())
997            .await
998            .unwrap();
999
1000        // Add to the cache.
1001        cache
1002            .put(
1003                IndexKey::new(region_id, file_id, FileType::Parquet),
1004                IndexValue { file_size: 5 },
1005            )
1006            .await;
1007
1008        let exist = cache.reader(key).await;
1009        assert!(exist.is_some());
1010        tokio::time::sleep(Duration::from_millis(15)).await;
1011        cache.inner.parquet_index.run_pending_tasks().await;
1012        let non = cache.reader(key).await;
1013        assert!(non.is_none());
1014    }
1015
1016    #[tokio::test]
1017    async fn test_file_cache_basic() {
1018        let dir = create_temp_dir("");
1019        let local_store = new_fs_store(dir.path().to_str().unwrap());
1020
1021        let cache = FileCache::new(
1022            local_store.clone(),
1023            ReadableSize::mb(10),
1024            None,
1025            None,
1026            true, // enable_background_worker
1027        );
1028        let region_id = RegionId::new(2000, 0);
1029        let file_id = FileId::random();
1030        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
1031        let file_path = cache.cache_file_path(key);
1032
1033        // Get an empty file.
1034        assert!(cache.reader(key).await.is_none());
1035
1036        // Write a file.
1037        local_store
1038            .write(&file_path, b"hello".as_slice())
1039            .await
1040            .unwrap();
1041        // Add to the cache.
1042        cache
1043            .put(
1044                IndexKey::new(region_id, file_id, FileType::Parquet),
1045                IndexValue { file_size: 5 },
1046            )
1047            .await;
1048
1049        // Read file content.
1050        let reader = cache.reader(key).await.unwrap();
1051        let buf = reader.read(..).await.unwrap().to_vec();
1052        assert_eq!("hello", String::from_utf8(buf).unwrap());
1053
1054        // Get weighted size.
1055        cache.inner.parquet_index.run_pending_tasks().await;
1056        assert_eq!(5, cache.inner.parquet_index.weighted_size());
1057
1058        // Remove the file.
1059        cache.remove(key).await;
1060        assert!(cache.reader(key).await.is_none());
1061
1062        // Ensure all pending tasks of the moka cache is done before assertion.
1063        cache.inner.parquet_index.run_pending_tasks().await;
1064
1065        // The file also not exists.
1066        assert!(!local_store.exists(&file_path).await.unwrap());
1067        assert_eq!(0, cache.inner.parquet_index.weighted_size());
1068    }
1069
1070    #[tokio::test]
1071    async fn test_file_cache_file_removed() {
1072        let dir = create_temp_dir("");
1073        let local_store = new_fs_store(dir.path().to_str().unwrap());
1074
1075        let cache = FileCache::new(
1076            local_store.clone(),
1077            ReadableSize::mb(10),
1078            None,
1079            None,
1080            true, // enable_background_worker
1081        );
1082        let region_id = RegionId::new(2000, 0);
1083        let file_id = FileId::random();
1084        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
1085        let file_path = cache.cache_file_path(key);
1086
1087        // Write a file.
1088        local_store
1089            .write(&file_path, b"hello".as_slice())
1090            .await
1091            .unwrap();
1092        // Add to the cache.
1093        cache
1094            .put(
1095                IndexKey::new(region_id, file_id, FileType::Parquet),
1096                IndexValue { file_size: 5 },
1097            )
1098            .await;
1099
1100        // Remove the file but keep the index.
1101        local_store.delete(&file_path).await.unwrap();
1102
1103        // Reader is none.
1104        assert!(cache.reader(key).await.is_none());
1105        // Key is removed.
1106        assert!(!cache.inner.parquet_index.contains_key(&key));
1107    }
1108
1109    #[tokio::test]
1110    async fn test_file_cache_recover() {
1111        let dir = create_temp_dir("");
1112        let local_store = new_fs_store(dir.path().to_str().unwrap());
1113        let cache = FileCache::new(
1114            local_store.clone(),
1115            ReadableSize::mb(10),
1116            None,
1117            None,
1118            true, // enable_background_worker
1119        );
1120
1121        let region_id = RegionId::new(2000, 0);
1122        let file_type = FileType::Parquet;
1123        // Write N files.
1124        let file_ids: Vec<_> = (0..10).map(|_| FileId::random()).collect();
1125        let mut total_size = 0;
1126        for (i, file_id) in file_ids.iter().enumerate() {
1127            let key = IndexKey::new(region_id, *file_id, file_type);
1128            let file_path = cache.cache_file_path(key);
1129            let bytes = i.to_string().into_bytes();
1130            local_store.write(&file_path, bytes.clone()).await.unwrap();
1131
1132            // Add to the cache.
1133            cache
1134                .put(
1135                    IndexKey::new(region_id, *file_id, file_type),
1136                    IndexValue {
1137                        file_size: bytes.len() as u32,
1138                    },
1139                )
1140                .await;
1141            total_size += bytes.len();
1142        }
1143
1144        // Only one part of this generation is resident. Its manifest and earlier parts
1145        // may have been evicted before restart.
1146        let native = IndexKey::new(region_id, FileId::random(), FileType::Samples(Some(7)));
1147        local_store
1148            .write(&cache.cache_file_path(native), "part")
1149            .await
1150            .unwrap();
1151        total_size += 4;
1152
1153        // Recover the cache.
1154        let cache = FileCache::new(
1155            local_store.clone(),
1156            ReadableSize::mb(10),
1157            None,
1158            None,
1159            true, // enable_background_worker
1160        );
1161        // No entry before recovery.
1162        assert!(
1163            cache
1164                .reader(IndexKey::new(region_id, file_ids[0], file_type))
1165                .await
1166                .is_none()
1167        );
1168        cache.recover(true, None).await;
1169        assert!(cache.contains_key(&native));
1170
1171        // Check size.
1172        cache.inner.parquet_index.run_pending_tasks().await;
1173        assert_eq!(
1174            total_size,
1175            cache.inner.parquet_index.weighted_size() as usize
1176        );
1177
1178        for (i, file_id) in file_ids.iter().enumerate() {
1179            let key = IndexKey::new(region_id, *file_id, file_type);
1180            let reader = cache.reader(key).await.unwrap();
1181            let buf = reader.read(..).await.unwrap().to_vec();
1182            assert_eq!(i.to_string(), String::from_utf8(buf).unwrap());
1183        }
1184    }
1185
1186    #[tokio::test]
1187    async fn test_file_cache_read_ranges() {
1188        let dir = create_temp_dir("");
1189        let local_store = new_fs_store(dir.path().to_str().unwrap());
1190        let file_cache = FileCache::new(
1191            local_store.clone(),
1192            ReadableSize::mb(10),
1193            None,
1194            None,
1195            true, // enable_background_worker
1196        );
1197        let region_id = RegionId::new(2000, 0);
1198        let file_id = FileId::random();
1199        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
1200        let file_path = file_cache.cache_file_path(key);
1201        // Write a file.
1202        let data = b"hello greptime database";
1203        local_store
1204            .write(&file_path, data.as_slice())
1205            .await
1206            .unwrap();
1207        // Add to the cache.
1208        file_cache.put(key, IndexValue { file_size: 5 }).await;
1209        // Ranges
1210        let ranges = vec![0..5, 6..10, 15..19, 0..data.len() as u64];
1211        let bytes = file_cache.read_ranges(key, &ranges).await.unwrap();
1212
1213        assert_eq!(4, bytes.len());
1214        assert_eq!(b"hello", bytes[0].as_ref());
1215        assert_eq!(b"grep", bytes[1].as_ref());
1216        assert_eq!(b"data", bytes[2].as_ref());
1217        assert_eq!(data, bytes[3].as_ref());
1218    }
1219
1220    #[test]
1221    fn test_file_cache_capacity_respects_total_budget() {
1222        let total_capacity = ReadableSize::mb(256).as_bytes();
1223        let (parquet_capacity, puffin_capacity) =
1224            FileCache::split_cache_capacities(total_capacity, 20);
1225
1226        assert_eq!(total_capacity, parquet_capacity + puffin_capacity);
1227        assert_eq!(ReadableSize::mb(128).as_bytes(), parquet_capacity);
1228        assert_eq!(ReadableSize::mb(128).as_bytes(), puffin_capacity);
1229    }
1230
1231    #[test]
1232    fn test_file_cache_capacity_keeps_split_when_total_allows_it() {
1233        let total_capacity = ReadableSize::gb(5).as_bytes();
1234        let (parquet_capacity, puffin_capacity) =
1235            FileCache::split_cache_capacities(total_capacity, 20);
1236
1237        assert_eq!(total_capacity, parquet_capacity + puffin_capacity);
1238        assert_eq!(ReadableSize::gb(4).as_bytes(), parquet_capacity);
1239        assert_eq!(ReadableSize::gb(1).as_bytes(), puffin_capacity);
1240    }
1241
1242    #[test]
1243    fn test_cache_file_path() {
1244        let file_id = FileId::parse_str("3368731b-a556-42b8-a5df-9c31ce155095").unwrap();
1245        assert_eq!(
1246            "test_dir/5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet",
1247            cache_file_path(
1248                "test_dir",
1249                IndexKey::new(RegionId::new(1234, 5), file_id, FileType::Parquet)
1250            )
1251        );
1252        assert_eq!(
1253            "test_dir/5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet",
1254            cache_file_path(
1255                "test_dir/",
1256                IndexKey::new(RegionId::new(1234, 5), file_id, FileType::Parquet)
1257            )
1258        );
1259    }
1260
1261    #[test]
1262    fn test_parse_file_name() {
1263        let file_id = FileId::parse_str("3368731b-a556-42b8-a5df-9c31ce155095").unwrap();
1264        let region_id = RegionId::new(1234, 5);
1265        assert_eq!(
1266            IndexKey::new(region_id, file_id, FileType::Parquet),
1267            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet").unwrap()
1268        );
1269        assert_eq!(
1270            IndexKey::new(region_id, file_id, FileType::Puffin(0)),
1271            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.puffin").unwrap()
1272        );
1273        assert_eq!(
1274            IndexKey::new(region_id, file_id, FileType::Puffin(42)),
1275            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.42.puffin")
1276                .unwrap()
1277        );
1278        assert!(parse_index_key("").is_none());
1279        assert!(parse_index_key(".").is_none());
1280        assert!(parse_index_key("5299989643269").is_none());
1281        assert!(parse_index_key("5299989643269.").is_none());
1282        assert!(parse_index_key(".5299989643269").is_none());
1283        assert!(parse_index_key("5299989643269.").is_none());
1284        assert!(parse_index_key("5299989643269.3368731b-a556-42b8-a5df").is_none());
1285        assert!(parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095").is_none());
1286        assert!(
1287            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parque").is_none()
1288        );
1289        assert!(
1290            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet.puffin")
1291                .is_none()
1292        );
1293    }
1294}