1use std::convert::TryFrom;
16use std::sync::Arc;
17
18use common_base::range_read::RangeReader;
19use common_telemetry::warn;
20use greptime_proto::v1::index::{BloomFilterMeta, InvertedIndexMeta, InvertedIndexMetas};
21use index::bitmap::BitmapType;
22use index::bloom_filter::reader::{BloomFilterReader, BloomFilterReaderImpl};
23use index::fulltext_index::Config as FulltextConfig;
24use index::inverted_index::format::reader::{InvertedIndexBlobReader, InvertedIndexReader};
25use index::target::IndexTarget;
26use puffin::blob_metadata::BlobMetadata;
27use puffin::puffin_manager::file_key::PuffinFileKey;
28use puffin::puffin_manager::{PuffinManager, PuffinReader};
29use serde_json::{Map, Value, json};
30use store_api::sst_entry::{
31 PUFFIN_INDEX_TYPE_BLOOM_FILTER, PUFFIN_INDEX_TYPE_FULLTEXT_BLOOM,
32 PUFFIN_INDEX_TYPE_FULLTEXT_TANTIVY, PUFFIN_INDEX_TYPE_INVERTED, PuffinIndexMetaEntry,
33};
34use store_api::storage::{ColumnId, RegionGroup, RegionId, RegionNumber, RegionSeq, TableId};
35
36use crate::cache::index::bloom_filter_index::{
37 BloomFilterIndexCacheRef, CachedBloomFilterIndexBlobReader, Tag,
38};
39use crate::cache::index::inverted_index::{CachedInvertedIndexBlobReader, InvertedIndexCacheRef};
40use crate::sst::file::RegionIndexId;
41use crate::sst::index::bloom_filter::INDEX_BLOB_TYPE as BLOOM_BLOB_TYPE;
42use crate::sst::index::fulltext_index::{
43 FULLTEXT_BLOOM_VERSION, INDEX_BLOB_TYPE_BLOOM as FULLTEXT_BLOOM_BLOB_TYPE,
44 INDEX_BLOB_TYPE_BLOOM_V1 as FULLTEXT_BLOOM_V1_BLOB_TYPE,
45 INDEX_BLOB_TYPE_TANTIVY as FULLTEXT_TANTIVY_BLOB_TYPE,
46};
47use crate::sst::index::inverted_index::INDEX_BLOB_TYPE as INVERTED_BLOB_TYPE;
48use crate::sst::index::puffin_manager::{SstPuffinManager, SstPuffinReader};
49
50const TARGET_TYPE_UNKNOWN: &str = "unknown";
51
52const TARGET_TYPE_COLUMN: &str = "column";
53
54const TARGET_TYPE_JSON_PATH: &str = "json_path";
55
56pub(crate) struct IndexEntryContext<'a> {
57 pub(crate) table_dir: &'a str,
58 pub(crate) index_file_path: &'a str,
59 pub(crate) region_id: RegionId,
60 pub(crate) table_id: TableId,
61 pub(crate) region_number: RegionNumber,
62 pub(crate) region_group: RegionGroup,
63 pub(crate) region_sequence: RegionSeq,
64 pub(crate) file_id: &'a str,
65 pub(crate) index_file_size: Option<u64>,
66 pub(crate) node_id: Option<u64>,
67}
68
69pub(crate) async fn collect_index_entries_from_puffin(
71 manager: SstPuffinManager,
72 region_index_id: RegionIndexId,
73 context: IndexEntryContext<'_>,
74 bloom_filter_cache: Option<BloomFilterIndexCacheRef>,
75 inverted_index_cache: Option<InvertedIndexCacheRef>,
76) -> Vec<PuffinIndexMetaEntry> {
77 let mut entries = Vec::new();
78
79 let file_key = manager.file_key(®ion_index_id);
80 let reader = match manager.reader(®ion_index_id).await {
81 Ok(reader) => reader,
82 Err(err) => {
83 warn!(
84 err;
85 "Failed to open puffin index file, table_dir: {}, file_id: {}",
86 context.table_dir,
87 context.file_id
88 );
89 return entries;
90 }
91 };
92
93 let file_metadata = match reader.metadata().await {
94 Ok(metadata) => metadata,
95 Err(err) => {
96 warn!(
97 err;
98 "Failed to read puffin file metadata, table_dir: {}, file_id: {}",
99 context.table_dir,
100 context.file_id
101 );
102 return entries;
103 }
104 };
105
106 for blob in &file_metadata.blobs {
107 match BlobIndexTypeTargetKey::from_blob_type(&blob.blob_type) {
108 Some(BlobIndexTypeTargetKey::BloomFilter(target_key)) => {
109 let bloom_meta = try_read_bloom_meta(
110 &reader,
111 &file_key,
112 blob.blob_type.as_str(),
113 target_key,
114 bloom_filter_cache.as_ref(),
115 Tag::Skipping,
116 &context,
117 )
118 .await;
119
120 let bloom_value = bloom_meta.as_deref().map(bloom_meta_value);
121 let (target_type, target_json) = decode_target_info(target_key);
122 let meta_json = build_meta_json(bloom_value, None, None);
123 let entry = build_index_entry(
124 &context,
125 PUFFIN_INDEX_TYPE_BLOOM_FILTER,
126 target_type,
127 target_key.to_string(),
128 target_json,
129 blob.length as u64,
130 meta_json,
131 );
132 entries.push(entry);
133 }
134 Some(BlobIndexTypeTargetKey::FulltextBloom(target_key, bloom_version)) => {
135 let bloom_meta = try_read_bloom_meta(
136 &reader,
137 &file_key,
138 blob.blob_type.as_str(),
139 target_key,
140 bloom_filter_cache.as_ref(),
141 Tag::Fulltext,
142 &context,
143 )
144 .await;
145
146 let bloom_value = bloom_meta.as_deref().map(bloom_meta_value);
147 let fulltext_value = Some(fulltext_meta_value(blob, Some(bloom_version)));
148 let (target_type, target_json) = decode_target_info(target_key);
149 let meta_json = build_meta_json(bloom_value, fulltext_value, None);
150 let entry = build_index_entry(
151 &context,
152 PUFFIN_INDEX_TYPE_FULLTEXT_BLOOM,
153 target_type,
154 target_key.to_string(),
155 target_json,
156 blob.length as u64,
157 meta_json,
158 );
159 entries.push(entry);
160 }
161 Some(BlobIndexTypeTargetKey::FulltextTantivy(target_key)) => {
162 let fulltext_value = Some(fulltext_meta_value(blob, None));
163 let (target_type, target_json) = decode_target_info(target_key);
164 let meta_json = build_meta_json(None, fulltext_value, None);
165 let entry = build_index_entry(
166 &context,
167 PUFFIN_INDEX_TYPE_FULLTEXT_TANTIVY,
168 target_type,
169 target_key.to_string(),
170 target_json,
171 blob.length as u64,
172 meta_json,
173 );
174 entries.push(entry);
175 }
176 Some(BlobIndexTypeTargetKey::Inverted) => {
177 let mut inverted_entries = collect_inverted_entries(
178 &reader,
179 &file_key,
180 inverted_index_cache.as_ref(),
181 &context,
182 )
183 .await;
184 entries.append(&mut inverted_entries);
185 }
186 None => {}
187 }
188 }
189
190 entries
191}
192
193async fn collect_inverted_entries(
194 reader: &SstPuffinReader,
195 file_key: &PuffinFileKey<RegionIndexId>,
196 cache: Option<&InvertedIndexCacheRef>,
197 context: &IndexEntryContext<'_>,
198) -> Vec<PuffinIndexMetaEntry> {
199 let guard = match reader.blob(INVERTED_BLOB_TYPE).await {
201 Ok(guard) => guard,
202 Err(err) => {
203 warn!(
204 err;
205 "Failed to open inverted index blob, table_dir: {}, file_id: {}",
206 context.table_dir,
207 context.file_id
208 );
209 return Vec::new();
210 }
211 };
212
213 let blob_reader = match guard.reader().await {
214 Ok(reader) => reader,
215 Err(err) => {
216 warn!(
217 err;
218 "Failed to build inverted index blob reader, table_dir: {}, file_id: {}",
219 context.table_dir,
220 context.file_id
221 );
222 return Vec::new();
223 }
224 };
225
226 let blob_size = blob_reader
227 .metadata()
228 .await
229 .ok()
230 .map(|meta| meta.content_length);
231 let metas = if let (Some(cache), Some(blob_size)) = (cache, blob_size) {
232 let reader = CachedInvertedIndexBlobReader::new(
233 file_key.clone(),
234 blob_size,
235 InvertedIndexBlobReader::new(blob_reader),
236 cache.clone(),
237 );
238 match reader.metadata(None).await {
239 Ok(metas) => metas,
240 Err(err) => {
241 warn!(
242 err;
243 "Failed to read inverted index metadata, table_dir: {}, file_id: {}",
244 context.table_dir,
245 context.file_id
246 );
247 return Vec::new();
248 }
249 }
250 } else {
251 let reader = InvertedIndexBlobReader::new(blob_reader);
252 match reader.metadata(None).await {
253 Ok(metas) => metas,
254 Err(err) => {
255 warn!(
256 err;
257 "Failed to read inverted index metadata, table_dir: {}, file_id: {}",
258 context.table_dir,
259 context.file_id
260 );
261 return Vec::new();
262 }
263 }
264 };
265
266 build_inverted_entries(context, metas.as_ref())
267}
268
269fn build_inverted_entries(
270 context: &IndexEntryContext<'_>,
271 metas: &InvertedIndexMetas,
272) -> Vec<PuffinIndexMetaEntry> {
273 let mut entries = Vec::new();
274 for (name, meta) in &metas.metas {
275 let (target_type, target_json) = decode_target_info(name);
276 let inverted_value = inverted_meta_value(meta, metas);
277 let meta_json = build_meta_json(None, None, Some(inverted_value));
278 let entry = build_index_entry(
279 context,
280 PUFFIN_INDEX_TYPE_INVERTED,
281 target_type,
282 name.clone(),
283 target_json,
284 meta.inverted_index_size,
285 meta_json,
286 );
287 entries.push(entry);
288 }
289 entries
290}
291
292async fn try_read_bloom_meta(
293 reader: &SstPuffinReader,
294 file_key: &PuffinFileKey<RegionIndexId>,
295 blob_type: &str,
296 target_key: &str,
297 cache: Option<&BloomFilterIndexCacheRef>,
298 tag: Tag,
299 context: &IndexEntryContext<'_>,
300) -> Option<Arc<BloomFilterMeta>> {
301 let column_id = decode_column_id(target_key);
302
303 match reader.blob(blob_type).await {
305 Ok(guard) => match guard.reader().await {
306 Ok(blob_reader) => {
307 let blob_size = blob_reader
308 .metadata()
309 .await
310 .ok()
311 .map(|meta| meta.content_length);
312 let bloom_reader = BloomFilterReaderImpl::new(blob_reader);
313 let result = match (cache, column_id, blob_size) {
314 (Some(cache), Some(column_id), Some(blob_size)) => {
315 CachedBloomFilterIndexBlobReader::new(
316 file_key.clone(),
317 IndexTarget::ColumnId(column_id),
318 tag,
319 blob_size,
320 bloom_reader,
321 cache.clone(),
322 )
323 .metadata(None)
324 .await
325 }
326 _ => bloom_reader.metadata(None).await,
327 };
328
329 match result {
330 Ok(meta) => Some(meta),
331 Err(err) => {
332 warn!(
333 err;
334 "Failed to read index metadata, table_dir: {}, file_id: {}, blob: {}",
335 context.table_dir,
336 context.file_id,
337 blob_type
338 );
339 None
340 }
341 }
342 }
343 Err(err) => {
344 warn!(
345 err;
346 "Failed to open index blob reader, table_dir: {}, file_id: {}, blob: {}",
347 context.table_dir,
348 context.file_id,
349 blob_type
350 );
351 None
352 }
353 },
354 Err(err) => {
355 warn!(
356 err;
357 "Failed to open index blob, table_dir: {}, file_id: {}, blob: {}",
358 context.table_dir,
359 context.file_id,
360 blob_type
361 );
362 None
363 }
364 }
365}
366
367fn decode_target_info(target_key: &str) -> (String, String) {
368 match IndexTarget::decode(target_key) {
369 Ok(IndexTarget::ColumnId(id)) => (
370 TARGET_TYPE_COLUMN.to_string(),
371 json!({ "column": id }).to_string(),
372 ),
373 Ok(IndexTarget::JsonPath(target)) => (
374 TARGET_TYPE_JSON_PATH.to_string(),
375 json!({ "json_path": { "column": target.column_id(), "path": target.path() } })
376 .to_string(),
377 ),
378 _ => (
379 TARGET_TYPE_UNKNOWN.to_string(),
380 json!({ "error": "failed_to_decode" }).to_string(),
381 ),
382 }
383}
384
385fn decode_column_id(target_key: &str) -> Option<ColumnId> {
386 match IndexTarget::decode(target_key) {
387 Ok(IndexTarget::ColumnId(id)) => Some(id),
388 _ => None,
389 }
390}
391
392fn bloom_meta_value(meta: &BloomFilterMeta) -> Value {
393 json!({
394 "rows_per_segment": meta.rows_per_segment,
395 "segment_count": meta.segment_count,
396 "row_count": meta.row_count,
397 "bloom_filter_size": meta.bloom_filter_size,
398 })
399}
400
401fn fulltext_meta_value(blob: &BlobMetadata, bloom_version: Option<u8>) -> Value {
402 let config = FulltextConfig::from_blob_metadata(blob).unwrap_or_default();
403 let mut value = json!({
404 "analyzer": config.analyzer.to_str(),
405 "case_sensitive": config.case_sensitive,
406 });
407 if let Some(version) = bloom_version {
408 value["bloom_version"] = json!(version);
409 }
410 value
411}
412
413fn inverted_meta_value(meta: &InvertedIndexMeta, metas: &InvertedIndexMetas) -> Value {
414 let bitmap_type = BitmapType::try_from(meta.bitmap_type)
415 .map(|bt| format!("{:?}", bt))
416 .unwrap_or_else(|_| meta.bitmap_type.to_string());
417 json!({
418 "bitmap_type": bitmap_type,
419 "base_offset": meta.base_offset,
420 "inverted_index_size": meta.inverted_index_size,
421 "relative_fst_offset": meta.relative_fst_offset,
422 "fst_size": meta.fst_size,
423 "relative_null_bitmap_offset": meta.relative_null_bitmap_offset,
424 "null_bitmap_size": meta.null_bitmap_size,
425 "segment_row_count": metas.segment_row_count,
426 "total_row_count": metas.total_row_count,
427 })
428}
429
430fn build_meta_json(
431 bloom: Option<Value>,
432 fulltext: Option<Value>,
433 inverted: Option<Value>,
434) -> Option<String> {
435 let mut map = Map::new();
436 if let Some(value) = bloom {
437 map.insert("bloom".to_string(), value);
438 }
439 if let Some(value) = fulltext {
440 map.insert("fulltext".to_string(), value);
441 }
442 if let Some(value) = inverted {
443 map.insert("inverted".to_string(), value);
444 }
445 if map.is_empty() {
446 None
447 } else {
448 Some(Value::Object(map).to_string())
449 }
450}
451
452enum BlobIndexTypeTargetKey<'a> {
453 BloomFilter(&'a str),
454 FulltextBloom(&'a str, u8),
456 FulltextTantivy(&'a str),
457 Inverted,
458}
459
460impl<'a> BlobIndexTypeTargetKey<'a> {
461 fn from_blob_type(blob_type: &'a str) -> Option<Self> {
462 if let Some(target_key) = Self::target_key_from_blob(blob_type, BLOOM_BLOB_TYPE) {
463 Some(BlobIndexTypeTargetKey::BloomFilter(target_key))
464 } else if let Some(target_key) =
465 Self::target_key_from_blob(blob_type, FULLTEXT_BLOOM_BLOB_TYPE)
467 {
468 Some(BlobIndexTypeTargetKey::FulltextBloom(
469 target_key,
470 FULLTEXT_BLOOM_VERSION,
471 ))
472 } else if let Some(target_key) =
473 Self::target_key_from_blob(blob_type, FULLTEXT_BLOOM_V1_BLOB_TYPE)
474 {
475 Some(BlobIndexTypeTargetKey::FulltextBloom(target_key, 1))
476 } else if let Some(target_key) =
477 Self::target_key_from_blob(blob_type, FULLTEXT_TANTIVY_BLOB_TYPE)
478 {
479 Some(BlobIndexTypeTargetKey::FulltextTantivy(target_key))
480 } else if blob_type == INVERTED_BLOB_TYPE {
481 Some(BlobIndexTypeTargetKey::Inverted)
482 } else {
483 None
484 }
485 }
486
487 fn target_key_from_blob(blob_type: &'a str, prefix: &str) -> Option<&'a str> {
488 blob_type
490 .strip_prefix(prefix)
491 .and_then(|suffix| suffix.strip_prefix('-'))
492 }
493}
494
495fn build_index_entry(
496 context: &IndexEntryContext<'_>,
497 index_type: &str,
498 target_type: String,
499 target_key: String,
500 target_json: String,
501 blob_size: u64,
502 meta_json: Option<String>,
503) -> PuffinIndexMetaEntry {
504 PuffinIndexMetaEntry {
505 table_dir: context.table_dir.to_string(),
506 index_file_path: context.index_file_path.to_string(),
507 region_id: context.region_id,
508 table_id: context.table_id,
509 region_number: context.region_number,
510 region_group: context.region_group,
511 region_sequence: context.region_sequence,
512 file_id: context.file_id.to_string(),
513 index_file_size: context.index_file_size,
514 index_type: index_type.to_string(),
515 target_type,
516 target_key,
517 target_json,
518 blob_size,
519 meta_json,
520 node_id: context.node_id,
521 }
522}