Skip to main content

mito_codec/
labels.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
15use 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
60/// One ordered key column of the minimal decode layout.
61struct KeyColumn {
62    id: ColumnId,
63    name: String,
64    data_type: ConcreteDataType,
65}
66
67/// Minimal primary-key layout labels can be decoded from.
68///
69/// It holds only what decoding reads: the metric name, the primary-key encoding, and the ordered
70/// primary-key columns with their physical types. A frame schema's [`LabelDecodeSpec`] reduces
71/// to this view, so decoding binds directly to the described layout.
72/// Every key column is a `Tag` column, which is checked when a decoder is bound, so the layout
73/// carries no per-column role.
74struct KeyLayout {
75    metric_name: Arc<str>,
76    encoding: PrimaryKeyEncoding,
77    columns: Vec<KeyColumn>,
78    /// Index of each column id in `columns`, built once when a decoder binds.
79    ///
80    /// `columns` is in primary-key encoding order, which is neither sorted nor otherwise
81    /// searchable by id, so a listed column is remembered by id instead: every lookup of a listed
82    /// column is then one probe instead of a walk over the whole physical key, and a sparse key is
83    /// audited in time proportional to its own label count rather than to `labels × columns`.
84    /// Duplicate ids cannot occur here, because [`LabelDecodeSpec::validate`] rejects them.
85    positions: HashMap<ColumnId, usize>,
86}
87
88impl KeyLayout {
89    /// Finds a listed primary-key column.
90    fn column(&self, id: ColumnId) -> Option<&KeyColumn> {
91        self.position(id).map(|position| &self.columns[position])
92    }
93
94    /// Returns the position of a listed primary-key column.
95    fn position(&self, id: ColumnId) -> Option<usize> {
96        self.positions.get(&id).copied()
97    }
98}
99
100/// Decodes labels on demand using the minimal primary-key layout bound to a raw-label source.
101pub struct PrimaryKeyLabelDecoder {
102    key: KeyLayout,
103    labels: Vec<BoundLabel>,
104    value_scratch: Vec<u8>,
105    layout: Layout,
106}
107
108impl PrimaryKeyLabelDecoder {
109    /// Binds a decoder to a frame schema's label decode description.
110    ///
111    /// This is the decoding path for a consumer that received only the raw frame schema: the
112    /// description carries the metric name, the primary-key encoding, the ordered key columns with
113    /// their physical types, and the logical tags. The description is validated first, so a version
114    /// or structure this revision cannot honour is an error instead of a best-effort decode.
115    ///
116    /// The description lists exactly the encoded key fields, and region metadata guarantees each
117    /// of them is a tag column, so no per-column role is carried or re-checked; an array position
118    /// is an encoding position. The logical tags are still checked here, one by one, exactly as
119    /// for a typed binding, which is the only place the decoder inspects them (a listed column no
120    /// tag selects is not examined).
121    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            // Filled from `columns` when the logical tags are bound.
140            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    /// Binds the ordered logical tags of `key` to one decode layout.
151    fn bind<'a, I>(mut key: KeyLayout, tags: I) -> Result<Self>
152    where
153        I: IntoIterator<Item = (ColumnId, &'a str)>,
154    {
155        // Index the physical key once, so binding its tags and auditing every decoded key probe
156        // the index instead of scanning the key columns per label.
157        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    /// Decodes labels without modifying or consuming `read_key`.
228    ///
229    /// Returns complete [`SeriesLabels`]. Dense keys are fully checked against the exact
230    /// described layout. Sparse keys receive a full structural audit before values are read.
231    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;