servers/prom_remote_write/
row_builder.rs1use std::collections::HashMap;
16
17use api::prom_store::remote::Sample;
18use api::v1::helper::{field_column_schema, time_index_column_schema};
19use api::v1::value::ValueData;
20use api::v1::{ColumnDataType, ColumnSchema, Row, RowInsertRequest, Rows, SemanticType, Value};
21use common_query::prelude::{greptime_timestamp, greptime_value};
22use pipeline::{ContextOpt, ContextReq};
23use prost::DecodeError;
24
25use crate::prom_remote_write::PromValidationMode;
26use crate::prom_remote_write::types::PromLabel;
27use crate::prom_remote_write::validation::validate_label_name;
28use crate::repeated_field::Clear;
29
30#[derive(Debug, Default, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
31pub struct PromCtx {
32 pub schema: Option<String>,
33 pub physical_table: Option<String>,
34}
35
36impl From<PromCtx> for ContextOpt {
37 fn from(prom_ctx: PromCtx) -> Self {
38 let mut opt = ContextOpt::default();
39 if let Some(schema) = prom_ctx.schema {
40 opt.set_schema(schema);
41 }
42 if let Some(physical_table) = prom_ctx.physical_table {
43 opt.set_physical_table(physical_table);
44 }
45 opt
46 }
47}
48
49#[derive(Default, Debug)]
50pub struct TablesBuilder<'a> {
51 pub tables: HashMap<PromCtx, HashMap<String, TableBuilder<'a>>>,
52 pub(crate) raw_data: Vec<u8>,
53 pub(crate) exemplars: crate::exemplar::ExemplarRequests,
54}
55
56impl<'a> Clear for TablesBuilder<'a> {
57 fn clear(&mut self) {
58 self.tables.clear();
59 self.raw_data.clear();
60 self.exemplars.clear();
61 }
62}
63
64impl<'a> TablesBuilder<'a> {
65 pub(crate) fn get_or_create_table_builder(
66 &mut self,
67 prom_ctx: PromCtx,
68 table_name: String,
69 label_num: usize,
70 row_num: usize,
71 ) -> &mut TableBuilder<'a> {
72 self.tables
73 .entry(prom_ctx)
74 .or_default()
75 .entry(table_name)
76 .or_insert_with(|| TableBuilder::with_capacity(label_num + 2, row_num))
77 }
78
79 pub(crate) fn as_insert_requests(&mut self) -> ContextReq {
80 self.tables
81 .drain()
82 .map(|(prom, mut tables)| {
83 let opt = ContextOpt::from(prom);
84 let mut ctx_req = ContextReq::default();
85 let reqs = tables
86 .drain()
87 .map(|(table_name, mut table)| table.as_row_insert_request(table_name));
88 ctx_req.add_rows(opt, reqs);
89
90 ctx_req
91 })
92 .fold(ContextReq::default(), |mut req, reqs| {
93 req.merge(reqs);
94 req
95 })
96 }
97
98 pub(crate) fn set_raw_data(&mut self, buf: Vec<u8>) {
99 self.raw_data = buf;
100 }
101}
102
103#[derive(Debug)]
104pub struct TableBuilder<'a> {
105 schema: Vec<ColumnSchema>,
106 rows: Vec<Row>,
107 col_indexes: HashMap<&'a [u8], usize>,
108}
109
110impl<'a> Default for TableBuilder<'a> {
111 fn default() -> Self {
112 Self::with_capacity(2, 0)
113 }
114}
115
116impl<'a> TableBuilder<'a> {
117 pub(crate) fn with_capacity(cols: usize, rows: usize) -> Self {
118 let mut col_indexes = HashMap::with_capacity_and_hasher(cols, Default::default());
119 col_indexes.insert(greptime_timestamp().as_bytes(), 0);
120 col_indexes.insert(greptime_value().as_bytes(), 1);
121
122 let mut schema = Vec::with_capacity(cols);
123 schema.push(time_index_column_schema(
124 greptime_timestamp(),
125 ColumnDataType::TimestampMillisecond,
126 ));
127 schema.push(field_column_schema(
128 greptime_value(),
129 ColumnDataType::Float64,
130 ));
131
132 Self {
133 schema,
134 rows: Vec::with_capacity(rows),
135 col_indexes,
136 }
137 }
138
139 pub(crate) fn add_labels_and_samples(
140 &mut self,
141 labels: &[PromLabel],
142 samples: &[Sample],
143 prom_validation_mode: PromValidationMode,
144 ) -> Result<(), DecodeError> {
145 let mut row = vec![Value { value_data: None }; self.col_indexes.len()];
146
147 for PromLabel { name, value } in labels {
148 if !validate_label_name(name) {
149 return Err(DecodeError::new(format!(
150 "Invalid label name: `{}`",
151 String::from_utf8_lossy(name)
152 )));
153 }
154 let raw_tag_name = *name;
155 let tag_value = Some(ValueData::StringValue(
156 prom_validation_mode.decode_string(value)?,
157 ));
158 let tag_num = self.col_indexes.len();
159
160 if let Some(e) = self.col_indexes.get_mut(raw_tag_name) {
161 row[*e].value_data = tag_value;
162 continue;
163 }
164
165 let tag_name = unsafe { std::str::from_utf8_unchecked(raw_tag_name) };
166 self.schema.push(ColumnSchema {
167 column_name: tag_name.to_owned(),
168 datatype: ColumnDataType::String as i32,
169 semantic_type: SemanticType::Tag as i32,
170 ..Default::default()
171 });
172 self.col_indexes.insert(raw_tag_name, tag_num);
173
174 row.push(Value {
175 value_data: tag_value,
176 });
177 }
178
179 let Some((last_sample, preceding_samples)) = samples.split_last() else {
180 return Ok(());
181 };
182
183 for sample in preceding_samples {
184 row[0].value_data = Some(ValueData::TimestampMillisecondValue(sample.timestamp));
185 row[1].value_data = Some(ValueData::F64Value(sample.value));
186 self.rows.push(Row {
187 values: row.clone(),
188 });
189 }
190
191 row[0].value_data = Some(ValueData::TimestampMillisecondValue(last_sample.timestamp));
192 row[1].value_data = Some(ValueData::F64Value(last_sample.value));
193 self.rows.push(Row { values: row });
194
195 Ok(())
196 }
197
198 pub fn as_row_insert_request(&mut self, table_name: String) -> RowInsertRequest {
199 let mut rows = std::mem::take(&mut self.rows);
200 let schema = std::mem::take(&mut self.schema);
201 let col_num = schema.len();
202 for row in &mut rows {
203 if row.values.len() < col_num {
204 row.values.resize(col_num, Value { value_data: None });
205 }
206 }
207
208 RowInsertRequest {
209 table_name,
210 rows: Some(Rows { schema, rows }),
211 }
212 }
213
214 pub fn tags(&self) -> impl Iterator<Item = &String> {
215 self.schema
216 .iter()
217 .filter(|v| v.semantic_type == SemanticType::Tag as i32)
218 .map(|c| &c.column_name)
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use api::prom_store::remote::Sample;
225 use prost::DecodeError;
226
227 use super::*;
228
229 fn assert_sample(row: &Row, timestamp: i64, value: f64) {
230 assert_eq!(
231 Some(&ValueData::TimestampMillisecondValue(timestamp)),
232 row.values[0].value_data.as_ref()
233 );
234 assert_eq!(
235 Some(&ValueData::F64Value(value)),
236 row.values[1].value_data.as_ref()
237 );
238 }
239
240 #[test]
241 fn test_add_labels_and_samples() {
242 let mut builder = TableBuilder::default();
243 builder
244 .add_labels_and_samples(
245 &[PromLabel {
246 name: b"tag0",
247 value: b"v0",
248 }],
249 &[],
250 PromValidationMode::Strict,
251 )
252 .unwrap();
253 assert!(builder.rows.is_empty());
254
255 builder
256 .add_labels_and_samples(
257 &[PromLabel {
258 name: b"tag0",
259 value: b"v0",
260 }],
261 &[Sample {
262 value: 1.0,
263 timestamp: 1,
264 }],
265 PromValidationMode::Strict,
266 )
267 .unwrap();
268
269 builder
270 .add_labels_and_samples(
271 &[
272 PromLabel {
273 name: b"tag0",
274 value: b"v1",
275 },
276 PromLabel {
277 name: b"tag1",
278 value: b"v2",
279 },
280 ],
281 &[
282 Sample {
283 value: 2.0,
284 timestamp: 2,
285 },
286 Sample {
287 value: 3.0,
288 timestamp: 3,
289 },
290 ],
291 PromValidationMode::Strict,
292 )
293 .unwrap();
294
295 let request = builder.as_row_insert_request("test".to_string());
296 let rows = request.rows.unwrap().rows;
297 assert_eq!(3, rows.len());
298 assert!(rows.iter().all(|row| row.values.len() == 4));
299
300 assert_sample(&rows[0], 1, 1.0);
301 assert_eq!(
302 Some(&ValueData::StringValue("v0".to_string())),
303 rows[0].values[2].value_data.as_ref()
304 );
305 assert!(rows[0].values[3].value_data.is_none());
306
307 assert_sample(&rows[1], 2, 2.0);
308 assert_sample(&rows[2], 3, 3.0);
309 for row in &rows[1..] {
310 assert_eq!(
311 Some(&ValueData::StringValue("v1".to_string())),
312 row.values[2].value_data.as_ref()
313 );
314 assert_eq!(
315 Some(&ValueData::StringValue("v2".to_string())),
316 row.values[3].value_data.as_ref()
317 );
318 }
319 }
320
321 #[test]
322 fn test_table_builder() {
323 let mut builder = TableBuilder::default();
324 let _ = builder.add_labels_and_samples(
325 &[
326 PromLabel {
327 name: b"tag0",
328 value: b"v0",
329 },
330 PromLabel {
331 name: b"tag1",
332 value: b"v1",
333 },
334 ],
335 &[Sample {
336 value: 0.0,
337 timestamp: 0,
338 }],
339 PromValidationMode::Strict,
340 );
341
342 let _ = builder.add_labels_and_samples(
343 &[
344 PromLabel {
345 name: b"tag0",
346 value: b"v0",
347 },
348 PromLabel {
349 name: b"tag2",
350 value: b"v2",
351 },
352 ],
353 &[Sample {
354 value: 0.1,
355 timestamp: 1,
356 }],
357 PromValidationMode::Strict,
358 );
359
360 let request = builder.as_row_insert_request("test".to_string());
361 let rows = request.rows.unwrap().rows;
362 assert_eq!(2, rows.len());
363
364 let invalid_utf8_bytes = &[0xFF, 0xFF, 0xFF];
365 let res = builder.add_labels_and_samples(
366 &[PromLabel {
367 name: b"tag0",
368 value: invalid_utf8_bytes,
369 }],
370 &[Sample {
371 value: 0.1,
372 timestamp: 1,
373 }],
374 PromValidationMode::Strict,
375 );
376 assert_eq!(res, Err(DecodeError::new("invalid utf-8")));
377 }
378}