Skip to main content

mito2/
access_layer.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::path::Path;
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use async_stream::try_stream;
20use common_base::readable_size::ReadableSize;
21use common_runtime::runtime::RuntimeTrait;
22use common_telemetry::warn;
23use common_time::Timestamp;
24use futures::{Stream, TryStreamExt};
25use object_store::services::Fs;
26use object_store::util::{join_dir, with_instrument_layers};
27use object_store::{ATOMIC_WRITE_DIR, ErrorKind, OLD_ATOMIC_WRITE_DIR, ObjectStore};
28use parquet::file::metadata::PageIndexPolicy;
29use smallvec::SmallVec;
30use snafu::ResultExt;
31use store_api::metadata::RegionMetadataRef;
32use store_api::region_request::PathType;
33use store_api::sst_entry::StorageSstEntry;
34use store_api::storage::{FileId, RegionId, SequenceNumber};
35
36use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey};
37use crate::cache::write_cache::SstUploadRequest;
38use crate::cache::{CacheManagerRef, SstMetaPreparation, prepare_sst_meta_sync};
39use crate::config::{BloomFilterConfig, FulltextIndexConfig, IndexConfig, InvertedIndexConfig};
40use crate::error::{
41    CleanDirSnafu, DeleteIndexSnafu, DeleteIndexesSnafu, DeleteSstsSnafu, OpenDalSnafu, Result,
42};
43use crate::metrics::{COMPACTION_STAGE_ELAPSED, FLUSH_ELAPSED};
44use crate::read::FlatSource;
45use crate::region::options::IndexOptions;
46use crate::sst::file::{FileHandle, RegionFileId, RegionIndexId};
47use crate::sst::index::intermediate::IntermediateManager;
48use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinManager};
49use crate::sst::index::{IndexerBuilderImpl, build_index_from_parquet_bytes};
50use crate::sst::location::{self, region_dir_from_table_dir};
51use crate::sst::parquet::reader::ParquetReaderBuilder;
52use crate::sst::parquet::writer::ParquetWriter;
53use crate::sst::parquet::{SstInfo, WriteOptions};
54use crate::sst::{DEFAULT_WRITE_CONCURRENCY, FormatType};
55
56pub type AccessLayerRef = Arc<AccessLayer>;
57/// SST write results.
58pub type SstInfoArray = SmallVec<[SstInfo; 2]>;
59
60/// Write operation type.
61#[derive(Eq, PartialEq, Debug)]
62pub enum WriteType {
63    /// Writes from flush
64    Flush,
65    /// Writes from compaction.
66    Compaction,
67}
68
69#[derive(Debug)]
70pub struct Metrics {
71    pub(crate) write_type: WriteType,
72    pub(crate) iter_source: Duration,
73    pub(crate) write_batch: Duration,
74    pub(crate) update_index: Duration,
75    pub(crate) upload_parquet: Duration,
76    pub(crate) upload_puffin: Duration,
77    pub(crate) compact_memtable: Duration,
78}
79
80impl Metrics {
81    pub fn new(write_type: WriteType) -> Self {
82        Self {
83            write_type,
84            iter_source: Default::default(),
85            write_batch: Default::default(),
86            update_index: Default::default(),
87            upload_parquet: Default::default(),
88            upload_puffin: Default::default(),
89            compact_memtable: Default::default(),
90        }
91    }
92
93    pub(crate) fn merge(mut self, other: Self) -> Self {
94        assert_eq!(self.write_type, other.write_type);
95        self.iter_source += other.iter_source;
96        self.write_batch += other.write_batch;
97        self.update_index += other.update_index;
98        self.upload_parquet += other.upload_parquet;
99        self.upload_puffin += other.upload_puffin;
100        self.compact_memtable += other.compact_memtable;
101        self
102    }
103
104    pub(crate) fn observe(self) {
105        match self.write_type {
106            WriteType::Flush => {
107                FLUSH_ELAPSED
108                    .with_label_values(&["iter_source"])
109                    .observe(self.iter_source.as_secs_f64());
110                FLUSH_ELAPSED
111                    .with_label_values(&["write_batch"])
112                    .observe(self.write_batch.as_secs_f64());
113                FLUSH_ELAPSED
114                    .with_label_values(&["update_index"])
115                    .observe(self.update_index.as_secs_f64());
116                FLUSH_ELAPSED
117                    .with_label_values(&["upload_parquet"])
118                    .observe(self.upload_parquet.as_secs_f64());
119                FLUSH_ELAPSED
120                    .with_label_values(&["upload_puffin"])
121                    .observe(self.upload_puffin.as_secs_f64());
122                if !self.compact_memtable.is_zero() {
123                    FLUSH_ELAPSED
124                        .with_label_values(&["compact_memtable"])
125                        .observe(self.upload_puffin.as_secs_f64());
126                }
127            }
128            WriteType::Compaction => {
129                COMPACTION_STAGE_ELAPSED
130                    .with_label_values(&["iter_source"])
131                    .observe(self.iter_source.as_secs_f64());
132                COMPACTION_STAGE_ELAPSED
133                    .with_label_values(&["write_batch"])
134                    .observe(self.write_batch.as_secs_f64());
135                COMPACTION_STAGE_ELAPSED
136                    .with_label_values(&["update_index"])
137                    .observe(self.update_index.as_secs_f64());
138                COMPACTION_STAGE_ELAPSED
139                    .with_label_values(&["upload_parquet"])
140                    .observe(self.upload_parquet.as_secs_f64());
141                COMPACTION_STAGE_ELAPSED
142                    .with_label_values(&["upload_puffin"])
143                    .observe(self.upload_puffin.as_secs_f64());
144            }
145        };
146    }
147}
148
149/// A layer to access SST files under the same directory.
150pub struct AccessLayer {
151    table_dir: String,
152    /// Path type for generating file paths.
153    path_type: PathType,
154    /// Target object store.
155    object_store: ObjectStore,
156    /// Puffin manager factory for index.
157    puffin_manager_factory: PuffinManagerFactory,
158    /// Intermediate manager for inverted index.
159    intermediate_manager: IntermediateManager,
160}
161
162impl std::fmt::Debug for AccessLayer {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        f.debug_struct("AccessLayer")
165            .field("table_dir", &self.table_dir)
166            .finish()
167    }
168}
169
170impl AccessLayer {
171    /// Returns a new [AccessLayer] for specific `table_dir`.
172    pub fn new(
173        table_dir: impl Into<String>,
174        path_type: PathType,
175        object_store: ObjectStore,
176        puffin_manager_factory: PuffinManagerFactory,
177        intermediate_manager: IntermediateManager,
178    ) -> AccessLayer {
179        AccessLayer {
180            table_dir: table_dir.into(),
181            path_type,
182            object_store,
183            puffin_manager_factory,
184            intermediate_manager,
185        }
186    }
187
188    /// Returns the directory of the table.
189    pub fn table_dir(&self) -> &str {
190        &self.table_dir
191    }
192
193    /// Returns the object store of the layer.
194    pub fn object_store(&self) -> &ObjectStore {
195        &self.object_store
196    }
197
198    /// Returns the path type of the layer.
199    pub fn path_type(&self) -> PathType {
200        self.path_type
201    }
202
203    /// Returns the puffin manager factory.
204    pub fn puffin_manager_factory(&self) -> &PuffinManagerFactory {
205        &self.puffin_manager_factory
206    }
207
208    /// Returns the intermediate manager.
209    pub fn intermediate_manager(&self) -> &IntermediateManager {
210        &self.intermediate_manager
211    }
212
213    /// Build the puffin manager.
214    pub(crate) fn build_puffin_manager(&self) -> SstPuffinManager {
215        let store = self.object_store.clone();
216        let path_provider =
217            RegionFilePathFactory::new(self.table_dir().to_string(), self.path_type());
218        self.puffin_manager_factory.build(store, path_provider)
219    }
220
221    pub(crate) async fn delete_index(
222        &self,
223        index_file_id: RegionIndexId,
224    ) -> Result<(), crate::error::Error> {
225        let path = location::index_file_path(
226            &self.table_dir,
227            RegionIndexId::new(index_file_id.file_id, index_file_id.version),
228            self.path_type,
229        );
230        self.object_store
231            .delete(&path)
232            .await
233            .context(DeleteIndexSnafu {
234                file_id: index_file_id.file_id(),
235            })?;
236        Ok(())
237    }
238
239    pub(crate) async fn delete_ssts(
240        &self,
241        region_id: RegionId,
242        file_ids: &[FileId],
243    ) -> Result<(), crate::error::Error> {
244        if file_ids.is_empty() {
245            return Ok(());
246        }
247
248        let attempted_files = file_ids.to_vec();
249        // Deleter does not normalize leading slashes like Operator::delete does.
250        let paths: Vec<_> = file_ids
251            .iter()
252            .map(|file_id| {
253                location::sst_file_path(
254                    &self.table_dir,
255                    RegionFileId::new(region_id, *file_id),
256                    self.path_type,
257                )
258                .trim_start_matches('/')
259                .to_string()
260            })
261            .collect();
262
263        let mut deleter = self
264            .object_store
265            .deleter()
266            .await
267            .with_context(|_| DeleteSstsSnafu {
268                region_id,
269                file_ids: attempted_files.clone(),
270            })?;
271        deleter
272            .delete_iter(paths)
273            .await
274            .with_context(|_| DeleteSstsSnafu {
275                region_id,
276                file_ids: attempted_files.clone(),
277            })?;
278        deleter.close().await.with_context(|_| DeleteSstsSnafu {
279            region_id,
280            file_ids: attempted_files,
281        })?;
282
283        Ok(())
284    }
285
286    pub(crate) async fn delete_indexes(
287        &self,
288        index_ids: &[RegionIndexId],
289    ) -> Result<(), crate::error::Error> {
290        if index_ids.is_empty() {
291            return Ok(());
292        }
293
294        let file_ids: Vec<_> = index_ids
295            .iter()
296            .map(|index_id| index_id.file_id())
297            .collect();
298        let paths: Vec<_> = index_ids
299            .iter()
300            .map(|index_id| {
301                location::index_file_path(&self.table_dir, *index_id, self.path_type)
302                    .trim_start_matches('/')
303                    .to_string()
304            })
305            .collect();
306
307        let mut deleter = self
308            .object_store
309            .deleter()
310            .await
311            .context(DeleteIndexesSnafu {
312                file_ids: file_ids.clone(),
313            })?;
314        deleter
315            .delete_iter(paths)
316            .await
317            .context(DeleteIndexesSnafu {
318                file_ids: file_ids.clone(),
319            })?;
320        deleter
321            .close()
322            .await
323            .context(DeleteIndexesSnafu { file_ids })?;
324
325        Ok(())
326    }
327
328    /// Returns the directory of the region in the table.
329    pub fn build_region_dir(&self, region_id: RegionId) -> String {
330        region_dir_from_table_dir(&self.table_dir, region_id, self.path_type)
331    }
332
333    /// Returns a reader builder for specific `file`.
334    pub(crate) fn read_sst(&self, file: FileHandle) -> ParquetReaderBuilder {
335        ParquetReaderBuilder::new(
336            self.table_dir.clone(),
337            self.path_type,
338            file,
339            self.object_store.clone(),
340        )
341    }
342
343    /// Writes a SST with specific `file_id` and `metadata` to the layer.
344    ///
345    /// Returns the info of the SST. If no data written, returns None.
346    pub async fn write_sst(
347        &self,
348        request: SstWriteRequest,
349        write_opts: &WriteOptions,
350        metrics: &mut Metrics,
351    ) -> Result<SstInfoArray> {
352        let op_type = request.op_type;
353        let region_id = request.metadata.region_id;
354        let region_metadata = request.metadata.clone();
355        let cache_manager = request.cache_manager.clone();
356        let override_sequence = if request.preserve_row_sequence {
357            None
358        } else {
359            request.max_sequence
360        };
361
362        let sst_info = if let Some(write_cache) = cache_manager.write_cache() {
363            // Write to the write cache.
364            write_cache
365                .write_and_upload_sst(
366                    request,
367                    SstUploadRequest {
368                        dest_path_provider: RegionFilePathFactory::new(
369                            self.table_dir.clone(),
370                            self.path_type,
371                        ),
372                        remote_store: self.object_store.clone(),
373                    },
374                    write_opts,
375                    metrics,
376                )
377                .await?
378        } else {
379            // Write cache is disabled.
380            let store = self.object_store.clone();
381            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
382            let indexer_builder = IndexerBuilderImpl {
383                build_type: request.op_type.into(),
384                metadata: request.metadata.clone(),
385                puffin_manager: self
386                    .puffin_manager_factory
387                    .build(store, path_provider.clone()),
388                write_cache_enabled: false,
389                intermediate_manager: self.intermediate_manager.clone(),
390                index_options: request.index_options,
391                inverted_index_config: request.inverted_index_config,
392                fulltext_index_config: request.fulltext_index_config,
393                bloom_filter_index_config: request.bloom_filter_index_config,
394            };
395            // We disable write cache on file system but we still use atomic write.
396            // TODO(yingwen): If we support other non-fs stores without the write cache, then
397            // we may have find a way to check whether we need the cleaner.
398            let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
399            let mut writer = ParquetWriter::new_with_object_store(
400                self.object_store.clone(),
401                request.metadata,
402                request.index_config,
403                indexer_builder,
404                path_provider,
405                metrics,
406            )
407            .await
408            .with_file_cleaner(cleaner);
409            match request.sst_write_format {
410                FormatType::PrimaryKey => {
411                    writer
412                        .write_all_flat_as_primary_key(
413                            request.source,
414                            override_sequence,
415                            write_opts,
416                        )
417                        .await?
418                }
419                FormatType::Flat => {
420                    writer
421                        .write_all_flat(request.source, override_sequence, write_opts)
422                        .await?
423                }
424            }
425        };
426
427        // Put parquet metadata to cache manager.
428        if !sst_info.is_empty() && cache_manager.sst_meta_cache_enabled() {
429            let runtime = match op_type {
430                OperationType::Compact => common_runtime::compact_runtime(),
431                OperationType::Flush => common_runtime::global_runtime(),
432            };
433            for sst in &sst_info {
434                if let Some(parquet_metadata) = &sst.file_metadata {
435                    let file_id = RegionFileId::new(region_id, sst.file_id);
436                    let file_path = format!(
437                        "region_id={}, file_id={}",
438                        file_id.region_id(),
439                        file_id.file_id()
440                    );
441                    let page_index_policy = if parquet_metadata.offset_index().is_some() {
442                        PageIndexPolicy::Optional
443                    } else {
444                        PageIndexPolicy::Skip
445                    };
446                    let parquet_metadata = parquet_metadata.clone();
447                    let region_metadata = region_metadata.clone();
448                    let cache_manager = cache_manager.clone();
449                    // Compact cache preparation is best-effort. Run the entire operation in one
450                    // detached blocking task so it neither blocks an async worker nor delays the
451                    // SST write.
452                    runtime.spawn_blocking(move || {
453                        match prepare_sst_meta_sync(
454                            &file_path,
455                            Arc::unwrap_or_clone(parquet_metadata),
456                            Some(region_metadata),
457                            page_index_policy,
458                        ) {
459                            Ok(SstMetaPreparation::Prepared(metadata)) => {
460                                cache_manager.put_prepared_sst_meta(file_id, metadata, true);
461                            }
462                            Ok(SstMetaPreparation::DecodedOnly { encoding_error, .. }) => warn!(
463                                encoding_error;
464                                "Failed to encode parquet metadata for cache, file: {}",
465                                file_path
466                            ),
467                            Err(err) => {
468                                warn!(err; "Failed to cache parquet metadata for {}", file_path);
469                            }
470                        }
471                    });
472                }
473            }
474        }
475
476        Ok(sst_info)
477    }
478
479    /// Puts encoded SST bytes to the write cache (if enabled) and uploads it to the object store.
480    ///
481    /// Builds the SST's indexes from `data` into `sst_info.index_metadata` when
482    /// `index_build_params` is set.
483    pub(crate) async fn put_sst(
484        &self,
485        data: &bytes::Bytes,
486        region_id: RegionId,
487        sst_info: &mut SstInfo,
488        cache_manager: &CacheManagerRef,
489        write_buffer_size: ReadableSize,
490        index_build_params: Option<EncodedSstIndexBuildParams>,
491    ) -> Result<Metrics> {
492        let region_file_id = RegionFileId::new(region_id, sst_info.file_id);
493        if let Some(write_cache) = cache_manager.write_cache() {
494            // Write to cache and upload to remote store
495            let upload_request = SstUploadRequest {
496                dest_path_provider: RegionFilePathFactory::new(
497                    self.table_dir.clone(),
498                    self.path_type,
499                ),
500                remote_store: self.object_store.clone(),
501            };
502            write_cache
503                .put_and_upload_sst(
504                    data,
505                    region_id,
506                    sst_info,
507                    upload_request,
508                    write_buffer_size,
509                    index_build_params,
510                )
511                .await
512        } else {
513            let start = Instant::now();
514            let cleaner =
515                TempFileCleaner::new(region_file_id.region_id(), self.object_store.clone());
516            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
517            let sst_file_path = path_provider.build_sst_file_path(region_file_id);
518            let mut writer = self
519                .object_store
520                .writer_with(&sst_file_path)
521                .chunk(write_buffer_size.as_bytes() as usize)
522                .concurrent(DEFAULT_WRITE_CONCURRENCY)
523                .await
524                .context(OpenDalSnafu)?;
525            if let Err(err) = writer.write(data.clone()).await.context(OpenDalSnafu) {
526                cleaner.clean_by_file_id(region_file_id.file_id()).await;
527                return Err(err);
528            }
529            if let Err(err) = writer.close().await.context(OpenDalSnafu) {
530                cleaner.clean_by_file_id(region_file_id.file_id()).await;
531                return Err(err);
532            }
533            let mut metrics = Metrics::new(WriteType::Flush);
534            metrics.write_batch = start.elapsed();
535
536            if let Some(params) = index_build_params {
537                let start = Instant::now();
538                let builder = params.indexer_builder(
539                    self.puffin_manager_factory
540                        .build(self.object_store.clone(), path_provider),
541                    false,
542                    self.intermediate_manager.clone(),
543                );
544                sst_info.index_metadata =
545                    build_index_from_parquet_bytes(&builder, region_file_id, data).await;
546                metrics.update_index = start.elapsed();
547            }
548            Ok(metrics)
549        }
550    }
551
552    /// Lists the SST entries from the storage layer in the table directory.
553    pub fn storage_sst_entries(&self) -> impl Stream<Item = Result<StorageSstEntry>> + use<> {
554        let object_store = self.object_store.clone();
555        let table_dir = self.table_dir.clone();
556
557        try_stream! {
558            let mut lister = object_store
559                .lister_with(table_dir.as_str())
560                .recursive(true)
561                .await
562                .context(OpenDalSnafu)?;
563
564            while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? {
565                let metadata = entry.metadata();
566                if metadata.is_dir() {
567                    continue;
568                }
569
570                let path = entry.path();
571                if !path.ends_with(".parquet") && !path.ends_with(".puffin") {
572                    continue;
573                }
574
575                let file_size = metadata.content_length();
576                let file_size = if file_size == 0 { None } else { Some(file_size) };
577                let last_modified_ms = metadata
578                    .last_modified()
579                    .map(|ts| Timestamp::new_millisecond(ts.into_inner().as_millisecond()));
580
581                let entry = StorageSstEntry {
582                    file_path: path.to_string(),
583                    file_size,
584                    last_modified_ms,
585                    node_id: None,
586                };
587
588                yield entry;
589            }
590        }
591    }
592}
593
594/// `OperationType` represents the origin of the `SstWriteRequest`.
595#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
596pub enum OperationType {
597    Flush,
598    Compact,
599}
600
601/// Contents to build a SST.
602pub struct SstWriteRequest {
603    pub op_type: OperationType,
604    pub metadata: RegionMetadataRef,
605    pub source: FlatSource,
606    pub cache_manager: CacheManagerRef,
607    /// Optional uniform row sequence for writes that do not preserve sequences.
608    /// Compaction and LastNonNull flushes pass `None` to retain input sequences.
609    pub max_sequence: Option<SequenceNumber>,
610    pub sst_write_format: FormatType,
611
612    pub preserve_row_sequence: bool,
613
614    /// Configs for index
615    pub index_options: IndexOptions,
616    pub index_config: IndexConfig,
617    pub inverted_index_config: InvertedIndexConfig,
618    pub fulltext_index_config: FulltextIndexConfig,
619    pub bloom_filter_index_config: BloomFilterConfig,
620}
621
622/// Index inputs for SST bytes that were encoded outside [ParquetWriter].
623pub(crate) struct EncodedSstIndexBuildParams {
624    pub(crate) metadata: RegionMetadataRef,
625    pub(crate) index_options: IndexOptions,
626    pub(crate) inverted_index_config: InvertedIndexConfig,
627    pub(crate) fulltext_index_config: FulltextIndexConfig,
628    pub(crate) bloom_filter_index_config: BloomFilterConfig,
629}
630
631impl EncodedSstIndexBuildParams {
632    pub(crate) fn indexer_builder(
633        self,
634        puffin_manager: SstPuffinManager,
635        write_cache_enabled: bool,
636        intermediate_manager: IntermediateManager,
637    ) -> IndexerBuilderImpl {
638        IndexerBuilderImpl {
639            build_type: OperationType::Flush.into(),
640            metadata: self.metadata,
641            puffin_manager,
642            write_cache_enabled,
643            intermediate_manager,
644            index_options: self.index_options,
645            inverted_index_config: self.inverted_index_config,
646            fulltext_index_config: self.fulltext_index_config,
647            bloom_filter_index_config: self.bloom_filter_index_config,
648        }
649    }
650}
651
652/// Cleaner to remove temp files on the atomic write dir.
653pub(crate) struct TempFileCleaner {
654    region_id: RegionId,
655    object_store: ObjectStore,
656}
657
658impl TempFileCleaner {
659    /// Constructs the cleaner for the region and store.
660    pub(crate) fn new(region_id: RegionId, object_store: ObjectStore) -> Self {
661        Self {
662            region_id,
663            object_store,
664        }
665    }
666
667    /// Removes the SST and index file from the local atomic dir by the file id.
668    /// This only removes the initial index, since the index version is always 0 for a new SST, this method should be safe to pass 0.
669    pub(crate) async fn clean_by_file_id(&self, file_id: FileId) {
670        let sst_key = IndexKey::new(self.region_id, file_id, FileType::Parquet).to_string();
671        let index_key = IndexKey::new(self.region_id, file_id, FileType::Puffin(0)).to_string();
672
673        Self::clean_atomic_dir_files(&self.object_store, &[&sst_key, &index_key]).await;
674    }
675
676    /// Removes the files from the local atomic dir by their names.
677    pub(crate) async fn clean_atomic_dir_files(
678        local_store: &ObjectStore,
679        names_to_remove: &[&str],
680    ) {
681        // We don't know the actual suffix of the file under atomic dir, so we have
682        // to list the dir. The cost should be acceptable as there won't be to many files.
683        let Ok(entries) = local_store.list(ATOMIC_WRITE_DIR).await.inspect_err(|e| {
684            if e.kind() != ErrorKind::NotFound {
685                common_telemetry::error!(e; "Failed to list tmp files for {:?}", names_to_remove)
686            }
687        }) else {
688            return;
689        };
690
691        // In our case, we can ensure the file id is unique so it is safe to remove all files
692        // with the same file id under the atomic write dir.
693        let actual_files: Vec<_> = entries
694            .into_iter()
695            .filter_map(|entry| {
696                if entry.metadata().is_dir() {
697                    return None;
698                }
699
700                // Remove name that matches files_to_remove.
701                let should_remove = names_to_remove
702                    .iter()
703                    .any(|file| entry.name().starts_with(file));
704                if should_remove {
705                    Some(entry.path().to_string())
706                } else {
707                    None
708                }
709            })
710            .collect();
711
712        common_telemetry::warn!(
713            "Clean files {:?} under atomic write dir for {:?}",
714            actual_files,
715            names_to_remove
716        );
717
718        if let Err(e) = local_store.delete_iter(actual_files).await {
719            common_telemetry::error!(e; "Failed to delete tmp file for {:?}", names_to_remove);
720        }
721    }
722}
723
724pub(crate) async fn new_fs_cache_store(root: &str) -> Result<ObjectStore> {
725    // Preserve native filesystem prefixes such as Windows UNC shares.
726    let atomic_write_dir = Path::new(root).join(ATOMIC_WRITE_DIR);
727    clean_dir(&atomic_write_dir.to_string_lossy()).await?;
728
729    // Compatible code. Remove this after a major release.
730    let old_atomic_temp_dir = join_dir(root, OLD_ATOMIC_WRITE_DIR);
731    clean_dir(&old_atomic_temp_dir).await?;
732
733    let builder = Fs::default()
734        .root(root)
735        .atomic_write_dir(&atomic_write_dir.to_string_lossy());
736    let store = ObjectStore::new(builder).context(OpenDalSnafu)?;
737
738    Ok(with_instrument_layers(store, false))
739}
740
741/// Clean the directory.
742async fn clean_dir(dir: &str) -> Result<()> {
743    if tokio::fs::try_exists(dir)
744        .await
745        .context(CleanDirSnafu { dir })?
746    {
747        tokio::fs::remove_dir_all(dir)
748            .await
749            .context(CleanDirSnafu { dir })?;
750    }
751
752    Ok(())
753}
754
755/// Path provider for SST file and index file.
756pub trait FilePathProvider: Send + Sync {
757    /// Creates index file path of given file id. Version default to 0, and not shown in the path.
758    fn build_index_file_path(&self, file_id: RegionFileId) -> String;
759
760    /// Creates index file path of given index id (with version support).
761    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String;
762
763    /// Creates SST file path of given file id.
764    fn build_sst_file_path(&self, file_id: RegionFileId) -> String;
765}
766
767/// Path provider that builds paths in local write cache.
768#[derive(Clone)]
769pub(crate) struct WriteCachePathProvider {
770    file_cache: FileCacheRef,
771}
772
773impl WriteCachePathProvider {
774    /// Creates a new `WriteCachePathProvider` instance.
775    pub fn new(file_cache: FileCacheRef) -> Self {
776        Self { file_cache }
777    }
778}
779
780impl FilePathProvider for WriteCachePathProvider {
781    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
782        let puffin_key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Puffin(0));
783        self.file_cache.cache_file_path(puffin_key)
784    }
785
786    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String {
787        let puffin_key = IndexKey::new(
788            index_id.region_id(),
789            index_id.file_id(),
790            FileType::Puffin(index_id.version),
791        );
792        self.file_cache.cache_file_path(puffin_key)
793    }
794
795    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
796        let parquet_file_key =
797            IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
798        self.file_cache.cache_file_path(parquet_file_key)
799    }
800}
801
802/// Path provider that builds paths in region storage path.
803#[derive(Clone, Debug)]
804pub(crate) struct RegionFilePathFactory {
805    pub(crate) table_dir: String,
806    pub(crate) path_type: PathType,
807}
808
809impl RegionFilePathFactory {
810    /// Creates a new `RegionFilePathFactory` instance.
811    pub fn new(table_dir: String, path_type: PathType) -> Self {
812        Self {
813            table_dir,
814            path_type,
815        }
816    }
817}
818
819impl FilePathProvider for RegionFilePathFactory {
820    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
821        location::index_file_path_legacy(&self.table_dir, file_id, self.path_type)
822    }
823
824    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String {
825        location::index_file_path(&self.table_dir, index_id, self.path_type)
826    }
827
828    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
829        location::sst_file_path(&self.table_dir, file_id, self.path_type)
830    }
831}
832
833#[cfg(test)]
834mod tests {
835    use std::path::PathBuf;
836
837    use bytes::Bytes;
838    use common_test_util::temp_dir::create_temp_dir;
839
840    use super::*;
841    use crate::cache::CacheManager;
842    use crate::cache::test_util::new_fs_store;
843    use crate::test_util::TestEnv;
844    use crate::test_util::sst_util::WriteChunkRecorder;
845
846    #[rstest::rstest]
847    #[tokio::test]
848    async fn test_put_sst_uses_configured_buffer_size(
849        #[values(false, true)] enable_write_cache: bool,
850        #[values(1024, 4096)] chunk_size: usize,
851    ) {
852        let mut env = TestEnv::new().await;
853        let remote_chunks = WriteChunkRecorder::default();
854        let remote_store = env.init_object_store_manager().layer(remote_chunks.layer());
855        let local_dir = create_temp_dir("encoded-sst-cache");
856        let local_chunks = WriteChunkRecorder::default();
857        let local_store =
858            new_fs_store(local_dir.path().to_str().unwrap()).layer(local_chunks.layer());
859        let write_cache = if enable_write_cache {
860            Some(
861                env.create_write_cache(local_store.clone(), ReadableSize::mb(10))
862                    .await,
863            )
864        } else {
865            None
866        };
867        let cache_manager = Arc::new(
868            CacheManager::builder()
869                .write_cache(write_cache.clone())
870                .build(),
871        );
872        let access_layer = AccessLayer::new(
873            "test",
874            PathType::Bare,
875            remote_store.clone(),
876            env.get_puffin_manager(),
877            env.get_intermediate_manager(),
878        );
879        let file_id = RegionFileId::new(RegionId::new(1024, 1), FileId::random());
880        // Two full chunks and a partial tail distinguish the configured size from the default.
881        let encoded = Bytes::from(
882            (0..2 * chunk_size + 17)
883                .map(|i| (i % 251) as u8)
884                .collect::<Vec<_>>(),
885        );
886        access_layer
887            .put_sst(
888                &encoded,
889                file_id.region_id(),
890                &mut SstInfo {
891                    file_id: file_id.file_id(),
892                    ..Default::default()
893                },
894                &cache_manager,
895                ReadableSize(chunk_size as u64),
896                None,
897            )
898            .await
899            .unwrap();
900
901        let remote_path = location::sst_file_path("test", file_id, PathType::Bare);
902        remote_chunks.assert_chunks(&remote_path, chunk_size, encoded.len());
903        assert_eq!(
904            remote_store.read(&remote_path).await.unwrap().to_bytes(),
905            encoded
906        );
907        if let Some(write_cache) = write_cache {
908            let key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
909            let cache_path = write_cache.file_cache().cache_file_path(key);
910            local_chunks.assert_chunks(&cache_path, chunk_size, encoded.len());
911            assert_eq!(
912                local_store.read(&cache_path).await.unwrap().to_bytes(),
913                encoded
914            );
915        }
916    }
917
918    #[tokio::test]
919    async fn test_new_fs_cache_store() {
920        let root = common_test_util::temp_dir::create_temp_dir("fs-cache-store");
921        let dirs = [
922            root.path().join(ATOMIC_WRITE_DIR),
923            PathBuf::from(join_dir(
924                root.path().to_str().unwrap(),
925                OLD_ATOMIC_WRITE_DIR,
926            )),
927        ];
928        for dir in &dirs {
929            tokio::fs::create_dir_all(dir).await.unwrap();
930            tokio::fs::write(dir.join("stale"), b"stale").await.unwrap();
931        }
932        let store = new_fs_cache_store(root.path().to_str().unwrap())
933            .await
934            .unwrap();
935        for dir in &dirs {
936            assert!(!dir.join("stale").exists());
937        }
938        store.write("index", "contents").await.unwrap();
939        assert_eq!(
940            tokio::fs::read(root.path().join("index")).await.unwrap(),
941            b"contents"
942        );
943    }
944}