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                    // Prepare and cache metadata in the background without delaying the SST write.
450                    let task_runtime = runtime.clone();
451                    runtime.spawn(async move {
452                        let preparation = task_runtime.spawn_blocking(move || {
453                            prepare_sst_meta_sync(
454                                &file_path,
455                                Arc::unwrap_or_clone(parquet_metadata),
456                                Some(region_metadata),
457                                page_index_policy,
458                            )
459                        }).await.context(crate::error::JoinSnafu).and_then(|result| result);
460                        match preparation {
461                            Ok(SstMetaPreparation::Prepared(metadata)) => {
462                                cache_manager.put_compact_sst_meta(file_id, metadata.compact);
463                                cache_manager.put_sst_meta_data(file_id, metadata.decoded).await;
464                            }
465                            Ok(SstMetaPreparation::DecodedOnly { encoding_error, .. }) => warn!(
466                                encoding_error;
467                                "Failed to encode parquet metadata for cache, file: {}",
468                                file_id.file_id()
469                            ),
470                            Err(err) => {
471                                warn!(err; "Failed to cache parquet metadata for {}", file_id.file_id());
472                            }
473                        }
474                    });
475                }
476            }
477        }
478
479        Ok(sst_info)
480    }
481
482    /// Puts encoded SST bytes to the write cache (if enabled) and uploads it to the object store.
483    ///
484    /// Builds the SST's indexes from `data` into `sst_info.index_metadata` when
485    /// `index_build_params` is set.
486    pub(crate) async fn put_sst(
487        &self,
488        data: &bytes::Bytes,
489        region_id: RegionId,
490        sst_info: &mut SstInfo,
491        cache_manager: &CacheManagerRef,
492        write_buffer_size: ReadableSize,
493        index_build_params: Option<EncodedSstIndexBuildParams>,
494    ) -> Result<Metrics> {
495        let region_file_id = RegionFileId::new(region_id, sst_info.file_id);
496        if let Some(write_cache) = cache_manager.write_cache() {
497            // Write to cache and upload to remote store
498            let upload_request = SstUploadRequest {
499                dest_path_provider: RegionFilePathFactory::new(
500                    self.table_dir.clone(),
501                    self.path_type,
502                ),
503                remote_store: self.object_store.clone(),
504            };
505            write_cache
506                .put_and_upload_sst(
507                    data,
508                    region_id,
509                    sst_info,
510                    upload_request,
511                    write_buffer_size,
512                    index_build_params,
513                )
514                .await
515        } else {
516            let start = Instant::now();
517            let cleaner =
518                TempFileCleaner::new(region_file_id.region_id(), self.object_store.clone());
519            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
520            let sst_file_path = path_provider.build_sst_file_path(region_file_id);
521            let mut writer = self
522                .object_store
523                .writer_with(&sst_file_path)
524                .chunk(write_buffer_size.as_bytes() as usize)
525                .concurrent(DEFAULT_WRITE_CONCURRENCY)
526                .await
527                .context(OpenDalSnafu)?;
528            if let Err(err) = writer.write(data.clone()).await.context(OpenDalSnafu) {
529                cleaner.clean_by_file_id(region_file_id.file_id()).await;
530                return Err(err);
531            }
532            if let Err(err) = writer.close().await.context(OpenDalSnafu) {
533                cleaner.clean_by_file_id(region_file_id.file_id()).await;
534                return Err(err);
535            }
536            let mut metrics = Metrics::new(WriteType::Flush);
537            metrics.write_batch = start.elapsed();
538
539            if let Some(params) = index_build_params {
540                let start = Instant::now();
541                let builder = params.indexer_builder(
542                    self.puffin_manager_factory
543                        .build(self.object_store.clone(), path_provider),
544                    false,
545                    self.intermediate_manager.clone(),
546                );
547                sst_info.index_metadata =
548                    build_index_from_parquet_bytes(&builder, region_file_id, data).await;
549                metrics.update_index = start.elapsed();
550            }
551            Ok(metrics)
552        }
553    }
554
555    /// Lists the SST entries from the storage layer in the table directory.
556    pub fn storage_sst_entries(&self) -> impl Stream<Item = Result<StorageSstEntry>> + use<> {
557        let object_store = self.object_store.clone();
558        let table_dir = self.table_dir.clone();
559
560        try_stream! {
561            let mut lister = object_store
562                .lister_with(table_dir.as_str())
563                .recursive(true)
564                .await
565                .context(OpenDalSnafu)?;
566
567            while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? {
568                let metadata = entry.metadata();
569                if metadata.is_dir() {
570                    continue;
571                }
572
573                let path = entry.path();
574                if !path.ends_with(".parquet") && !path.ends_with(".puffin") {
575                    continue;
576                }
577
578                let file_size = metadata.content_length();
579                let file_size = if file_size == 0 { None } else { Some(file_size) };
580                let last_modified_ms = metadata
581                    .last_modified()
582                    .map(|ts| Timestamp::new_millisecond(ts.into_inner().as_millisecond()));
583
584                let entry = StorageSstEntry {
585                    file_path: path.to_string(),
586                    file_size,
587                    last_modified_ms,
588                    node_id: None,
589                };
590
591                yield entry;
592            }
593        }
594    }
595}
596
597/// `OperationType` represents the origin of the `SstWriteRequest`.
598#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
599pub enum OperationType {
600    Flush,
601    Compact,
602}
603
604/// Contents to build a SST.
605pub struct SstWriteRequest {
606    pub op_type: OperationType,
607    pub metadata: RegionMetadataRef,
608    pub source: FlatSource,
609    pub cache_manager: CacheManagerRef,
610    /// Optional uniform row sequence for writes that do not preserve sequences.
611    /// Compaction and LastNonNull flushes pass `None` to retain input sequences.
612    pub max_sequence: Option<SequenceNumber>,
613    pub sst_write_format: FormatType,
614
615    pub preserve_row_sequence: bool,
616
617    /// Configs for index
618    pub index_options: IndexOptions,
619    pub index_config: IndexConfig,
620    pub inverted_index_config: InvertedIndexConfig,
621    pub fulltext_index_config: FulltextIndexConfig,
622    pub bloom_filter_index_config: BloomFilterConfig,
623}
624
625/// Index inputs for SST bytes that were encoded outside [ParquetWriter].
626pub(crate) struct EncodedSstIndexBuildParams {
627    pub(crate) metadata: RegionMetadataRef,
628    pub(crate) index_options: IndexOptions,
629    pub(crate) inverted_index_config: InvertedIndexConfig,
630    pub(crate) fulltext_index_config: FulltextIndexConfig,
631    pub(crate) bloom_filter_index_config: BloomFilterConfig,
632}
633
634impl EncodedSstIndexBuildParams {
635    pub(crate) fn indexer_builder(
636        self,
637        puffin_manager: SstPuffinManager,
638        write_cache_enabled: bool,
639        intermediate_manager: IntermediateManager,
640    ) -> IndexerBuilderImpl {
641        IndexerBuilderImpl {
642            build_type: OperationType::Flush.into(),
643            metadata: self.metadata,
644            puffin_manager,
645            write_cache_enabled,
646            intermediate_manager,
647            index_options: self.index_options,
648            inverted_index_config: self.inverted_index_config,
649            fulltext_index_config: self.fulltext_index_config,
650            bloom_filter_index_config: self.bloom_filter_index_config,
651        }
652    }
653}
654
655/// Cleaner to remove temp files on the atomic write dir.
656pub(crate) struct TempFileCleaner {
657    region_id: RegionId,
658    object_store: ObjectStore,
659}
660
661impl TempFileCleaner {
662    /// Constructs the cleaner for the region and store.
663    pub(crate) fn new(region_id: RegionId, object_store: ObjectStore) -> Self {
664        Self {
665            region_id,
666            object_store,
667        }
668    }
669
670    /// Removes the SST and index file from the local atomic dir by the file id.
671    /// 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.
672    pub(crate) async fn clean_by_file_id(&self, file_id: FileId) {
673        let sst_key = IndexKey::new(self.region_id, file_id, FileType::Parquet).to_string();
674        let index_key = IndexKey::new(self.region_id, file_id, FileType::Puffin(0)).to_string();
675
676        Self::clean_atomic_dir_files(&self.object_store, &[&sst_key, &index_key]).await;
677    }
678
679    /// Removes the files from the local atomic dir by their names.
680    pub(crate) async fn clean_atomic_dir_files(
681        local_store: &ObjectStore,
682        names_to_remove: &[&str],
683    ) {
684        // We don't know the actual suffix of the file under atomic dir, so we have
685        // to list the dir. The cost should be acceptable as there won't be to many files.
686        let Ok(entries) = local_store.list(ATOMIC_WRITE_DIR).await.inspect_err(|e| {
687            if e.kind() != ErrorKind::NotFound {
688                common_telemetry::error!(e; "Failed to list tmp files for {:?}", names_to_remove)
689            }
690        }) else {
691            return;
692        };
693
694        // In our case, we can ensure the file id is unique so it is safe to remove all files
695        // with the same file id under the atomic write dir.
696        let actual_files: Vec<_> = entries
697            .into_iter()
698            .filter_map(|entry| {
699                if entry.metadata().is_dir() {
700                    return None;
701                }
702
703                // Remove name that matches files_to_remove.
704                let should_remove = names_to_remove
705                    .iter()
706                    .any(|file| entry.name().starts_with(file));
707                if should_remove {
708                    Some(entry.path().to_string())
709                } else {
710                    None
711                }
712            })
713            .collect();
714
715        common_telemetry::warn!(
716            "Clean files {:?} under atomic write dir for {:?}",
717            actual_files,
718            names_to_remove
719        );
720
721        if let Err(e) = local_store.delete_iter(actual_files).await {
722            common_telemetry::error!(e; "Failed to delete tmp file for {:?}", names_to_remove);
723        }
724    }
725}
726
727pub(crate) async fn new_fs_cache_store(root: &str) -> Result<ObjectStore> {
728    // Preserve native filesystem prefixes such as Windows UNC shares.
729    let atomic_write_dir = Path::new(root).join(ATOMIC_WRITE_DIR);
730    clean_dir(&atomic_write_dir.to_string_lossy()).await?;
731
732    // Compatible code. Remove this after a major release.
733    let old_atomic_temp_dir = join_dir(root, OLD_ATOMIC_WRITE_DIR);
734    clean_dir(&old_atomic_temp_dir).await?;
735
736    let builder = Fs::default()
737        .root(root)
738        .atomic_write_dir(&atomic_write_dir.to_string_lossy());
739    let store = ObjectStore::new(builder).context(OpenDalSnafu)?;
740
741    Ok(with_instrument_layers(store, false))
742}
743
744/// Clean the directory.
745async fn clean_dir(dir: &str) -> Result<()> {
746    if tokio::fs::try_exists(dir)
747        .await
748        .context(CleanDirSnafu { dir })?
749    {
750        tokio::fs::remove_dir_all(dir)
751            .await
752            .context(CleanDirSnafu { dir })?;
753    }
754
755    Ok(())
756}
757
758/// Path provider for SST file and index file.
759pub trait FilePathProvider: Send + Sync {
760    /// Creates index file path of given file id. Version default to 0, and not shown in the path.
761    fn build_index_file_path(&self, file_id: RegionFileId) -> String;
762
763    /// Creates index file path of given index id (with version support).
764    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String;
765
766    /// Creates SST file path of given file id.
767    fn build_sst_file_path(&self, file_id: RegionFileId) -> String;
768}
769
770/// Path provider that builds paths in local write cache.
771#[derive(Clone)]
772pub(crate) struct WriteCachePathProvider {
773    file_cache: FileCacheRef,
774}
775
776impl WriteCachePathProvider {
777    /// Creates a new `WriteCachePathProvider` instance.
778    pub fn new(file_cache: FileCacheRef) -> Self {
779        Self { file_cache }
780    }
781}
782
783impl FilePathProvider for WriteCachePathProvider {
784    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
785        let puffin_key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Puffin(0));
786        self.file_cache.cache_file_path(puffin_key)
787    }
788
789    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String {
790        let puffin_key = IndexKey::new(
791            index_id.region_id(),
792            index_id.file_id(),
793            FileType::Puffin(index_id.version),
794        );
795        self.file_cache.cache_file_path(puffin_key)
796    }
797
798    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
799        let parquet_file_key =
800            IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
801        self.file_cache.cache_file_path(parquet_file_key)
802    }
803}
804
805/// Path provider that builds paths in region storage path.
806#[derive(Clone, Debug)]
807pub(crate) struct RegionFilePathFactory {
808    pub(crate) table_dir: String,
809    pub(crate) path_type: PathType,
810}
811
812impl RegionFilePathFactory {
813    /// Creates a new `RegionFilePathFactory` instance.
814    pub fn new(table_dir: String, path_type: PathType) -> Self {
815        Self {
816            table_dir,
817            path_type,
818        }
819    }
820}
821
822impl FilePathProvider for RegionFilePathFactory {
823    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
824        location::index_file_path_legacy(&self.table_dir, file_id, self.path_type)
825    }
826
827    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String {
828        location::index_file_path(&self.table_dir, index_id, self.path_type)
829    }
830
831    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
832        location::sst_file_path(&self.table_dir, file_id, self.path_type)
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use std::path::PathBuf;
839
840    use bytes::Bytes;
841    use common_test_util::temp_dir::create_temp_dir;
842
843    use super::*;
844    use crate::cache::CacheManager;
845    use crate::cache::test_util::new_fs_store;
846    use crate::test_util::TestEnv;
847    use crate::test_util::sst_util::WriteChunkRecorder;
848
849    #[rstest::rstest]
850    #[tokio::test]
851    async fn test_put_sst_uses_configured_buffer_size(
852        #[values(false, true)] enable_write_cache: bool,
853        #[values(1024, 4096)] chunk_size: usize,
854    ) {
855        let mut env = TestEnv::new().await;
856        let remote_chunks = WriteChunkRecorder::default();
857        let remote_store = env.init_object_store_manager().layer(remote_chunks.layer());
858        let local_dir = create_temp_dir("encoded-sst-cache");
859        let local_chunks = WriteChunkRecorder::default();
860        let local_store =
861            new_fs_store(local_dir.path().to_str().unwrap()).layer(local_chunks.layer());
862        let write_cache = if enable_write_cache {
863            Some(
864                env.create_write_cache(local_store.clone(), ReadableSize::mb(10))
865                    .await,
866            )
867        } else {
868            None
869        };
870        let cache_manager = Arc::new(
871            CacheManager::builder()
872                .write_cache(write_cache.clone())
873                .build(),
874        );
875        let access_layer = AccessLayer::new(
876            "test",
877            PathType::Bare,
878            remote_store.clone(),
879            env.get_puffin_manager(),
880            env.get_intermediate_manager(),
881        );
882        let file_id = RegionFileId::new(RegionId::new(1024, 1), FileId::random());
883        // Two full chunks and a partial tail distinguish the configured size from the default.
884        let encoded = Bytes::from(
885            (0..2 * chunk_size + 17)
886                .map(|i| (i % 251) as u8)
887                .collect::<Vec<_>>(),
888        );
889        access_layer
890            .put_sst(
891                &encoded,
892                file_id.region_id(),
893                &mut SstInfo {
894                    file_id: file_id.file_id(),
895                    ..Default::default()
896                },
897                &cache_manager,
898                ReadableSize(chunk_size as u64),
899                None,
900            )
901            .await
902            .unwrap();
903
904        let remote_path = location::sst_file_path("test", file_id, PathType::Bare);
905        remote_chunks.assert_chunks(&remote_path, chunk_size, encoded.len());
906        assert_eq!(
907            remote_store.read(&remote_path).await.unwrap().to_bytes(),
908            encoded
909        );
910        if let Some(write_cache) = write_cache {
911            let key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
912            let cache_path = write_cache.file_cache().cache_file_path(key);
913            local_chunks.assert_chunks(&cache_path, chunk_size, encoded.len());
914            assert_eq!(
915                local_store.read(&cache_path).await.unwrap().to_bytes(),
916                encoded
917            );
918        }
919    }
920
921    #[tokio::test]
922    async fn test_new_fs_cache_store() {
923        let root = common_test_util::temp_dir::create_temp_dir("fs-cache-store");
924        let dirs = [
925            root.path().join(ATOMIC_WRITE_DIR),
926            PathBuf::from(join_dir(
927                root.path().to_str().unwrap(),
928                OLD_ATOMIC_WRITE_DIR,
929            )),
930        ];
931        for dir in &dirs {
932            tokio::fs::create_dir_all(dir).await.unwrap();
933            tokio::fs::write(dir.join("stale"), b"stale").await.unwrap();
934        }
935        let store = new_fs_cache_store(root.path().to_str().unwrap())
936            .await
937            .unwrap();
938        for dir in &dirs {
939            assert!(!dir.join("stale").exists());
940        }
941        store.write("index", "contents").await.unwrap();
942        assert_eq!(
943            tokio::fs::read(root.path().join("index")).await.unwrap(),
944            b"contents"
945        );
946    }
947}