Skip to main content

mito2/
compaction.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
15mod buckets;
16pub mod compactor;
17mod json2;
18mod last_non_null;
19pub mod memory_manager;
20#[cfg(feature = "enterprise")]
21pub mod multi_region;
22mod overlap;
23pub mod picker;
24mod reader;
25#[cfg(test)]
26pub(crate) use reader::CompactionSstReaderBuilder;
27pub mod run;
28mod scheduler;
29mod task;
30#[cfg(test)]
31mod test_util;
32mod twcs;
33mod unit;
34mod window;
35
36use std::any::Any;
37use std::collections::HashMap;
38
39use common_meta::key::SchemaMetadataManagerRef;
40use common_telemetry::{debug, error};
41use common_time::TimeToLive;
42use common_time::range::TimestampRange;
43pub(crate) use json2::{
44    Json2RewritePlans, collect_json2_rewrite_plans, rewrite_json2_batch, rewrite_json2_schema,
45};
46pub(crate) use scheduler::{
47    CancelCompactionResult, CompactionCoordinator, CompactionExecution, CompactionPickFinished,
48    CompactionScheduler, CompactionState, CompactionStateRef, CompactionTransition,
49};
50pub use scheduler::{CompactionGuard, CompactionRequest};
51use serde::{Deserialize, Serialize};
52use snafu::ResultExt;
53use store_api::mito_engine_options::{TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, TWCS_TRIGGER_FILE_NUM};
54use store_api::storage::RegionId;
55
56use crate::error::{GetSchemaMetadataSnafu, Result, TimeoutSnafu};
57use crate::sst::file::{FileHandle, FileMeta, Level};
58
59/// Finds compaction options and TTL together with a single metadata fetch to reduce RTT.
60pub(crate) async fn find_dynamic_options(
61    region_id: RegionId,
62    region_options: &crate::region::options::RegionOptions,
63    schema_metadata_manager: &SchemaMetadataManagerRef,
64) -> Result<(crate::region::options::CompactionOptions, TimeToLive)> {
65    let table_id = region_id.table_id();
66    if let (true, Some(ttl)) = (region_options.compaction_override, region_options.ttl) {
67        debug!(
68            "Use region options directly for table {}: compaction={:?}, ttl={:?}",
69            table_id, region_options.compaction, region_options.ttl
70        );
71        return Ok((region_options.compaction.clone(), ttl));
72    }
73
74    let db_options = tokio::time::timeout(
75        crate::config::FETCH_OPTION_TIMEOUT,
76        schema_metadata_manager.get_schema_options_by_table_id(table_id),
77    )
78    .await
79    .context(TimeoutSnafu)?
80    .context(GetSchemaMetadataSnafu)?;
81
82    let ttl = if let Some(ttl) = region_options.ttl {
83        debug!(
84            "Use region TTL directly for table {}: ttl={:?}",
85            table_id, region_options.ttl
86        );
87        ttl
88    } else {
89        db_options
90            .as_ref()
91            .and_then(|options| options.ttl)
92            .unwrap_or_default()
93            .into()
94    };
95
96    let compaction = if !region_options.compaction_override {
97        if let Some(schema_opts) = db_options {
98            let mut map: HashMap<String, String> = schema_opts
99                .extra_options
100                .iter()
101                .filter_map(|(k, v)| {
102                    if k.starts_with("compaction.") {
103                        Some((k.clone(), v.clone()))
104                    } else {
105                        None
106                    }
107                })
108                .collect();
109            // Historical metadata may contain both aliases; prefer the canonical key.
110            if map.contains_key(TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM) {
111                map.remove(TWCS_TRIGGER_FILE_NUM);
112            }
113            if map.is_empty() {
114                region_options.compaction.clone()
115            } else {
116                crate::region::options::RegionOptions::try_from_options(region_id, &map)
117                    .map(|o| o.compaction)
118                    .unwrap_or_else(|e| {
119                        error!(e; "Failed to create RegionOptions from map");
120                        region_options.compaction.clone()
121                    })
122            }
123        } else {
124            debug!(
125                "DB options is None for table {}, use region compaction: compaction={:?}",
126                table_id, region_options.compaction
127            );
128            region_options.compaction.clone()
129        }
130    } else {
131        debug!(
132            "No schema options for table {}, use region compaction: compaction={:?}",
133            table_id, region_options.compaction
134        );
135        region_options.compaction.clone()
136    };
137
138    debug!(
139        "Resolved dynamic options for table {}: compaction={:?}, ttl={:?}",
140        table_id, compaction, ttl
141    );
142    Ok((compaction, ttl))
143}
144
145#[derive(Debug, Clone)]
146pub struct CompactionOutput {
147    /// Compaction output file level.
148    pub output_level: Level,
149    /// Compaction input files.
150    pub inputs: Vec<FileHandle>,
151    /// Whether to remove deletion markers.
152    pub filter_deleted: bool,
153    /// Compaction output time range. Only windowed compaction specifies output time range.
154    pub output_time_range: Option<TimestampRange>,
155}
156
157/// SerializedCompactionOutput is a serialized version of [CompactionOutput] by replacing [FileHandle] with [FileMeta].
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct SerializedCompactionOutput {
160    output_level: Level,
161    inputs: Vec<FileMeta>,
162    filter_deleted: bool,
163    output_time_range: Option<TimestampRange>,
164}
165
166/// Returns the printable reason carried by a caught panic payload.
167pub(crate) fn format_panic_reason(payload: &(dyn Any + Send + 'static)) -> String {
168    if let Some(message) = payload.downcast_ref::<&str>() {
169        message.to_string()
170    } else if let Some(message) = payload.downcast_ref::<String>() {
171        message.clone()
172    } else {
173        "unknown panic".to_string()
174    }
175}
176
177/// A rewrite is balanced when the peers contribute at least the largest input size.
178pub(crate) fn bytes_balanced(largest: u128, total: u128) -> bool {
179    largest <= total - largest
180}