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 has_manifest = matches!(
837            &file.format,
838            crate::sst::file::FileFormat::NarthexSeriesIndex(_)
839        );
840        let manifest_index = has_manifest.then(|| objects.len() - 1);
841        objects
842            .into_iter()
843            .enumerate()
844            .map(|(i, object)| {
845                let part = (Some(i) != manifest_index).then_some(i as u32);
846                let kind = match &file.format {
847                    crate::sst::file::FileFormat::NarthexSamples(_) => FileType::Samples(part),
848                    crate::sst::file::FileFormat::NarthexSeriesIndex(_) => FileType::Series(part),
849                    _ => unreachable!(),
850                };
851                (Self::new(file.region_id, file.file_id, kind), object)
852            })
853            .collect()
854    }
855
856    /// Creates a new index key.
857    pub fn new(region_id: RegionId, file_id: FileId, file_type: FileType) -> IndexKey {
858        IndexKey {
859            region_id,
860            file_id,
861            file_type,
862        }
863    }
864}
865
866impl fmt::Display for IndexKey {
867    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
868        write!(
869            f,
870            "{}.{}.{}",
871            self.region_id.as_u64(),
872            self.file_id,
873            self.file_type
874        )
875    }
876}
877
878/// Type of the file.
879#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
880pub enum FileType {
881    /// Parquet file.
882    Parquet,
883    /// Puffin file.
884    Puffin(u64),
885    /// Immutable part, or the manifest when the part ID is absent.
886    Series(Option<u32>),
887    Samples(Option<u32>),
888}
889
890impl From<crate::sst::location::SstObjectType> for FileType {
891    fn from(kind: crate::sst::location::SstObjectType) -> Self {
892        match kind {
893            crate::sst::location::SstObjectType::Parquet => Self::Parquet,
894            crate::sst::location::SstObjectType::Puffin(version) => Self::Puffin(version),
895        }
896    }
897}
898
899impl fmt::Display for FileType {
900    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901        match self {
902            FileType::Samples(None) => f.write_str("samples"),
903            FileType::Series(None) => f.write_str("series"),
904            FileType::Samples(Some(part)) => write!(f, "{part}.samples"),
905            FileType::Series(Some(part)) => write!(f, "{part}.series"),
906            FileType::Parquet => write!(f, "parquet"),
907            FileType::Puffin(version) => write!(f, "{}.puffin", version),
908        }
909    }
910}
911
912impl FileType {
913    /// Parses the file type from string.
914    pub(crate) fn parse(s: &str) -> Option<FileType> {
915        match s {
916            "series" => Some(Self::Series(None)),
917            "samples" => Some(Self::Samples(None)),
918            _ if s.ends_with(".series") => {
919                Some(Self::Series(Some(s.strip_suffix(".series")?.parse().ok()?)))
920            }
921            _ if s.ends_with(".samples") => Some(Self::Samples(Some(
922                s.strip_suffix(".samples")?.parse().ok()?,
923            ))),
924            other => crate::sst::location::SstObjectType::parse(other).map(Self::from),
925        }
926    }
927
928    /// Returns the metric label for this file type.
929    fn metric_label(&self) -> &'static str {
930        match self {
931            FileType::Parquet | FileType::Samples(_) => FILE_TYPE,
932            FileType::Puffin(_) | FileType::Series(_) => INDEX_TYPE,
933        }
934    }
935}
936
937/// An entity that describes the file in the file cache.
938///
939/// It should only keep minimal information needed by the cache.
940#[derive(Debug, Clone)]
941pub(crate) struct IndexValue {
942    /// Size of the file in bytes.
943    pub(crate) file_size: u32,
944}
945
946/// Generates the path to the cached file.
947///
948/// The file name format is `{region_id}.{file_id}.{file_type}`
949fn cache_file_path(cache_file_dir: &str, key: IndexKey) -> String {
950    join_path(cache_file_dir, &key.to_string())
951}
952
953/// Parse index key from the file name.
954fn parse_index_key(name: &str) -> Option<IndexKey> {
955    let mut split = name.splitn(3, '.');
956    let region_id = split.next().and_then(|s| {
957        let id = s.parse::<u64>().ok()?;
958        Some(RegionId::from_u64(id))
959    })?;
960    let file_id = split.next().and_then(|s| FileId::parse_str(s).ok())?;
961    let file_type = split.next().and_then(FileType::parse)?;
962
963    Some(IndexKey::new(region_id, file_id, file_type))
964}
965
966#[cfg(test)]
967mod tests {
968    use common_test_util::temp_dir::create_temp_dir;
969    use object_store::services::Fs;
970
971    use super::*;
972
973    fn new_fs_store(path: &str) -> ObjectStore {
974        let builder = Fs::default().root(path);
975        ObjectStore::new(builder).unwrap()
976    }
977
978    #[tokio::test]
979    async fn test_file_cache_ttl() {
980        let dir = create_temp_dir("");
981        let local_store = new_fs_store(dir.path().to_str().unwrap());
982
983        let cache = FileCache::new(
984            local_store.clone(),
985            ReadableSize::mb(10),
986            Some(Duration::from_millis(10)),
987            None,
988            true, // enable_background_worker
989        );
990        let region_id = RegionId::new(2000, 0);
991        let file_id = FileId::random();
992        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
993        let file_path = cache.cache_file_path(key);
994
995        // Get an empty file.
996        assert!(cache.reader(key).await.is_none());
997
998        // Write a file.
999        local_store
1000            .write(&file_path, b"hello".as_slice())
1001            .await
1002            .unwrap();
1003
1004        // Add to the cache.
1005        cache
1006            .put(
1007                IndexKey::new(region_id, file_id, FileType::Parquet),
1008                IndexValue { file_size: 5 },
1009            )
1010            .await;
1011
1012        let exist = cache.reader(key).await;
1013        assert!(exist.is_some());
1014        tokio::time::sleep(Duration::from_millis(15)).await;
1015        cache.inner.parquet_index.run_pending_tasks().await;
1016        let non = cache.reader(key).await;
1017        assert!(non.is_none());
1018    }
1019
1020    #[tokio::test]
1021    async fn test_file_cache_basic() {
1022        let dir = create_temp_dir("");
1023        let local_store = new_fs_store(dir.path().to_str().unwrap());
1024
1025        let cache = FileCache::new(
1026            local_store.clone(),
1027            ReadableSize::mb(10),
1028            None,
1029            None,
1030            true, // enable_background_worker
1031        );
1032        let region_id = RegionId::new(2000, 0);
1033        let file_id = FileId::random();
1034        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
1035        let file_path = cache.cache_file_path(key);
1036
1037        // Get an empty file.
1038        assert!(cache.reader(key).await.is_none());
1039
1040        // Write a file.
1041        local_store
1042            .write(&file_path, b"hello".as_slice())
1043            .await
1044            .unwrap();
1045        // Add to the cache.
1046        cache
1047            .put(
1048                IndexKey::new(region_id, file_id, FileType::Parquet),
1049                IndexValue { file_size: 5 },
1050            )
1051            .await;
1052
1053        // Read file content.
1054        let reader = cache.reader(key).await.unwrap();
1055        let buf = reader.read(..).await.unwrap().to_vec();
1056        assert_eq!("hello", String::from_utf8(buf).unwrap());
1057
1058        // Get weighted size.
1059        cache.inner.parquet_index.run_pending_tasks().await;
1060        assert_eq!(5, cache.inner.parquet_index.weighted_size());
1061
1062        // Remove the file.
1063        cache.remove(key).await;
1064        assert!(cache.reader(key).await.is_none());
1065
1066        // Ensure all pending tasks of the moka cache is done before assertion.
1067        cache.inner.parquet_index.run_pending_tasks().await;
1068
1069        // The file also not exists.
1070        assert!(!local_store.exists(&file_path).await.unwrap());
1071        assert_eq!(0, cache.inner.parquet_index.weighted_size());
1072    }
1073
1074    #[tokio::test]
1075    async fn test_file_cache_file_removed() {
1076        let dir = create_temp_dir("");
1077        let local_store = new_fs_store(dir.path().to_str().unwrap());
1078
1079        let cache = FileCache::new(
1080            local_store.clone(),
1081            ReadableSize::mb(10),
1082            None,
1083            None,
1084            true, // enable_background_worker
1085        );
1086        let region_id = RegionId::new(2000, 0);
1087        let file_id = FileId::random();
1088        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
1089        let file_path = cache.cache_file_path(key);
1090
1091        // Write a file.
1092        local_store
1093            .write(&file_path, b"hello".as_slice())
1094            .await
1095            .unwrap();
1096        // Add to the cache.
1097        cache
1098            .put(
1099                IndexKey::new(region_id, file_id, FileType::Parquet),
1100                IndexValue { file_size: 5 },
1101            )
1102            .await;
1103
1104        // Remove the file but keep the index.
1105        local_store.delete(&file_path).await.unwrap();
1106
1107        // Reader is none.
1108        assert!(cache.reader(key).await.is_none());
1109        // Key is removed.
1110        assert!(!cache.inner.parquet_index.contains_key(&key));
1111    }
1112
1113    #[tokio::test]
1114    async fn test_file_cache_recover() {
1115        let dir = create_temp_dir("");
1116        let local_store = new_fs_store(dir.path().to_str().unwrap());
1117        let cache = FileCache::new(
1118            local_store.clone(),
1119            ReadableSize::mb(10),
1120            None,
1121            None,
1122            true, // enable_background_worker
1123        );
1124
1125        let region_id = RegionId::new(2000, 0);
1126        let file_type = FileType::Parquet;
1127        // Write N files.
1128        let file_ids: Vec<_> = (0..10).map(|_| FileId::random()).collect();
1129        let mut total_size = 0;
1130        for (i, file_id) in file_ids.iter().enumerate() {
1131            let key = IndexKey::new(region_id, *file_id, file_type);
1132            let file_path = cache.cache_file_path(key);
1133            let bytes = i.to_string().into_bytes();
1134            local_store.write(&file_path, bytes.clone()).await.unwrap();
1135
1136            // Add to the cache.
1137            cache
1138                .put(
1139                    IndexKey::new(region_id, *file_id, file_type),
1140                    IndexValue {
1141                        file_size: bytes.len() as u32,
1142                    },
1143                )
1144                .await;
1145            total_size += bytes.len();
1146        }
1147
1148        // Only one part of this generation is resident. Its manifest and earlier parts
1149        // may have been evicted before restart.
1150        let native = IndexKey::new(region_id, FileId::random(), FileType::Samples(Some(7)));
1151        local_store
1152            .write(&cache.cache_file_path(native), "part")
1153            .await
1154            .unwrap();
1155        total_size += 4;
1156
1157        // Recover the cache.
1158        let cache = FileCache::new(
1159            local_store.clone(),
1160            ReadableSize::mb(10),
1161            None,
1162            None,
1163            true, // enable_background_worker
1164        );
1165        // No entry before recovery.
1166        assert!(
1167            cache
1168                .reader(IndexKey::new(region_id, file_ids[0], file_type))
1169                .await
1170                .is_none()
1171        );
1172        cache.recover(true, None).await;
1173        assert!(cache.contains_key(&native));
1174
1175        // Check size.
1176        cache.inner.parquet_index.run_pending_tasks().await;
1177        assert_eq!(
1178            total_size,
1179            cache.inner.parquet_index.weighted_size() as usize
1180        );
1181
1182        for (i, file_id) in file_ids.iter().enumerate() {
1183            let key = IndexKey::new(region_id, *file_id, file_type);
1184            let reader = cache.reader(key).await.unwrap();
1185            let buf = reader.read(..).await.unwrap().to_vec();
1186            assert_eq!(i.to_string(), String::from_utf8(buf).unwrap());
1187        }
1188    }
1189
1190    #[tokio::test]
1191    async fn test_file_cache_read_ranges() {
1192        let dir = create_temp_dir("");
1193        let local_store = new_fs_store(dir.path().to_str().unwrap());
1194        let file_cache = FileCache::new(
1195            local_store.clone(),
1196            ReadableSize::mb(10),
1197            None,
1198            None,
1199            true, // enable_background_worker
1200        );
1201        let region_id = RegionId::new(2000, 0);
1202        let file_id = FileId::random();
1203        let key = IndexKey::new(region_id, file_id, FileType::Parquet);
1204        let file_path = file_cache.cache_file_path(key);
1205        // Write a file.
1206        let data = b"hello greptime database";
1207        local_store
1208            .write(&file_path, data.as_slice())
1209            .await
1210            .unwrap();
1211        // Add to the cache.
1212        file_cache.put(key, IndexValue { file_size: 5 }).await;
1213        // Ranges
1214        let ranges = vec![0..5, 6..10, 15..19, 0..data.len() as u64];
1215        let bytes = file_cache.read_ranges(key, &ranges).await.unwrap();
1216
1217        assert_eq!(4, bytes.len());
1218        assert_eq!(b"hello", bytes[0].as_ref());
1219        assert_eq!(b"grep", bytes[1].as_ref());
1220        assert_eq!(b"data", bytes[2].as_ref());
1221        assert_eq!(data, bytes[3].as_ref());
1222    }
1223
1224    #[test]
1225    fn test_file_cache_capacity_respects_total_budget() {
1226        let total_capacity = ReadableSize::mb(256).as_bytes();
1227        let (parquet_capacity, puffin_capacity) =
1228            FileCache::split_cache_capacities(total_capacity, 20);
1229
1230        assert_eq!(total_capacity, parquet_capacity + puffin_capacity);
1231        assert_eq!(ReadableSize::mb(128).as_bytes(), parquet_capacity);
1232        assert_eq!(ReadableSize::mb(128).as_bytes(), puffin_capacity);
1233    }
1234
1235    #[test]
1236    fn test_file_cache_capacity_keeps_split_when_total_allows_it() {
1237        let total_capacity = ReadableSize::gb(5).as_bytes();
1238        let (parquet_capacity, puffin_capacity) =
1239            FileCache::split_cache_capacities(total_capacity, 20);
1240
1241        assert_eq!(total_capacity, parquet_capacity + puffin_capacity);
1242        assert_eq!(ReadableSize::gb(4).as_bytes(), parquet_capacity);
1243        assert_eq!(ReadableSize::gb(1).as_bytes(), puffin_capacity);
1244    }
1245
1246    #[test]
1247    fn test_cache_file_path() {
1248        let file_id = FileId::parse_str("3368731b-a556-42b8-a5df-9c31ce155095").unwrap();
1249        assert_eq!(
1250            "test_dir/5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet",
1251            cache_file_path(
1252                "test_dir",
1253                IndexKey::new(RegionId::new(1234, 5), file_id, FileType::Parquet)
1254            )
1255        );
1256        assert_eq!(
1257            "test_dir/5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet",
1258            cache_file_path(
1259                "test_dir/",
1260                IndexKey::new(RegionId::new(1234, 5), file_id, FileType::Parquet)
1261            )
1262        );
1263    }
1264
1265    #[test]
1266    fn test_parse_file_name() {
1267        let file_id = FileId::parse_str("3368731b-a556-42b8-a5df-9c31ce155095").unwrap();
1268        let region_id = RegionId::new(1234, 5);
1269        assert_eq!(
1270            IndexKey::new(region_id, file_id, FileType::Parquet),
1271            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet").unwrap()
1272        );
1273        assert_eq!(
1274            IndexKey::new(region_id, file_id, FileType::Puffin(0)),
1275            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.puffin").unwrap()
1276        );
1277        assert_eq!(
1278            IndexKey::new(region_id, file_id, FileType::Puffin(42)),
1279            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.42.puffin")
1280                .unwrap()
1281        );
1282        assert!(parse_index_key("").is_none());
1283        assert!(parse_index_key(".").is_none());
1284        assert!(parse_index_key("5299989643269").is_none());
1285        assert!(parse_index_key("5299989643269.").is_none());
1286        assert!(parse_index_key(".5299989643269").is_none());
1287        assert!(parse_index_key("5299989643269.").is_none());
1288        assert!(parse_index_key("5299989643269.3368731b-a556-42b8-a5df").is_none());
1289        assert!(parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095").is_none());
1290        assert!(
1291            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parque").is_none()
1292        );
1293        assert!(
1294            parse_index_key("5299989643269.3368731b-a556-42b8-a5df-9c31ce155095.parquet.puffin")
1295                .is_none()
1296        );
1297    }
1298}