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 prometheus::HistogramVec;
30use smallvec::SmallVec;
31use snafu::ResultExt;
32use store_api::metadata::RegionMetadataRef;
33use store_api::region_request::PathType;
34use store_api::sst_entry::StorageSstEntry;
35use store_api::storage::{FileId, RegionId, SequenceNumber};
36use strum::IntoStaticStr;
37
38use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey};
39use crate::cache::write_cache::SstUploadRequest;
40use crate::cache::{CacheManagerRef, SstMetaPreparation, prepare_sst_meta_sync};
41use crate::config::{BloomFilterConfig, FulltextIndexConfig, IndexConfig, InvertedIndexConfig};
42use crate::error::{
43    CleanDirSnafu, DeleteIndexSnafu, DeleteIndexesSnafu, DeleteSstsSnafu, OpenDalSnafu, Result,
44};
45use crate::metrics::{COMPACTION_STAGE_ELAPSED, FLUSH_ELAPSED, TAIL_REPLAY_ELAPSED};
46use crate::read::FlatSource;
47use crate::region::options::IndexOptions;
48use crate::series_index::samples::bulk::NarthexBulkPart;
49use crate::sst::file::{FileHandle, RegionFileId, RegionIndexId};
50use crate::sst::index::build::IndexBuildInputs;
51use crate::sst::index::intermediate::IntermediateManager;
52use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinManager};
53use crate::sst::index::registry::IndexRegistry;
54use crate::sst::index::{IndexerBuilderImpl, build_index_from_parquet_bytes};
55use crate::sst::location::{self, region_dir_from_table_dir};
56use crate::sst::parquet::reader::ParquetReaderBuilder;
57use crate::sst::parquet::writer::{ParquetWriter, SstWriteContext};
58use crate::sst::parquet::{SstInfo, WriteOptions};
59use crate::sst::{DEFAULT_WRITE_CONCURRENCY, FormatType};
60
61pub type AccessLayerRef = Arc<AccessLayer>;
62/// SST write results.
63pub type SstInfoArray = SmallVec<[SstInfo; 2]>;
64
65/// Write operation type.
66#[derive(Eq, PartialEq, Debug, Clone, Copy, IntoStaticStr)]
67pub enum WriteType {
68    /// Writes from flush
69    Flush,
70    /// Writes from compaction.
71    Compaction,
72    /// Writes from the replay of pending WAL tails.
73    TailReplay,
74}
75
76#[derive(Debug)]
77pub struct Metrics {
78    pub(crate) write_type: WriteType,
79    pub(crate) iter_source: Duration,
80    pub(crate) write_batch: Duration,
81    pub(crate) update_index: Duration,
82    pub(crate) upload_parquet: Duration,
83    pub(crate) upload_puffin: Duration,
84    pub(crate) compact_memtable: Duration,
85}
86
87impl Metrics {
88    pub fn new(write_type: WriteType) -> Self {
89        Self {
90            write_type,
91            iter_source: Default::default(),
92            write_batch: Default::default(),
93            update_index: Default::default(),
94            upload_parquet: Default::default(),
95            upload_puffin: Default::default(),
96            compact_memtable: Default::default(),
97        }
98    }
99
100    pub(crate) fn merge(mut self, other: Self) -> Self {
101        assert_eq!(self.write_type, other.write_type);
102        self.iter_source += other.iter_source;
103        self.write_batch += other.write_batch;
104        self.update_index += other.update_index;
105        self.upload_parquet += other.upload_parquet;
106        self.upload_puffin += other.upload_puffin;
107        self.compact_memtable += other.compact_memtable;
108        self
109    }
110
111    pub(crate) fn observe(self) {
112        let elapsed: &HistogramVec = match self.write_type {
113            WriteType::Flush => &FLUSH_ELAPSED,
114            WriteType::Compaction => &COMPACTION_STAGE_ELAPSED,
115            WriteType::TailReplay => &TAIL_REPLAY_ELAPSED,
116        };
117        let stages = [
118            ("iter_source", self.iter_source),
119            ("write_batch", self.write_batch),
120            ("update_index", self.update_index),
121            ("upload_parquet", self.upload_parquet),
122            ("upload_puffin", self.upload_puffin),
123        ];
124        for (stage, duration) in stages {
125            elapsed
126                .with_label_values(&[stage])
127                .observe(duration.as_secs_f64());
128        }
129        if !self.compact_memtable.is_zero() {
130            elapsed
131                .with_label_values(&["compact_memtable"])
132                .observe(self.compact_memtable.as_secs_f64());
133        }
134    }
135}
136
137/// A layer to access SST files under the same directory.
138pub struct AccessLayer {
139    table_dir: String,
140    /// Path type for generating file paths.
141    path_type: PathType,
142    /// Target object store.
143    object_store: ObjectStore,
144    /// Puffin manager factory for index.
145    puffin_manager_factory: PuffinManagerFactory,
146    /// Intermediate manager for inverted index.
147    intermediate_manager: IntermediateManager,
148    file_protection: Option<crate::engine::region_hook::RegionHookRef>,
149}
150
151impl std::fmt::Debug for AccessLayer {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("AccessLayer")
154            .field("table_dir", &self.table_dir)
155            .finish()
156    }
157}
158
159impl AccessLayer {
160    /// Returns a new [AccessLayer] for specific `table_dir`.
161    pub fn new(
162        table_dir: impl Into<String>,
163        path_type: PathType,
164        object_store: ObjectStore,
165        puffin_manager_factory: PuffinManagerFactory,
166        intermediate_manager: IntermediateManager,
167    ) -> AccessLayer {
168        AccessLayer {
169            table_dir: table_dir.into(),
170            path_type,
171            object_store,
172            puffin_manager_factory,
173            intermediate_manager,
174            file_protection: None,
175        }
176    }
177
178    /// Attaches the engine's deletion-time protection provider for local purging.
179    pub(crate) fn with_file_protection(
180        mut self,
181        hook: Option<crate::engine::region_hook::RegionHookRef>,
182    ) -> Self {
183        self.file_protection = hook;
184        self
185    }
186
187    pub(crate) async fn is_file_protected(&self, file: RegionFileId) -> crate::error::Result<bool> {
188        match &self.file_protection {
189            Some(hook) => Ok(hook
190                .protected_sst_files(self, &[file])
191                .await?
192                .contains(&file)),
193            None => Ok(false),
194        }
195    }
196
197    /// Returns the directory of the table.
198    pub fn table_dir(&self) -> &str {
199        &self.table_dir
200    }
201
202    /// Returns the object store of the layer.
203    pub fn object_store(&self) -> &ObjectStore {
204        &self.object_store
205    }
206
207    /// Returns the path type of the layer.
208    pub fn path_type(&self) -> PathType {
209        self.path_type
210    }
211
212    /// Returns the puffin manager factory.
213    pub fn puffin_manager_factory(&self) -> &PuffinManagerFactory {
214        &self.puffin_manager_factory
215    }
216
217    /// Returns the intermediate manager.
218    pub fn intermediate_manager(&self) -> &IntermediateManager {
219        &self.intermediate_manager
220    }
221
222    /// Build the puffin manager.
223    pub(crate) fn build_puffin_manager(&self) -> SstPuffinManager {
224        let store = self.object_store.clone();
225        let path_provider =
226            RegionFilePathFactory::new(self.table_dir().to_string(), self.path_type());
227        self.puffin_manager_factory.build(store, path_provider)
228    }
229
230    pub(crate) async fn delete_index(
231        &self,
232        index_file_id: RegionIndexId,
233    ) -> Result<(), crate::error::Error> {
234        let path = location::index_file_path(
235            &self.table_dir,
236            RegionIndexId::new(index_file_id.file_id, index_file_id.version),
237            self.path_type,
238        );
239        self.object_store
240            .delete(&path)
241            .await
242            .context(DeleteIndexSnafu {
243                file_id: index_file_id.file_id(),
244            })?;
245        Ok(())
246    }
247
248    /// Deletes objects belonging to a fenced artifact in its canonical directory.
249    pub(crate) async fn delete_narthex_artifact(
250        &self,
251        region_id: RegionId,
252        file_id: FileId,
253    ) -> Result<()> {
254        let region_dir = self.build_region_dir(region_id);
255        let dir = location::narthex_file_dir(&region_dir, file_id);
256        self.object_store
257            .delete_with(&dir)
258            .recursive(true)
259            .await
260            .context(OpenDalSnafu)?;
261        Ok(())
262    }
263
264    pub(crate) async fn delete_ssts(
265        &self,
266        region_id: RegionId,
267        file_ids: &[FileId],
268    ) -> Result<(), crate::error::Error> {
269        if file_ids.is_empty() {
270            return Ok(());
271        }
272
273        let attempted_files = file_ids.to_vec();
274        // Deleter does not normalize leading slashes like Operator::delete does.
275        let paths: Vec<_> = file_ids
276            .iter()
277            .map(|file_id| {
278                location::sst_file_path(
279                    &self.table_dir,
280                    RegionFileId::new(region_id, *file_id),
281                    self.path_type,
282                )
283                .trim_start_matches('/')
284                .to_string()
285            })
286            .collect();
287
288        let mut deleter = self
289            .object_store
290            .deleter()
291            .await
292            .with_context(|_| DeleteSstsSnafu {
293                region_id,
294                file_ids: attempted_files.clone(),
295            })?;
296        deleter
297            .delete_iter(paths)
298            .await
299            .with_context(|_| DeleteSstsSnafu {
300                region_id,
301                file_ids: attempted_files.clone(),
302            })?;
303        deleter.close().await.with_context(|_| DeleteSstsSnafu {
304            region_id,
305            file_ids: attempted_files,
306        })?;
307
308        Ok(())
309    }
310
311    pub(crate) async fn delete_indexes(
312        &self,
313        index_ids: &[RegionIndexId],
314    ) -> Result<(), crate::error::Error> {
315        if index_ids.is_empty() {
316            return Ok(());
317        }
318
319        let file_ids: Vec<_> = index_ids
320            .iter()
321            .map(|index_id| index_id.file_id())
322            .collect();
323        let paths: Vec<_> = index_ids
324            .iter()
325            .map(|index_id| {
326                location::index_file_path(&self.table_dir, *index_id, self.path_type)
327                    .trim_start_matches('/')
328                    .to_string()
329            })
330            .collect();
331
332        let mut deleter = self
333            .object_store
334            .deleter()
335            .await
336            .context(DeleteIndexesSnafu {
337                file_ids: file_ids.clone(),
338            })?;
339        deleter
340            .delete_iter(paths)
341            .await
342            .context(DeleteIndexesSnafu {
343                file_ids: file_ids.clone(),
344            })?;
345        deleter
346            .close()
347            .await
348            .context(DeleteIndexesSnafu { file_ids })?;
349
350        Ok(())
351    }
352
353    /// Returns the directory of the region in the table.
354    pub fn build_region_dir(&self, region_id: RegionId) -> String {
355        region_dir_from_table_dir(&self.table_dir, region_id, self.path_type)
356    }
357
358    /// Returns a reader builder for specific `file`.
359    pub(crate) fn read_sst(&self, file: FileHandle) -> ParquetReaderBuilder {
360        ParquetReaderBuilder::new(
361            self.table_dir.clone(),
362            self.path_type,
363            file,
364            self.object_store.clone(),
365        )
366    }
367
368    /// Writes a SST with specific `file_id` and `metadata` to the layer.
369    ///
370    /// Returns the info of the SST. If no data written, returns None.
371    pub async fn write_sst(
372        &self,
373        request: SstWriteRequest,
374        write_opts: &WriteOptions,
375        metrics: &mut Metrics,
376    ) -> Result<SstInfoArray> {
377        self.write_sst_inner(request, write_opts, metrics, None)
378            .await
379    }
380
381    /// Writes SSTs with explicit ownership and cooperative cancellation.
382    pub(crate) async fn write_sst_with_context(
383        &self,
384        request: SstWriteRequest,
385        write_opts: &WriteOptions,
386        metrics: &mut Metrics,
387        context: SstWriteContext,
388    ) -> Result<SstInfoArray> {
389        self.write_sst_inner(request, write_opts, metrics, Some(context))
390            .await
391    }
392
393    async fn write_sst_inner(
394        &self,
395        mut request: SstWriteRequest,
396        write_opts: &WriteOptions,
397        metrics: &mut Metrics,
398        context: Option<SstWriteContext>,
399    ) -> Result<SstInfoArray> {
400        // Rollover can create multiple SSTs from this request, so no output may
401        // reuse summaries covering the complete input set.
402        if let Some(provider) = &mut request.index_build_inputs {
403            provider.can_merge_inputs &= write_opts.max_file_size.is_none();
404        }
405        let context = context.unwrap_or_default();
406        if request.sst_write_format == FormatType::Narthex {
407            if context.limits.is_some() {
408                return crate::error::UnsupportedOperationSnafu {
409                    err_msg: "Narthex table compaction is unsupported",
410                }
411                .fail();
412            }
413            return crate::sst::narthex::write_samples(
414                self,
415                request,
416                context.guard,
417                context.cancellation,
418            )
419            .await;
420        }
421        let limits = context.limits;
422        let guard = context.guard.clone();
423        let cancellation = context.cancellation.clone();
424        let op_type = request.op_type;
425        let region_id = request.metadata.region_id;
426        let region_metadata = request.metadata.clone();
427        let cache_manager = request.cache_manager.clone();
428        let override_sequence = if request.preserve_row_sequence {
429            None
430        } else {
431            request.max_sequence
432        };
433
434        let sst_info = if let Some(write_cache) = cache_manager.write_cache()
435            && limits.is_none()
436        {
437            // Write to the write cache.
438            write_cache
439                .write_and_upload_sst_with_context(
440                    request,
441                    SstUploadRequest {
442                        dest_path_provider: RegionFilePathFactory::new(
443                            self.table_dir.clone(),
444                            self.path_type,
445                        ),
446                        remote_store: self.object_store.clone(),
447                    },
448                    write_opts,
449                    metrics,
450                    context,
451                )
452                .await?
453        } else {
454            // The write cache does not enforce SstWriteLimits, so bounded writes
455            // bypass it.
456            let store = self.object_store.clone();
457            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
458            let puffin_factory = self.puffin_manager_factory.clone();
459            #[cfg(feature = "enterprise")]
460            let puffin_factory = if let Some(limits) = limits {
461                puffin_factory.with_upload_limits(limits.upload_limits)
462            } else {
463                puffin_factory
464            };
465            let indexer_builder = IndexerBuilderImpl {
466                index_build_inputs: request.index_build_inputs,
467                build_type: request.op_type.into(),
468                metadata: request.metadata.clone(),
469                puffin_manager: puffin_factory.build(store, path_provider.clone()),
470                write_cache_enabled: false,
471                intermediate_manager: self.intermediate_manager.clone(),
472                index_options: request.index_options,
473                registry: Arc::new(IndexRegistry::new(
474                    request.inverted_index_config,
475                    request.fulltext_index_config,
476                    request.bloom_filter_index_config,
477                )),
478            };
479            // We disable write cache on file system but we still use atomic write.
480            // TODO(yingwen): If we support other non-fs stores without the write cache, then
481            // we may have find a way to check whether we need the cleaner.
482            let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
483            let writer = ParquetWriter::new_with_object_store(
484                self.object_store.clone(),
485                request.metadata,
486                request.index_config,
487                indexer_builder,
488                path_provider,
489                metrics,
490            )
491            .await
492            .with_file_cleaner(cleaner)
493            .with_write_concurrency(if limits.is_some() {
494                1
495            } else {
496                crate::sst::DEFAULT_WRITE_CONCURRENCY
497            })
498            .with_write_guard(guard)
499            .with_cancellation(cancellation)
500            .with_memory_limits(limits);
501            #[cfg(feature = "enterprise")]
502            let writer = if let Some(limits) = limits {
503                writer.with_upload_limits(limits.upload_limits)
504            } else {
505                writer
506            };
507            let mut writer = writer;
508            match request.sst_write_format {
509                FormatType::PrimaryKey => {
510                    writer
511                        .write_all_flat_as_primary_key(
512                            request.source,
513                            override_sequence,
514                            write_opts,
515                        )
516                        .await?
517                }
518                FormatType::Narthex => {
519                    return crate::error::UnsupportedOperationSnafu {
520                        err_msg: "narthex writer must bypass Parquet cache",
521                    }
522                    .fail();
523                }
524                FormatType::Flat => {
525                    writer
526                        .write_all_flat(request.source, override_sequence, write_opts)
527                        .await?
528                }
529            }
530        };
531
532        // Put parquet metadata to cache manager.
533        if !sst_info.is_empty() && cache_manager.sst_meta_cache_on_write_enabled() {
534            let runtime = match op_type {
535                OperationType::Compact => common_runtime::compact_runtime(),
536                OperationType::Flush => common_runtime::global_runtime(),
537            };
538            for sst in &sst_info {
539                if let Some(parquet_metadata) = &sst.file_metadata {
540                    let file_id = RegionFileId::new(region_id, sst.file_id);
541                    let file_path = format!(
542                        "region_id={}, file_id={}",
543                        file_id.region_id(),
544                        file_id.file_id()
545                    );
546                    let page_index_policy = if parquet_metadata.offset_index().is_some() {
547                        PageIndexPolicy::Optional
548                    } else {
549                        PageIndexPolicy::Skip
550                    };
551                    let parquet_metadata = parquet_metadata.clone();
552                    let region_metadata = region_metadata.clone();
553                    let cache_manager = cache_manager.clone();
554                    // Prepare and cache metadata in the background without delaying the SST write.
555                    let task_runtime = runtime.clone();
556                    runtime.spawn(async move {
557                        let preparation = task_runtime.spawn_blocking(move || {
558                            prepare_sst_meta_sync(
559                                &file_path,
560                                Arc::unwrap_or_clone(parquet_metadata),
561                                Some(region_metadata),
562                                page_index_policy,
563                            )
564                        }).await.context(crate::error::JoinSnafu).and_then(|result| result);
565                        match preparation {
566                            Ok(SstMetaPreparation::Prepared(metadata)) => {
567                                cache_manager.put_compact_sst_meta(file_id, metadata.compact);
568                                cache_manager.put_sst_meta_data(file_id, metadata.decoded).await;
569                            }
570                            Ok(SstMetaPreparation::DecodedOnly { encoding_error, .. }) => warn!(
571                                encoding_error;
572                                "Failed to encode parquet metadata for cache, file: {}",
573                                file_id.file_id()
574                            ),
575                            Err(err) => {
576                                warn!(err; "Failed to cache parquet metadata for {}", file_id.file_id());
577                            }
578                        }
579                    });
580                }
581            }
582        }
583
584        Ok(sst_info)
585    }
586
587    /// Uploads the complete sample parts before making their codec manifest available.
588    pub(crate) async fn put_narthex_part(
589        &self,
590        region: RegionId,
591        artifact: &NarthexBulkPart,
592        cache_manager: &CacheManagerRef,
593    ) -> Result<()> {
594        let prefix = crate::sst::location::narthex_file_dir(
595            &self.build_region_dir(region),
596            artifact.file_id(),
597        );
598        artifact
599            .upload(
600                &self.object_store,
601                &prefix,
602                region,
603                cache_manager.write_cache().map(Arc::as_ref),
604            )
605            .await
606    }
607
608    /// Puts encoded SST bytes to the write cache (if enabled) and uploads it to the object store.
609    ///
610    /// Builds the SST's indexes from `data` into `sst_info.index_metadata` when
611    /// `index_build_params` is set.
612    #[allow(clippy::too_many_arguments)]
613    pub(crate) async fn put_sst(
614        &self,
615        data: &bytes::Bytes,
616        region_id: RegionId,
617        sst_info: &mut SstInfo,
618        cache_manager: &CacheManagerRef,
619        write_buffer_size: ReadableSize,
620        index_build_params: Option<EncodedSstIndexBuildParams>,
621        metrics: &mut Metrics,
622    ) -> Result<()> {
623        let region_file_id = RegionFileId::new(region_id, sst_info.file_id);
624        if let Some(write_cache) = cache_manager.write_cache() {
625            // Write to cache and upload to remote store
626            let upload_request = SstUploadRequest {
627                dest_path_provider: RegionFilePathFactory::new(
628                    self.table_dir.clone(),
629                    self.path_type,
630                ),
631                remote_store: self.object_store.clone(),
632            };
633            write_cache
634                .put_and_upload_sst(
635                    data,
636                    region_id,
637                    sst_info,
638                    upload_request,
639                    write_buffer_size,
640                    index_build_params,
641                    metrics,
642                )
643                .await
644        } else {
645            let start = Instant::now();
646            let cleaner =
647                TempFileCleaner::new(region_file_id.region_id(), self.object_store.clone());
648            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
649            let sst_file_path = path_provider.build_sst_file_path(region_file_id);
650            let mut writer = self
651                .object_store
652                .writer_with(&sst_file_path)
653                .chunk(write_buffer_size.as_bytes() as usize)
654                .concurrent(DEFAULT_WRITE_CONCURRENCY)
655                .await
656                .context(OpenDalSnafu)?;
657            if let Err(err) = writer.write(data.clone()).await.context(OpenDalSnafu) {
658                cleaner.clean_by_file_id(region_file_id.file_id()).await;
659                return Err(err);
660            }
661            if let Err(err) = writer.close().await.context(OpenDalSnafu) {
662                cleaner.clean_by_file_id(region_file_id.file_id()).await;
663                return Err(err);
664            }
665            metrics.write_batch = start.elapsed();
666
667            if let Some(params) = index_build_params {
668                let start = Instant::now();
669                let builder = params.indexer_builder(
670                    self.puffin_manager_factory
671                        .build(self.object_store.clone(), path_provider),
672                    false,
673                    self.intermediate_manager.clone(),
674                );
675                sst_info.index_metadata =
676                    build_index_from_parquet_bytes(&builder, region_file_id, data).await;
677                metrics.update_index = start.elapsed();
678            }
679            Ok(())
680        }
681    }
682
683    /// Lists the SST entries from the storage layer in the table directory.
684    pub fn storage_sst_entries(&self) -> impl Stream<Item = Result<StorageSstEntry>> + use<> {
685        let object_store = self.object_store.clone();
686        let table_dir = self.table_dir.clone();
687
688        try_stream! {
689            let mut lister = object_store
690                .lister_with(table_dir.as_str())
691                .recursive(true)
692                .await
693                .context(OpenDalSnafu)?;
694
695            while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? {
696                let metadata = entry.metadata();
697                if metadata.is_dir() {
698                    continue;
699                }
700
701                let path = entry.path();
702                if !path.ends_with(".parquet") && !path.ends_with(".puffin")
703                    && crate::sst::location::parse_narthex_file_id(path).is_none() {
704                    continue;
705                }
706
707                let file_size = metadata.content_length();
708                let file_size = if file_size == 0 { None } else { Some(file_size) };
709                let last_modified_ms = metadata
710                    .last_modified()
711                    .map(|ts| Timestamp::new_millisecond(ts.into_inner().as_millisecond()));
712
713                let entry = StorageSstEntry {
714                    file_path: path.to_string(),
715                    file_size,
716                    last_modified_ms,
717                    node_id: None,
718                };
719
720                yield entry;
721            }
722        }
723    }
724}
725
726/// `OperationType` represents the origin of the `SstWriteRequest`.
727#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
728pub enum OperationType {
729    Flush,
730    Compact,
731}
732
733/// Contents to build a SST.
734pub struct SstWriteRequest {
735    /// Optional preplanned index work and physical input files.
736    pub index_build_inputs: Option<IndexBuildInputs>,
737    pub op_type: OperationType,
738    pub metadata: RegionMetadataRef,
739    pub source: FlatSource,
740    pub cache_manager: CacheManagerRef,
741    /// Optional uniform row sequence for writes that do not preserve sequences.
742    /// Compaction and LastNonNull flushes pass `None` to retain input sequences.
743    pub max_sequence: Option<SequenceNumber>,
744    pub sst_write_format: FormatType,
745
746    pub preserve_row_sequence: bool,
747
748    /// Configs for index
749    pub index_options: IndexOptions,
750    pub index_config: IndexConfig,
751    pub inverted_index_config: InvertedIndexConfig,
752    pub fulltext_index_config: FulltextIndexConfig,
753    pub bloom_filter_index_config: BloomFilterConfig,
754}
755
756/// Index inputs for SST bytes that were encoded outside [ParquetWriter].
757pub(crate) struct EncodedSstIndexBuildParams {
758    pub(crate) metadata: RegionMetadataRef,
759    pub(crate) index_options: IndexOptions,
760    pub(crate) inverted_index_config: InvertedIndexConfig,
761    pub(crate) fulltext_index_config: FulltextIndexConfig,
762    pub(crate) bloom_filter_index_config: BloomFilterConfig,
763}
764
765impl EncodedSstIndexBuildParams {
766    pub(crate) fn indexer_builder(
767        self,
768        puffin_manager: SstPuffinManager,
769        write_cache_enabled: bool,
770        intermediate_manager: IntermediateManager,
771    ) -> IndexerBuilderImpl {
772        IndexerBuilderImpl {
773            index_build_inputs: None,
774            build_type: OperationType::Flush.into(),
775            metadata: self.metadata,
776            puffin_manager,
777            write_cache_enabled,
778            intermediate_manager,
779            index_options: self.index_options,
780            registry: Arc::new(IndexRegistry::new(
781                self.inverted_index_config,
782                self.fulltext_index_config,
783                self.bloom_filter_index_config,
784            )),
785        }
786    }
787}
788
789/// Cleaner to remove temp files on the atomic write dir.
790pub(crate) struct TempFileCleaner {
791    region_id: RegionId,
792    object_store: ObjectStore,
793}
794
795impl TempFileCleaner {
796    /// Constructs the cleaner for the region and store.
797    pub(crate) fn new(region_id: RegionId, object_store: ObjectStore) -> Self {
798        Self {
799            region_id,
800            object_store,
801        }
802    }
803
804    /// Removes the SST and index file from the local atomic dir by the file id.
805    /// 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.
806    pub(crate) async fn clean_by_file_id(&self, file_id: FileId) {
807        let sst_key = IndexKey::new(self.region_id, file_id, FileType::Parquet).to_string();
808        let index_key = IndexKey::new(self.region_id, file_id, FileType::Puffin(0)).to_string();
809
810        Self::clean_atomic_dir_files(&self.object_store, &[&sst_key, &index_key]).await;
811    }
812
813    /// Removes the files from the local atomic dir by their names.
814    pub(crate) async fn clean_atomic_dir_files(
815        local_store: &ObjectStore,
816        names_to_remove: &[&str],
817    ) {
818        // We don't know the actual suffix of the file under atomic dir, so we have
819        // to list the dir. The cost should be acceptable as there won't be to many files.
820        let Ok(entries) = local_store.list(ATOMIC_WRITE_DIR).await.inspect_err(|e| {
821            if e.kind() != ErrorKind::NotFound {
822                common_telemetry::error!(e; "Failed to list tmp files for {:?}", names_to_remove)
823            }
824        }) else {
825            return;
826        };
827
828        // In our case, we can ensure the file id is unique so it is safe to remove all files
829        // with the same file id under the atomic write dir.
830        let actual_files: Vec<_> = entries
831            .into_iter()
832            .filter_map(|entry| {
833                if entry.metadata().is_dir() {
834                    return None;
835                }
836
837                // Remove name that matches files_to_remove.
838                let should_remove = names_to_remove
839                    .iter()
840                    .any(|file| entry.name().starts_with(file));
841                if should_remove {
842                    Some(entry.path().to_string())
843                } else {
844                    None
845                }
846            })
847            .collect();
848
849        common_telemetry::warn!(
850            "Clean files {:?} under atomic write dir for {:?}",
851            actual_files,
852            names_to_remove
853        );
854
855        if let Err(e) = local_store.delete_iter(actual_files).await {
856            common_telemetry::error!(e; "Failed to delete tmp file for {:?}", names_to_remove);
857        }
858    }
859}
860
861pub(crate) async fn new_fs_cache_store(root: &str) -> Result<ObjectStore> {
862    // Preserve native filesystem prefixes such as Windows UNC shares.
863    let atomic_write_dir = Path::new(root).join(ATOMIC_WRITE_DIR);
864    clean_dir(&atomic_write_dir.to_string_lossy()).await?;
865
866    // A process can exit after the Narthex codec closes a part but before its upload.
867    let narthex_stage =
868        Path::new(root).join(crate::cache::write_cache::WriteCache::narthex_stage(""));
869    clean_dir(&narthex_stage.to_string_lossy()).await?;
870
871    // Compatible code. Remove this after a major release.
872    let old_atomic_temp_dir = join_dir(root, OLD_ATOMIC_WRITE_DIR);
873    clean_dir(&old_atomic_temp_dir).await?;
874
875    let builder = Fs::default()
876        .root(root)
877        .atomic_write_dir(&atomic_write_dir.to_string_lossy());
878    let store = ObjectStore::new(builder).context(OpenDalSnafu)?;
879
880    Ok(with_instrument_layers(store, false))
881}
882
883/// Clean the directory.
884async fn clean_dir(dir: &str) -> Result<()> {
885    if tokio::fs::try_exists(dir)
886        .await
887        .context(CleanDirSnafu { dir })?
888    {
889        tokio::fs::remove_dir_all(dir)
890            .await
891            .context(CleanDirSnafu { dir })?;
892    }
893
894    Ok(())
895}
896
897/// Path provider for SST file and index file.
898pub trait FilePathProvider: Send + Sync {
899    /// Creates index file path of given file id. Version default to 0, and not shown in the path.
900    fn build_index_file_path(&self, file_id: RegionFileId) -> String;
901
902    /// Creates index file path of given index id (with version support).
903    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String;
904
905    /// Creates SST file path of given file id.
906    fn build_sst_file_path(&self, file_id: RegionFileId) -> String;
907}
908
909/// Path provider that builds paths in local write cache.
910#[derive(Clone)]
911pub(crate) struct WriteCachePathProvider {
912    file_cache: FileCacheRef,
913}
914
915impl WriteCachePathProvider {
916    /// Creates a new `WriteCachePathProvider` instance.
917    pub fn new(file_cache: FileCacheRef) -> Self {
918        Self { file_cache }
919    }
920}
921
922impl FilePathProvider for WriteCachePathProvider {
923    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
924        let puffin_key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Puffin(0));
925        self.file_cache.cache_file_path(puffin_key)
926    }
927
928    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String {
929        let puffin_key = IndexKey::new(
930            index_id.region_id(),
931            index_id.file_id(),
932            FileType::Puffin(index_id.version),
933        );
934        self.file_cache.cache_file_path(puffin_key)
935    }
936
937    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
938        let parquet_file_key =
939            IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
940        self.file_cache.cache_file_path(parquet_file_key)
941    }
942}
943
944/// Path provider that builds paths in region storage path.
945#[derive(Clone, Debug)]
946pub(crate) struct RegionFilePathFactory {
947    pub(crate) table_dir: String,
948    pub(crate) path_type: PathType,
949}
950
951impl RegionFilePathFactory {
952    /// Creates a new `RegionFilePathFactory` instance.
953    pub fn new(table_dir: String, path_type: PathType) -> Self {
954        Self {
955            table_dir,
956            path_type,
957        }
958    }
959}
960
961impl FilePathProvider for RegionFilePathFactory {
962    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
963        location::index_file_path_legacy(&self.table_dir, file_id, self.path_type)
964    }
965
966    fn build_index_file_path_with_version(&self, index_id: RegionIndexId) -> String {
967        location::index_file_path(&self.table_dir, index_id, self.path_type)
968    }
969
970    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
971        location::sst_file_path(&self.table_dir, file_id, self.path_type)
972    }
973}
974
975#[cfg(test)]
976mod tests {
977    use std::path::PathBuf;
978
979    use bytes::Bytes;
980    use common_test_util::temp_dir::create_temp_dir;
981
982    use super::*;
983    use crate::cache::CacheManager;
984    use crate::cache::test_util::new_fs_store;
985    use crate::test_util::TestEnv;
986    use crate::test_util::sst_util::WriteChunkRecorder;
987
988    #[rstest::rstest]
989    #[tokio::test]
990    async fn test_put_sst_uses_configured_buffer_size(
991        #[values(false, true)] enable_write_cache: bool,
992        #[values(1024, 4096)] chunk_size: usize,
993    ) {
994        let mut env = TestEnv::new().await;
995        let remote_chunks = WriteChunkRecorder::default();
996        let remote_store = env.init_object_store_manager().layer(remote_chunks.layer());
997        let local_dir = create_temp_dir("encoded-sst-cache");
998        let local_chunks = WriteChunkRecorder::default();
999        let local_store =
1000            new_fs_store(local_dir.path().to_str().unwrap()).layer(local_chunks.layer());
1001        let write_cache = if enable_write_cache {
1002            Some(
1003                env.create_write_cache(local_store.clone(), ReadableSize::mb(10))
1004                    .await,
1005            )
1006        } else {
1007            None
1008        };
1009        let cache_manager = Arc::new(
1010            CacheManager::builder()
1011                .write_cache(write_cache.clone())
1012                .build(),
1013        );
1014        let access_layer = AccessLayer::new(
1015            "test",
1016            PathType::Bare,
1017            remote_store.clone(),
1018            env.get_puffin_manager(),
1019            env.get_intermediate_manager(),
1020        );
1021        let file_id = RegionFileId::new(RegionId::new(1024, 1), FileId::random());
1022        // Two full chunks and a partial tail distinguish the configured size from the default.
1023        let encoded = Bytes::from(
1024            (0..2 * chunk_size + 17)
1025                .map(|i| (i % 251) as u8)
1026                .collect::<Vec<_>>(),
1027        );
1028        access_layer
1029            .put_sst(
1030                &encoded,
1031                file_id.region_id(),
1032                &mut SstInfo {
1033                    file_id: file_id.file_id(),
1034                    ..Default::default()
1035                },
1036                &cache_manager,
1037                ReadableSize(chunk_size as u64),
1038                None,
1039                &mut Metrics::new(WriteType::Flush),
1040            )
1041            .await
1042            .unwrap();
1043
1044        let remote_path = location::sst_file_path("test", file_id, PathType::Bare);
1045        remote_chunks.assert_chunks(&remote_path, chunk_size, encoded.len());
1046        assert_eq!(
1047            remote_store.read(&remote_path).await.unwrap().to_bytes(),
1048            encoded
1049        );
1050        if let Some(write_cache) = write_cache {
1051            let key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
1052            let cache_path = write_cache.file_cache().cache_file_path(key);
1053            local_chunks.assert_chunks(&cache_path, chunk_size, encoded.len());
1054            assert_eq!(
1055                local_store.read(&cache_path).await.unwrap().to_bytes(),
1056                encoded
1057            );
1058        }
1059    }
1060
1061    #[rstest::rstest]
1062    #[case::flush(OperationType::Flush, false)]
1063    #[case::local_compaction(OperationType::Compact, false)]
1064    #[case::input_only_compaction(OperationType::Compact, true)]
1065    #[tokio::test]
1066    async fn test_written_sst_metadata_cache_policy(
1067        #[case] op_type: OperationType,
1068        #[case] input_only: bool,
1069    ) {
1070        use crate::cache::CacheStrategy;
1071        use crate::sst::file::FileMeta;
1072        use crate::sst::file_purger::NoopFilePurger;
1073        use crate::sst::parquet::reader::MetadataCacheMetrics;
1074        use crate::test_util::sst_util::{
1075            new_flat_source_from_record_batches, new_record_batch_by_range, sst_region_metadata,
1076        };
1077
1078        let mut env = TestEnv::new().await;
1079        let store = env.init_object_store_manager();
1080        let access_layer = AccessLayer::new(
1081            "test",
1082            PathType::Bare,
1083            store,
1084            env.get_puffin_manager(),
1085            env.get_intermediate_manager(),
1086        );
1087        let builder = CacheManager::builder().sst_meta_cache_size(1024 * 1024);
1088        let cache = Arc::new(if input_only {
1089            builder.disable_sst_meta_cache_on_write().build()
1090        } else {
1091            builder.build()
1092        });
1093        let metadata = Arc::new(sst_region_metadata());
1094        let region_id = metadata.region_id;
1095        let infos =
1096            access_layer
1097                .write_sst(
1098                    SstWriteRequest {
1099                        index_build_inputs: None,
1100                        op_type,
1101                        metadata,
1102                        source: new_flat_source_from_record_batches(vec![
1103                            new_record_batch_by_range(&["a", "b"], 0, 16),
1104                        ]),
1105                        cache_manager: cache.clone(),
1106                        max_sequence: None,
1107                        sst_write_format: FormatType::Flat,
1108                        preserve_row_sequence: false,
1109                        index_options: Default::default(),
1110                        index_config: Default::default(),
1111                        inverted_index_config: Default::default(),
1112                        fulltext_index_config: Default::default(),
1113                        bloom_filter_index_config: Default::default(),
1114                    },
1115                    &WriteOptions::default(),
1116                    &mut Metrics::new(WriteType::Compaction),
1117                )
1118                .await
1119                .unwrap();
1120        assert_eq!(1, infos.len());
1121        // A prewarming task owns a cache reference until both tiers are populated.
1122        // Drain it before checking absence so the negative assertion cannot race it.
1123        tokio::time::timeout(Duration::from_secs(10), async {
1124            while Arc::strong_count(&cache) > 1 {
1125                tokio::task::yield_now().await;
1126            }
1127        })
1128        .await
1129        .unwrap();
1130        let info = &infos[0];
1131        let file_id = RegionFileId::new(region_id, info.file_id);
1132        let cached = cache
1133            .get_sst_meta_data(
1134                file_id,
1135                &mut MetadataCacheMetrics::default(),
1136                PageIndexPolicy::Skip,
1137                &common_runtime::compact_runtime(),
1138            )
1139            .await;
1140        assert_eq!(!input_only, cached.is_some());
1141
1142        let file = FileHandle::new(
1143            FileMeta {
1144                region_id,
1145                file_id: info.file_id,
1146                file_size: info.file_size,
1147                ..Default::default()
1148            },
1149            Arc::new(NoopFilePurger),
1150        );
1151        let path = file.file_path(access_layer.table_dir(), access_layer.path_type());
1152        let reader = access_layer
1153            .read_sst(file)
1154            .cache(CacheStrategy::Compaction(cache));
1155        let mut cold = MetadataCacheMetrics::default();
1156        let (first, _) = reader
1157            .read_parquet_metadata(&path, info.file_size, &mut cold, PageIndexPolicy::Skip)
1158            .await
1159            .unwrap();
1160        assert_eq!(input_only, cold.num_reads > 0);
1161        let mut warm = MetadataCacheMetrics::default();
1162        let (second, _) = reader
1163            .read_parquet_metadata(&path, info.file_size, &mut warm, PageIndexPolicy::Skip)
1164            .await
1165            .unwrap();
1166        assert_eq!(16, second.parquet_metadata().file_metadata().num_rows());
1167        assert!(Arc::ptr_eq(&first, &second));
1168        assert_eq!(0, warm.num_reads);
1169        assert_eq!(1, warm.mem_cache_hit);
1170    }
1171
1172    #[rstest::rstest]
1173    #[tokio::test]
1174    async fn test_cancelled_write_cleans_rolled_ssts(
1175        #[values(false, true)] enable_write_cache: bool,
1176        #[values(FormatType::Flat, FormatType::PrimaryKey)] format: FormatType,
1177    ) {
1178        use crate::read::FlatSource;
1179        use crate::sst::file::UncommittedSsts;
1180        use crate::test_util::sst_util::{new_record_batch_by_range, sst_region_metadata};
1181        use tokio_util::sync::CancellationToken;
1182
1183        let mut env = TestEnv::new().await;
1184        let store = env.init_object_store_manager();
1185        let local_dir = create_temp_dir("cancelled-sst-cache");
1186        let local_store = new_fs_store(local_dir.path().to_str().unwrap());
1187        let write_cache = if enable_write_cache {
1188            Some(
1189                env.create_write_cache(local_store.clone(), ReadableSize::mb(10))
1190                    .await,
1191            )
1192        } else {
1193            None
1194        };
1195        let cache = Arc::new(CacheManager::builder().write_cache(write_cache).build());
1196        let layer = Arc::new(AccessLayer::new(
1197            "cancelled",
1198            PathType::Bare,
1199            store.clone(),
1200            env.get_puffin_manager(),
1201            env.get_intermediate_manager(),
1202        ));
1203        let metadata = Arc::new(sst_region_metadata());
1204        let uncommitted =
1205            UncommittedSsts::new(metadata.region_id, layer.clone(), Some(cache.clone()));
1206        let cancellation = CancellationToken::new();
1207        let signal = cancellation.clone();
1208        let tracked = uncommitted.clone();
1209        let schema = new_record_batch_by_range(&["a", "b"], 0, 8).schema();
1210        let source = FlatSource::new_stream(
1211            schema,
1212            Box::pin(async_stream::try_stream! {
1213                for i in 0..64 {
1214                    if tracked.num_tracked_files() >= 3 {
1215                        signal.cancel();
1216                    }
1217                    let tag = format!("{i:04}");
1218                    yield new_record_batch_by_range(&[&tag, "b"], 0, 4096);
1219                }
1220            }),
1221        );
1222        let result = layer
1223            .write_sst_with_context(
1224                SstWriteRequest {
1225                    index_build_inputs: None,
1226                    op_type: OperationType::Compact,
1227                    metadata,
1228                    source,
1229                    cache_manager: cache,
1230                    max_sequence: None,
1231                    sst_write_format: format,
1232                    preserve_row_sequence: false,
1233                    index_options: Default::default(),
1234                    index_config: Default::default(),
1235                    inverted_index_config: Default::default(),
1236                    fulltext_index_config: Default::default(),
1237                    bloom_filter_index_config: Default::default(),
1238                },
1239                &WriteOptions {
1240                    max_file_size: Some(1),
1241                    row_group_size: 8,
1242                    ..Default::default()
1243                },
1244                &mut Metrics::new(WriteType::Compaction),
1245                SstWriteContext {
1246                    guard: Some(Arc::new(uncommitted.clone())),
1247                    cancellation: Some(cancellation),
1248                    ..Default::default()
1249                },
1250            )
1251            .await;
1252        assert!(matches!(
1253            result,
1254            Err(crate::error::Error::SstWriteCancelled { .. })
1255        ));
1256        assert!(
1257            uncommitted.num_tracked_files() >= 2,
1258            "must cover files finalized before cancellation"
1259        );
1260        uncommitted.cleanup_for_test().await.unwrap();
1261        for object_store in [&store, &local_store] {
1262            let entries = object_store.list_with("/").recursive(true).await.unwrap();
1263            assert!(
1264                entries.iter().all(|entry| entry.metadata().is_dir()),
1265                "uncommitted files remain: {entries:?}"
1266            );
1267        }
1268    }
1269
1270    #[tokio::test]
1271    async fn test_new_fs_cache_store() {
1272        let root = common_test_util::temp_dir::create_temp_dir("fs-cache-store");
1273        let dirs = [
1274            root.path().join(ATOMIC_WRITE_DIR),
1275            PathBuf::from(join_dir(
1276                root.path().to_str().unwrap(),
1277                OLD_ATOMIC_WRITE_DIR,
1278            )),
1279        ];
1280        for dir in &dirs {
1281            tokio::fs::create_dir_all(dir).await.unwrap();
1282            tokio::fs::write(dir.join("stale"), b"stale").await.unwrap();
1283        }
1284        let store = new_fs_cache_store(root.path().to_str().unwrap())
1285            .await
1286            .unwrap();
1287        for dir in &dirs {
1288            assert!(!dir.join("stale").exists());
1289        }
1290        store.write("index", "contents").await.unwrap();
1291        assert_eq!(
1292            tokio::fs::read(root.path().join("index")).await.unwrap(),
1293            b"contents"
1294        );
1295    }
1296}