1use std::collections::{BTreeMap, BTreeSet};
16use std::sync::Arc;
17
18use ahash::HashMap;
19use api::helper::ColumnDataTypeWrapper;
20use api::v1::helper::tag_column_schema;
21use api::v1::region::InsertRequest as RegionInsertRequest;
22use api::v1::value::ValueData;
23use api::v1::{ColumnDataType, ColumnOptions, ColumnSchema, Row, Rows, SemanticType, Value};
24use arrow_schema::extension::{
25 EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY, ExtensionType,
26};
27use common_catalog::consts::METRICS_EXEMPLARS_TABLE;
28use common_error::ext::BoxedError;
29use common_query::prelude::{
30 EXEMPLAR_METRIC_COLUMN, greptime_exemplar_labels, greptime_timestamp, greptime_value,
31};
32use common_time::Timestamp;
33use common_time::timestamp::TimeUnit;
34use datatypes::data_type::ConcreteDataType;
35use datatypes::extension::json::{Json2ExtensionType, JsonMetadata};
36use datatypes::json::{self, JsonSettings};
37use datatypes::types::json_type::JsonNativeType;
38use datatypes::value::Value as DataValue;
39use mito_codec::row_converter::TsidGenerator;
40use snafu::{OptionExt, ResultExt, ensure};
41use store_api::metric_engine_consts::{
42 DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
43};
44use store_api::storage::consts::is_internal_column;
45use store_api::storage::{RegionId, TableId};
46use table::metadata::TableInfo;
47
48use crate::error::{ColumnDataTypeSnafu, ExternalSnafu, InvalidInsertRequestSnafu, Result};
49
50#[derive(Debug, Clone, PartialEq)]
53pub struct Exemplar {
54 pub metric: Arc<str>,
55 pub series_labels: Arc<BTreeMap<String, String>>,
56 pub timestamp: i64,
57 pub value: f64,
58 pub labels: BTreeMap<String, String>,
59}
60
61impl Exemplar {
62 pub fn tsid(&self) -> u64 {
64 TsidGenerator::from_sorted_tags(
65 self.series_labels
66 .iter()
67 .map(|(k, v)| (k.as_str(), v.as_str())),
68 )
69 }
70}
71
72#[derive(Debug, Clone, PartialEq)]
74pub struct ExemplarBatch {
75 exemplars: Vec<Exemplar>,
76 sources: BTreeSet<String>,
77 distinct_tags: BTreeSet<String>,
78}
79
80impl ExemplarBatch {
81 pub fn try_new(exemplars: Vec<Exemplar>) -> Result<Self> {
83 let mut sources = BTreeSet::new();
84 let mut distinct_tags = BTreeSet::new();
85 let mut last_series: Option<&BTreeMap<String, String>> = None;
86
87 for exemplar in &exemplars {
88 ensure!(
89 !exemplar.metric.is_empty() && exemplar.metric.as_ref() != METRICS_EXEMPLARS_TABLE,
90 InvalidInsertRequestSnafu {
91 reason: "invalid or reserved exemplar source metric name",
92 }
93 );
94 if !sources.contains(exemplar.metric.as_ref()) {
95 sources.insert(exemplar.metric.to_string());
96 }
97
98 let series_ptr: &BTreeMap<String, String> = &exemplar.series_labels;
99 if !last_series.is_some_and(|prev| std::ptr::eq(prev, series_ptr)) {
100 for name in series_ptr.keys() {
101 ensure!(
102 !is_reserved_exemplar_tag(name),
103 InvalidInsertRequestSnafu {
104 reason: format!(
105 "inherited exemplar label collides with reserved column: {name}"
106 ),
107 }
108 );
109 if !distinct_tags.contains(name) {
110 distinct_tags.insert(name.clone());
111 }
112 }
113 last_series = Some(series_ptr);
114 }
115
116 for name in exemplar.labels.keys() {
117 ensure!(
118 name != json::JSON2_REMAINDER_FIELD_NAME,
119 InvalidInsertRequestSnafu {
120 reason: "exemplar label name is reserved by JSON2",
121 }
122 );
123 }
124 }
125
126 Ok(Self {
127 exemplars,
128 sources,
129 distinct_tags,
130 })
131 }
132
133 pub fn len(&self) -> usize {
134 self.exemplars.len()
135 }
136
137 pub fn is_empty(&self) -> bool {
138 self.exemplars.is_empty()
139 }
140
141 pub fn exemplars(&self) -> &[Exemplar] {
142 &self.exemplars
143 }
144
145 pub fn sources(&self) -> &BTreeSet<String> {
146 &self.sources
147 }
148
149 pub(crate) fn distinct_tags(&self) -> &BTreeSet<String> {
150 &self.distinct_tags
151 }
152
153 pub(crate) fn request_schema(&self) -> Result<Vec<ColumnSchema>> {
155 let mut schema = Vec::with_capacity(self.distinct_tags.len() + 6);
156 schema.push(tag_column_schema(
157 DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
158 ColumnDataType::Uint32,
159 ));
160 schema.push(tag_column_schema(
161 DATA_SCHEMA_TSID_COLUMN_NAME,
162 ColumnDataType::Uint64,
163 ));
164 schema.push(tag_column_schema(
165 EXEMPLAR_METRIC_COLUMN,
166 ColumnDataType::String,
167 ));
168 for tag in &self.distinct_tags {
169 schema.push(tag_column_schema(tag, ColumnDataType::String));
170 }
171 schema.push(ColumnSchema {
172 column_name: greptime_value().to_string(),
173 datatype: ColumnDataType::Float64 as i32,
174 semantic_type: SemanticType::Field as i32,
175 ..Default::default()
176 });
177 schema.push(ColumnSchema {
178 column_name: greptime_timestamp().to_string(),
179 datatype: ColumnDataType::TimestampNanosecond as i32,
180 semantic_type: SemanticType::Timestamp as i32,
181 ..Default::default()
182 });
183 schema.push(build_json2_column_schema(greptime_exemplar_labels())?);
184 Ok(schema)
185 }
186
187 pub(crate) fn validate_destination_tags(
188 &self,
189 table_name: &str,
190 has_tag: impl Fn(&str) -> bool,
191 ) -> Result<()> {
192 for tag in &self.distinct_tags {
193 ensure!(
194 has_tag(tag),
195 InvalidInsertRequestSnafu {
196 reason: format!("exemplar destination {table_name} is missing tag {tag}"),
197 }
198 );
199 }
200 Ok(())
201 }
202
203 pub(crate) fn validate_for_destination(
205 &self,
206 resolved_table_ids: &HashMap<String, TableId>,
207 destination: &TableInfo,
208 ) -> Result<()> {
209 let target_unit = destination
210 .meta
211 .schema
212 .timestamp_column()
213 .and_then(|c| c.data_type.as_timestamp())
214 .map(|ts| ts.unit())
215 .unwrap_or(TimeUnit::Nanosecond);
216 for exemplar in &self.exemplars {
217 resolved_table_ids
218 .get(exemplar.metric.as_ref())
219 .copied()
220 .with_context(|| InvalidInsertRequestSnafu {
221 reason: format!(
222 "exemplar source {} table ID was not resolved",
223 exemplar.metric
224 ),
225 })?;
226 Timestamp::new_nanosecond(exemplar.timestamp)
227 .convert_to(target_unit)
228 .with_context(|| InvalidInsertRequestSnafu {
229 reason: format!(
230 "exemplar timestamp {} overflows when converting to unit {target_unit:?}",
231 exemplar.timestamp
232 ),
233 })?;
234 }
235 Ok(())
236 }
237
238 pub(crate) fn to_unpadded_region_requests(
241 &self,
242 resolved_table_ids: &HashMap<String, TableId>,
243 destination: &TableInfo,
244 ) -> Result<Vec<RegionInsertRequest>> {
245 if self.exemplars.is_empty() {
246 return Ok(Vec::new());
247 }
248 let target_unit = destination
249 .meta
250 .schema
251 .timestamp_column()
252 .and_then(|c| c.data_type.as_timestamp())
253 .map(|ts| ts.unit())
254 .unwrap_or(TimeUnit::Nanosecond);
255 let ts_datatype = api::helper::timestamp_datatype(target_unit);
256 let region_id = RegionId::new(destination.table_id(), 0).as_u64();
257
258 let mut groups: BTreeMap<Vec<&str>, Vec<&Exemplar>> = BTreeMap::new();
259 for exemplar in &self.exemplars {
260 let key: Vec<&str> = exemplar.series_labels.keys().map(String::as_str).collect();
261 groups.entry(key).or_default().push(exemplar);
262 }
263
264 let labels_column = build_json2_column_schema(greptime_exemplar_labels())?;
265 let mut requests = Vec::with_capacity(groups.len());
266 for (tag_names, group) in groups {
267 let mut schema = Vec::with_capacity(tag_names.len() + 6);
268 schema.push(tag_column_schema(
269 DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
270 ColumnDataType::Uint32,
271 ));
272 schema.push(tag_column_schema(
273 DATA_SCHEMA_TSID_COLUMN_NAME,
274 ColumnDataType::Uint64,
275 ));
276 schema.push(tag_column_schema(
277 EXEMPLAR_METRIC_COLUMN,
278 ColumnDataType::String,
279 ));
280 for tag in &tag_names {
281 schema.push(tag_column_schema(tag, ColumnDataType::String));
282 }
283 schema.push(ColumnSchema {
284 column_name: greptime_value().to_string(),
285 datatype: ColumnDataType::Float64 as i32,
286 semantic_type: SemanticType::Field as i32,
287 ..Default::default()
288 });
289 schema.push(ColumnSchema {
290 column_name: greptime_timestamp().to_string(),
291 datatype: ts_datatype as i32,
292 semantic_type: SemanticType::Timestamp as i32,
293 ..Default::default()
294 });
295 schema.push(labels_column.clone());
296
297 let mut rows = Vec::with_capacity(group.len());
298 for exemplar in group {
299 let table_id = resolved_table_ids
300 .get(exemplar.metric.as_ref())
301 .copied()
302 .with_context(|| InvalidInsertRequestSnafu {
303 reason: format!(
304 "exemplar source {} table ID was not resolved",
305 exemplar.metric
306 ),
307 })?;
308 let tsid = exemplar.tsid();
309 let timestamp = Timestamp::new_nanosecond(exemplar.timestamp)
310 .convert_to(target_unit)
311 .with_context(|| InvalidInsertRequestSnafu {
312 reason: format!(
313 "exemplar timestamp {} overflows when converting to unit {target_unit:?}",
314 exemplar.timestamp
315 ),
316 })?;
317
318 let mut values = Vec::with_capacity(schema.len());
319 values.push(ValueData::U32Value(table_id).into());
320 values.push(ValueData::U64Value(tsid).into());
321 values.push(ValueData::StringValue(exemplar.metric.to_string()).into());
322 for tag_value in exemplar.series_labels.values() {
323 values.push(ValueData::StringValue(tag_value.clone()).into());
324 }
325 values.push(ValueData::F64Value(exemplar.value).into());
326 values.push(api::helper::to_grpc_value(DataValue::Timestamp(timestamp)));
327 values.push(Value {
328 value_data: Some(encode_json2_value(&exemplar.labels)?),
329 });
330 rows.push(Row { values });
331 }
332
333 requests.push(RegionInsertRequest {
334 region_id,
335 rows: Some(Rows { schema, rows }),
336 ..Default::default()
337 });
338 }
339 Ok(requests)
340 }
341}
342
343pub fn is_reserved_exemplar_tag(name: &str) -> bool {
345 [
346 greptime_timestamp(),
347 greptime_value(),
348 EXEMPLAR_METRIC_COLUMN,
349 greptime_exemplar_labels(),
350 DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
351 DATA_SCHEMA_TSID_COLUMN_NAME,
352 ]
353 .contains(&name)
354 || is_internal_column(name)
355}
356
357fn build_json2_column_schema(name: &str) -> Result<ColumnSchema> {
358 let extension = Json2ExtensionType::new(Arc::new(JsonMetadata::new(JsonSettings::new_v2())));
359 let mut options = ColumnOptions::default();
360 options.options.insert(
361 EXTENSION_TYPE_NAME_KEY.to_string(),
362 Json2ExtensionType::NAME.to_string(),
363 );
364 if let Some(metadata) = extension.serialize_metadata() {
365 options
366 .options
367 .insert(EXTENSION_TYPE_METADATA_KEY.to_string(), metadata);
368 }
369
370 Ok(ColumnSchema {
371 column_name: name.to_string(),
372 datatype: ColumnDataType::Json as i32,
373 semantic_type: SemanticType::Field as i32,
374 datatype_extension: ColumnDataTypeWrapper::try_from(ConcreteDataType::json2(
375 JsonNativeType::Null,
376 ))
377 .context(ColumnDataTypeSnafu)?
378 .into_parts()
379 .1,
380 options: Some(options),
381 })
382}
383
384pub(crate) fn encode_json2_data_value(labels: &BTreeMap<String, String>) -> Result<DataValue> {
385 let map: serde_json::Map<String, serde_json::Value> = labels
386 .iter()
387 .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
388 .collect();
389 JsonSettings::new_v2()
390 .encode(serde_json::Value::Object(map))
391 .map_err(BoxedError::new)
392 .context(ExternalSnafu)
393}
394
395fn encode_json2_value(labels: &BTreeMap<String, String>) -> Result<ValueData> {
396 let value = encode_json2_data_value(labels)?;
397 api::helper::to_grpc_value(value)
398 .value_data
399 .context(InvalidInsertRequestSnafu {
400 reason: "JSON2 encoding returned an empty value",
401 })
402}