1use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use common_telemetry::debug;
19use datatypes::data_type::ConcreteDataType;
20use datatypes::series::frame::{LabelDecodeEncoding, LabelDecodeSpec};
21use datatypes::series::{Label, SeriesLabels};
22use datatypes::value::Value;
23use snafu::ResultExt;
24use store_api::codec::PrimaryKeyEncoding;
25use store_api::metric_engine_consts::is_metric_engine_internal_column;
26use store_api::storage::{
27 ColumnId,
28 consts::{ReservedColumnId, is_internal_column},
29};
30
31use crate::error::{
32 InvalidDensePrimaryKeySnafu, InvalidLabelDecodeDescriptionSnafu, InvalidSparsePrimaryKeySnafu,
33 Result,
34};
35use crate::row_converter::SortField;
36use crate::row_converter::dense::DensePrimaryKeyCodec;
37use crate::row_converter::sparse::{SparseOffsetsCache, SparsePrimaryKeyView};
38
39enum Layout {
40 Sparse(SparseOffsetsCache),
41 Dense {
42 codec: DensePrimaryKeyCodec,
43 offsets: Vec<usize>,
44 },
45}
46
47fn invalid_binding_error(encoding: PrimaryKeyEncoding, reason: String) -> crate::error::Error {
48 match encoding {
49 PrimaryKeyEncoding::Dense => InvalidDensePrimaryKeySnafu { reason }.build(),
50 PrimaryKeyEncoding::Sparse => InvalidSparsePrimaryKeySnafu { reason }.build(),
51 }
52}
53
54struct BoundLabel {
55 id: ColumnId,
56 name: Arc<str>,
57 position: usize,
58}
59
60struct KeyColumn {
62 id: ColumnId,
63 name: String,
64 data_type: ConcreteDataType,
65}
66
67struct KeyLayout {
75 metric_name: Arc<str>,
76 encoding: PrimaryKeyEncoding,
77 columns: Vec<KeyColumn>,
78 positions: HashMap<ColumnId, usize>,
86}
87
88impl KeyLayout {
89 fn column(&self, id: ColumnId) -> Option<&KeyColumn> {
91 self.position(id).map(|position| &self.columns[position])
92 }
93
94 fn position(&self, id: ColumnId) -> Option<usize> {
96 self.positions.get(&id).copied()
97 }
98}
99
100pub struct PrimaryKeyLabelDecoder {
102 key: KeyLayout,
103 labels: Vec<BoundLabel>,
104 value_scratch: Vec<u8>,
105 layout: Layout,
106}
107
108impl PrimaryKeyLabelDecoder {
109 pub fn from_decode_spec(spec: &LabelDecodeSpec) -> Result<Self> {
122 spec.validate()
123 .context(InvalidLabelDecodeDescriptionSnafu)?;
124 let key = KeyLayout {
125 metric_name: Arc::from(spec.metric_name.as_str()),
126 encoding: match spec.encoding {
127 LabelDecodeEncoding::Dense => PrimaryKeyEncoding::Dense,
128 LabelDecodeEncoding::Sparse => PrimaryKeyEncoding::Sparse,
129 },
130 columns: spec
131 .primary_key
132 .iter()
133 .map(|column| KeyColumn {
134 id: column.column_id,
135 name: column.name.clone(),
136 data_type: column.physical_type.clone(),
137 })
138 .collect(),
139 positions: HashMap::new(),
141 };
142 Self::bind(
143 key,
144 spec.logical_tags
145 .iter()
146 .map(|tag| (tag.column_id, tag.name.as_str())),
147 )
148 }
149
150 fn bind<'a, I>(mut key: KeyLayout, tags: I) -> Result<Self>
152 where
153 I: IntoIterator<Item = (ColumnId, &'a str)>,
154 {
155 key.positions = key
158 .columns
159 .iter()
160 .enumerate()
161 .map(|(position, column)| (column.id, position))
162 .collect();
163 let mut labels = Vec::new();
164 let mut names = HashSet::new();
165 let mut ids = HashSet::new();
166 let mut logical_tag_count = 0;
167 for (column_id, name) in tags {
168 logical_tag_count += 1;
169 if !names.insert(name)
170 || !ids.insert(column_id)
171 || name == "__name__"
172 || is_internal_column(name)
173 || is_metric_engine_internal_column(name)
174 || ReservedColumnId::is_reserved(column_id)
175 || !key
176 .column(column_id)
177 .is_some_and(|column| column.name == name)
178 {
179 return Err(invalid_binding_error(
180 key.encoding,
181 format!("invalid logical tag binding {name}"),
182 ));
183 }
184 let position = key.position(column_id).ok_or_else(|| {
185 invalid_binding_error(
186 key.encoding,
187 format!("logical tag {name} is not a primary-key column"),
188 )
189 })?;
190 labels.push(BoundLabel {
191 id: column_id,
192 name: Arc::from(name),
193 position,
194 });
195 }
196 labels.sort_unstable_by(|a, b| a.name.cmp(&b.name));
197 let layout = match key.encoding {
198 PrimaryKeyEncoding::Sparse => Layout::Sparse(SparseOffsetsCache::new()),
199 PrimaryKeyEncoding::Dense => Layout::Dense {
200 codec: DensePrimaryKeyCodec::with_fields(
201 key.columns
202 .iter()
203 .map(|column| (column.id, SortField::new(column.data_type.clone())))
204 .collect(),
205 ),
206 offsets: Vec::new(),
207 },
208 };
209 let encoding = match key.encoding {
210 PrimaryKeyEncoding::Sparse => "sparse",
211 PrimaryKeyEncoding::Dense => "dense",
212 };
213 debug!(
214 encoding,
215 logical_tag_count,
216 selected_tag_count = labels.len(),
217 "Constructed primary key label decoder"
218 );
219 Ok(Self {
220 key,
221 labels,
222 value_scratch: Vec::new(),
223 layout,
224 })
225 }
226
227 pub fn decode(&mut self, read_key: &[u8]) -> Result<SeriesLabels> {
232 let mut values = Vec::with_capacity(self.labels.len());
233 let Self {
234 layout,
235 key,
236 labels,
237 value_scratch,
238 ..
239 } = self;
240 match layout {
241 Layout::Sparse(cache) => {
242 let mut view = SparsePrimaryKeyView::new(read_key, cache)?;
243 view.visit_label_ids(|id| {
244 if key.column(id).is_none() {
245 return InvalidSparsePrimaryKeySnafu {
246 reason: format!("unrecognized sparse tag id {id}"),
247 }
248 .fail();
249 }
250 Ok(())
251 })?;
252 for label in labels.iter() {
253 if let Some(value) = view.label(label.id, value_scratch)? {
254 values.push(Label {
255 name: label.name.clone(),
256 value: Arc::from(value),
257 });
258 }
259 }
260 }
261 Layout::Dense { codec, offsets } => {
262 offsets.clear();
263 let mut total = 0;
264 for pos in 0..codec.num_fields() {
265 let encoded = codec.encoded_value_at(read_key, pos, offsets)?;
266 total += encoded.len();
267 }
268 if total != read_key.len() {
269 return InvalidDensePrimaryKeySnafu {
270 reason: "trailing bytes after dense primary key",
271 }
272 .fail();
273 }
274 for label in labels.iter() {
275 let value = codec.decode_value_at(read_key, label.position, offsets)?;
276 if !matches!(value, Value::Null) {
277 values.push(Label {
278 name: label.name.clone(),
279 value: Arc::from(value.to_string()),
280 });
281 }
282 }
283 }
284 }
285 SeriesLabels::try_new(Some(key.metric_name.clone()), values).map_err(|error| {
286 InvalidSparsePrimaryKeySnafu {
287 reason: error.to_string(),
288 }
289 .build()
290 })
291 }
292}
293
294#[cfg(test)]
295mod tests;