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