Skip to main content

mito2/sst/index/handler/
builtin.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
15//! Dispatches built-in planning and shares column metadata policy.
16
17mod bloom;
18mod fulltext;
19mod inverted;
20
21use std::sync::Arc;
22
23use common_error::ext::BoxedError;
24use index::target::IndexTarget;
25
26use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig};
27use crate::sst::file::FileMeta;
28use crate::sst::index::handler::builtin::bloom::BloomPlan;
29use crate::sst::index::handler::builtin::fulltext::FulltextPlan;
30use crate::sst::index::handler::builtin::inverted::InvertedPlan;
31use crate::sst::index::handler::{IndexKindHandler, PlanContext, PlanEntry, PlannedIndex};
32use crate::sst::index::kind::IndexKind;
33
34/// Configuration for one of the existing file-level built-in creators.
35#[derive(Debug, Clone)]
36pub(crate) enum BuiltinIndexHandler {
37    Inverted(InvertedIndexConfig),
38    Fulltext(FulltextIndexConfig),
39    Bloom(BloomFilterConfig),
40}
41
42impl IndexKindHandler for BuiltinIndexHandler {
43    fn kinds(&self) -> &[IndexKind] {
44        match self {
45            Self::Inverted(_) => &[IndexKind::Inverted],
46            Self::Fulltext(_) => &[IndexKind::Fulltext],
47            Self::Bloom(_) => &[IndexKind::Bloom],
48        }
49    }
50
51    fn validate(&self, _context: &PlanContext<'_>) -> Result<(), BoxedError> {
52        // Built-in options retain their existing schema/build-time validation.
53        // Planning here would make region creation reject inputs it previously accepted.
54        Ok(())
55    }
56
57    fn plan(&self, context: &PlanContext<'_>) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
58        match self {
59            Self::Inverted(config) => InvertedPlan::plan(config, context)
60                .map(|plan| plan.map(|plan| plan as Arc<dyn PlannedIndex>)),
61            Self::Fulltext(config) => FulltextPlan::plan(config, context),
62            Self::Bloom(config) => BloomPlan::plan(config, context),
63        }
64    }
65}
66
67fn target_column_id(target: &IndexTarget) -> store_api::storage::ColumnId {
68    match target {
69        IndexTarget::ColumnId(id) => *id,
70        IndexTarget::JsonPath(path) => path.column_id(),
71    }
72}
73
74fn column_target_id(target: &IndexTarget) -> Option<store_api::storage::ColumnId> {
75    match target {
76        IndexTarget::ColumnId(id) => Some(*id),
77        IndexTarget::JsonPath(_) => None,
78    }
79}
80
81fn normalize_entries(entries: &mut Vec<PlanEntry>) {
82    entries.sort_by_key(|entry| (entry.column_id, entry.format_version));
83    entries.dedup_by(|a, b| {
84        if a.column_id == b.column_id {
85            b.format_version = b.format_version.max(a.format_version);
86            true
87        } else {
88            false
89        }
90    });
91}
92
93fn builtin_is_current(file: &FileMeta, context: &PlanContext<'_>) -> bool {
94    // Preserve the established schema/version policy, including its JSON rebuild scope.
95    file.is_index_consistent_with_region(&context.metadata.column_metadatas, context.index_options)
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::region::options::IndexOptions;
102    use crate::sst::index::IndexBuildType;
103    use crate::test_util::sst_util;
104
105    #[test]
106    fn test_builtin_validation_preserves_build_time_option_errors() {
107        for (handler, key) in [
108            (
109                BuiltinIndexHandler::Fulltext(FulltextIndexConfig::default()),
110                datatypes::schema::FULLTEXT_KEY,
111            ),
112            (
113                BuiltinIndexHandler::Bloom(BloomFilterConfig::default()),
114                datatypes::schema::SKIPPING_INDEX_KEY,
115            ),
116        ] {
117            let mut metadata = sst_util::sst_region_metadata();
118            let column = metadata
119                .column_metadatas
120                .iter_mut()
121                .find(|column| column.semantic_type == api::v1::SemanticType::Field)
122                .unwrap();
123            column.column_schema =
124                column
125                    .column_schema
126                    .clone()
127                    .with_metadata(std::collections::HashMap::from([(
128                        key.to_string(),
129                        "invalid json".to_string(),
130                    )]));
131            let metadata = Arc::new(metadata);
132            let options = IndexOptions::default();
133            let context = PlanContext {
134                metadata: &metadata,
135                index_options: &options,
136                build_type: IndexBuildType::Flush,
137                existing_indexes: &[],
138            };
139            assert!(handler.validate(&context).is_ok());
140            assert!(handler.plan(&context).is_err());
141        }
142    }
143
144    #[test]
145    fn test_builtin_planning_reports_invalid_options() {
146        for (handler, key) in [
147            (
148                BuiltinIndexHandler::Fulltext(FulltextIndexConfig::default()),
149                datatypes::schema::FULLTEXT_KEY,
150            ),
151            (
152                BuiltinIndexHandler::Bloom(BloomFilterConfig::default()),
153                datatypes::schema::SKIPPING_INDEX_KEY,
154            ),
155        ] {
156            let mut metadata = sst_util::sst_region_metadata();
157            let column = metadata
158                .column_metadatas
159                .iter_mut()
160                .find(|column| column.semantic_type == api::v1::SemanticType::Field)
161                .unwrap();
162            column.column_schema =
163                column
164                    .column_schema
165                    .clone()
166                    .with_metadata(std::collections::HashMap::from([(
167                        key.to_string(),
168                        "invalid json".to_string(),
169                    )]));
170            let metadata = Arc::new(metadata);
171            let options = IndexOptions::default();
172            let context = PlanContext {
173                metadata: &metadata,
174                index_options: &options,
175                build_type: IndexBuildType::Flush,
176                existing_indexes: &[],
177            };
178            assert!(handler.plan(&context).is_err());
179        }
180    }
181}