Skip to main content

servers/
exemplar.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
15//! Normalized metric exemplars shared by Remote Write and OTLP conversion.
16
17pub mod query;
18
19use std::collections::{BTreeMap, BTreeSet};
20
21use datatypes::json;
22use operator::insert::is_reserved_exemplar_tag;
23pub use operator::insert::{Exemplar, ExemplarBatch};
24use snafu::{OptionExt, ensure};
25
26use crate::error::{InvalidPromRemoteRequestSnafu, Result};
27
28/// Exemplars grouped by the source series' optional database routing control.
29pub type ExemplarRequests = BTreeMap<Option<String>, Vec<Exemplar>>;
30
31/// Bounds linear sparse conversion memory without quadratic `rows * tags` blowup.
32pub fn estimated_row_bytes<'a>(
33    requests: impl IntoIterator<Item = &'a [Exemplar]>,
34) -> Option<usize> {
35    requests.into_iter().try_fold(0usize, |total, exemplars| {
36        let mut tags = BTreeSet::new();
37        let mut payload = 0usize;
38        for exemplar in exemplars {
39            tags.extend(exemplar.series_labels.keys());
40            payload = payload.checked_add(exemplar.metric.len().checked_mul(4)?)?;
41            for (name, value) in exemplar.series_labels.iter().chain(&exemplar.labels) {
42                // Include owned strings, encoded keys/labels and JSON2 encoding scratch.
43                payload = payload.checked_add(
44                    name.len()
45                        .checked_add(value.len())?
46                        .checked_mul(4)?
47                        .checked_add(256)?,
48                )?;
49            }
50        }
51        let columns = tags.len().checked_add(6)?;
52        let rows = exemplars.len().checked_mul(512)?;
53        total
54            .checked_add(rows)?
55            .checked_add(columns.checked_mul(512)?)?
56            .checked_add(payload)
57    })
58}
59
60/// Validates labels with the protocol's name policy, preserving duplicates as errors.
61pub fn labels<I>(
62    labels: I,
63    exemplar_owned: bool,
64    validate_name: impl Fn(&[u8]) -> bool,
65) -> Result<BTreeMap<String, String>>
66where
67    I: IntoIterator<Item = (String, String)>,
68{
69    let mut result = BTreeMap::new();
70    let mut length = 0usize;
71    for (name, value) in labels {
72        ensure!(
73            validate_name(name.as_bytes()),
74            InvalidPromRemoteRequestSnafu {
75                msg: format!("invalid exemplar label name: {name}"),
76            }
77        );
78        if exemplar_owned {
79            ensure!(
80                name != json::JSON2_REMAINDER_FIELD_NAME,
81                InvalidPromRemoteRequestSnafu {
82                    msg: "exemplar label name is reserved by JSON2",
83                }
84            );
85        } else {
86            ensure!(
87                !is_reserved_exemplar_tag(&name),
88                InvalidPromRemoteRequestSnafu {
89                    msg: format!("inherited exemplar label collides with reserved column: {name}"),
90                }
91            );
92        }
93        length = length
94            .checked_add(name.chars().count())
95            .and_then(|n| n.checked_add(value.chars().count()))
96            .context(InvalidPromRemoteRequestSnafu {
97                msg: "exemplar label length overflow",
98            })?;
99        ensure!(
100            !exemplar_owned || length <= 128,
101            InvalidPromRemoteRequestSnafu {
102                msg: "exemplar label names and values exceed 128 characters",
103            }
104        );
105        ensure!(
106            result.insert(name.clone(), value).is_none(),
107            InvalidPromRemoteRequestSnafu {
108                msg: format!("duplicate exemplar label: {name}"),
109            }
110        );
111    }
112    Ok(result)
113}
114
115/// Converts Remote Write milliseconds without losing overflow information.
116pub fn timestamp_from_millis(timestamp: i64) -> Result<i64> {
117    timestamp
118        .checked_mul(1_000_000)
119        .context(InvalidPromRemoteRequestSnafu {
120            msg: "exemplar timestamp is outside the signed nanosecond range",
121        })
122}
123
124#[cfg(test)]
125mod tests {
126    use common_query::prelude::{EXEMPLAR_METRIC_COLUMN, greptime_exemplar_labels};
127    use metric_engine::row_modifier::TsidGenerator;
128    use store_api::metric_engine_consts::{
129        DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
130    };
131
132    use super::*;
133    use crate::prom_remote_write::validation::validate_label_name;
134
135    #[test]
136    fn test_exemplar_labels_and_timestamp_validation() {
137        assert!(
138            labels(
139                [(String::from("traceID"), String::from("abc"))],
140                true,
141                validate_label_name
142            )
143            .is_ok()
144        );
145        assert!(
146            labels(
147                [
148                    (String::from("job"), String::new()),
149                    (String::from("job"), String::new())
150                ],
151                false,
152                validate_label_name,
153            )
154            .is_err()
155        );
156        assert!(
157            labels(
158                [(EXEMPLAR_METRIC_COLUMN.into(), "x".into())],
159                false,
160                validate_label_name
161            )
162            .is_err()
163        );
164        assert!(labels([("id".into(), "x".repeat(127))], true, validate_label_name).is_err());
165        for name in ["", "request.method", "请求"] {
166            assert!(labels([(name.into(), "x".into())], true, validate_label_name).is_err());
167        }
168        for name in [
169            DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
170            DATA_SCHEMA_TSID_COLUMN_NAME,
171            greptime_exemplar_labels(),
172        ] {
173            assert!(labels([(name.into(), "x".into())], false, validate_label_name).is_err());
174        }
175        assert!(
176            labels(
177                [("exemplar_labels".into(), "x".into())],
178                false,
179                validate_label_name,
180            )
181            .is_ok()
182        );
183        assert_eq!(timestamp_from_millis(-1).unwrap(), -1_000_000);
184        assert!(timestamp_from_millis(i64::MAX).is_err());
185    }
186
187    #[test]
188    fn test_exemplar_tsid_uses_only_source_labels() {
189        let exemplar = Exemplar {
190            metric: "cpu".into(),
191            series_labels: BTreeMap::from([("job".into(), "api".into())]).into(),
192            timestamp: 1,
193            value: 2.0,
194            labels: BTreeMap::from([("trace_id".into(), "a".into())]),
195        };
196        let mut other = exemplar.clone();
197        other.metric = "memory".into();
198        other.labels.insert("trace_id".into(), "b".into());
199        let batch = ExemplarBatch::try_new(vec![exemplar, other]).unwrap();
200        assert_eq!(batch.sources().len(), 2);
201        let tsids: Vec<u64> = batch.exemplars().iter().map(Exemplar::tsid).collect();
202        let expected = TsidGenerator::from_sorted_tags([("job", "api")].into_iter());
203        assert_eq!(tsids, vec![expected, expected]);
204    }
205}