1use std::collections::BTreeMap;
18
19use promql_parser::label::{METRIC_NAME, MatchOp, Matcher};
20use promql_parser::parser::{Expr, VectorSelector};
21use promql_parser::util::{ExprVisitor, walk_expr};
22use query::parser::QueryLanguageParser;
23use query::promql::label_values::signed_millis_since_epoch;
24use serde::{Deserialize, Serialize};
25use snafu::OptionExt;
26
27use crate::error::{InvalidQuerySnafu, Result};
28use crate::prom_store::{FIELD_NAME_LABEL, is_database_selection_label};
29use crate::prometheus_handler::resolve_schema_from_matchers;
30
31#[derive(Debug, Clone)]
32pub struct Selector {
33 pub schema: String,
34 pub matchers: Vec<Matcher>,
35}
36
37#[derive(Debug)]
38pub struct Query {
39 pub expression: String,
40 pub selectors: Vec<Selector>,
41 pub bounds: (i64, i64),
43}
44
45impl Query {
46 pub fn parse(expression: String, start: &str, end: &str, schema: &str) -> Result<Self> {
47 let parse = |input| {
48 let time = QueryLanguageParser::parse_promql_timestamp(input).map_err(|error| {
49 InvalidQuerySnafu {
50 reason: error.to_string(),
51 }
52 .build()
53 })?;
54 let millis = signed_millis_since_epoch(time).map_err(|error| {
55 InvalidQuerySnafu {
56 reason: error.to_string(),
57 }
58 .build()
59 })?;
60 millis.checked_mul(1_000_000).context(InvalidQuerySnafu {
61 reason: "timestamp exceeds signed nanosecond range",
62 })
63 };
64 let start = parse(start)?;
65 let end = parse(end)?;
66 if start > end {
67 return invalid("start must not exceed end");
68 }
69 let expr = promql_parser::parser::parse(&expression)
70 .map_err(|reason| InvalidQuerySnafu { reason }.build())?;
71 struct Collector<'a> {
72 schema: &'a str,
73 selectors: Vec<Selector>,
74 }
75 impl ExprVisitor for Collector<'_> {
76 type Error = crate::error::Error;
77 fn pre_visit(&mut self, expr: &Expr) -> Result<bool> {
78 let selector = match expr {
79 Expr::VectorSelector(vs) => vs,
80 Expr::MatrixSelector(ms) => &ms.vs,
81 Expr::Aggregate(aggregate) => {
82 if let Some(param) = &aggregate.param {
84 walk_expr(self, param)?;
85 }
86 return Ok(true);
87 }
88 _ => return Ok(true),
89 };
90 self.selectors.extend(resolve(selector, self.schema)?);
91 Ok(true)
92 }
93 }
94 let mut collector = Collector {
95 schema,
96 selectors: Vec::new(),
97 };
98 walk_expr(&mut collector, &expr)?;
99 Ok(Self {
100 expression,
101 selectors: collector.selectors,
102 bounds: (start, end.saturating_add(999_999)),
104 })
105 }
106}
107
108fn resolve(selector: &VectorSelector, default_schema: &str) -> Result<Vec<Selector>> {
109 let branches = if selector.matchers.or_matchers.is_empty() {
110 vec![&selector.matchers.matchers]
111 } else {
112 selector.matchers.or_matchers.iter().collect()
113 };
114 branches
115 .into_iter()
116 .map(|branch| {
117 if branch
118 .iter()
119 .any(|matcher| matcher.name == FIELD_NAME_LABEL)
120 {
121 return invalid("__field__ is not supported in exemplar queries");
122 }
123 let schema =
124 resolve_schema_from_matchers(branch)?.unwrap_or_else(|| default_schema.to_string());
125 let mut matchers = branch
126 .iter()
127 .filter(|matcher| !is_database_selection_label(&matcher.name))
128 .cloned()
129 .collect::<Vec<_>>();
130 if let Some(name) = &selector.name {
131 matchers.push(Matcher::new(MatchOp::Equal, METRIC_NAME, name));
132 }
133 Ok(Selector { schema, matchers })
134 })
135 .collect()
136}
137
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139pub struct Series {
140 #[serde(rename = "seriesLabels")]
142 pub series_labels: BTreeMap<String, String>,
143 pub exemplars: Vec<Observation>,
144}
145
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct Observation {
148 pub labels: BTreeMap<String, String>,
149 pub value: String,
150 pub timestamp: f64,
152}
153
154fn invalid<T>(reason: &str) -> Result<T> {
155 InvalidQuerySnafu { reason }.fail()
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn query_bounds_use_prometheus_milliseconds() {
164 for (input, millis) in [
165 ("1.234567891", 1235),
166 ("1.234e0", 1234),
167 ("1720000000.123456789", 1720000000123),
168 ("-0.0006", -1),
169 ("-0.0004", 0),
170 ("-1.0005", -1000),
171 ("1970-01-01T00:00:00.0019Z", 1),
172 ("1969-12-31T23:59:59.999999999Z", -1),
173 ("1970-01-01T01:00:00.0019+01:00", 1),
174 ] {
175 assert_eq!(
176 Query::parse("up".into(), input, input, "public")
177 .unwrap()
178 .bounds,
179 (millis * 1_000_000, millis * 1_000_000 + 999_999),
180 "{input}",
181 );
182 }
183 assert_eq!(
184 Query::parse("up".into(), "0.0012", "0.0011", "public")
185 .unwrap()
186 .bounds,
187 (1_000_000, 1_999_999),
188 );
189 assert_eq!(
190 Query::parse(
191 "up".into(),
192 "2262-04-11T23:47:16.854Z",
193 "2262-04-11T23:47:16.854Z",
194 "public"
195 )
196 .unwrap()
197 .bounds,
198 (9_223_372_036_854_000_000, i64::MAX),
199 );
200 assert!(Query::parse("up".into(), "0.002", "0.001", "public").is_err());
201 for input in [
202 "NaN",
203 "inf",
204 "",
205 "1e100",
206 "9223372036.855",
207 "-9223372036.855",
208 ] {
209 assert!(
210 Query::parse("up".into(), input, input, "public").is_err(),
211 "{input}"
212 );
213 }
214 assert!(
215 Query::parse("1".into(), "0", "1", "public")
216 .unwrap()
217 .selectors
218 .is_empty()
219 );
220 }
221
222 #[test]
223 fn aggregation_parameter_selectors() {
224 for (expression, expected) in [
225 (
226 "topk(scalar(limit_metric), requests)",
227 vec!["limit_metric", "requests"],
228 ),
229 (
230 "bottomk(scalar(limit_metric), requests)",
231 vec!["limit_metric", "requests"],
232 ),
233 (
234 "quantile(scalar(limit_metric), requests)",
235 vec!["limit_metric", "requests"],
236 ),
237 (
238 "topk(scalar(topk(scalar(inner_limit), limit_metric)), requests)",
239 vec!["inner_limit", "limit_metric", "requests"],
240 ),
241 ("topk(2, requests)", vec!["requests"]),
242 ("count_values(\"kind\", requests)", vec!["requests"]),
243 (
244 "topk(scalar(requests), requests)",
245 vec!["requests", "requests"],
246 ),
247 ] {
248 let query = Query::parse(expression.into(), "0", "1", "public").unwrap();
249 let mut names = query
250 .selectors
251 .iter()
252 .flat_map(|selector| &selector.matchers)
253 .filter(|matcher| matcher.name == METRIC_NAME)
254 .map(|matcher| matcher.value.as_str())
255 .collect::<Vec<_>>();
256 names.sort_unstable();
257 assert_eq!(names, expected, "{expression}");
258 }
259 }
260
261 #[test]
262 fn range_vectors_and_routing_controls() {
263 let query = Query::parse(
264 "topk(scalar(sum(rate(requests{__schema__=\"a\"}[5m]))), errors{__database__=\"b\"})"
265 .into(),
266 "0",
267 "1",
268 "public",
269 )
270 .unwrap();
271 assert_eq!(
272 query
273 .selectors
274 .iter()
275 .map(|s| s.schema.as_str())
276 .collect::<Vec<_>>(),
277 ["a", "b"]
278 );
279 for query in [
280 "up{__schema__=\"\"}",
281 "up{__schema__!=\"a\"}",
282 "up{__field__=\"x\"}",
283 "topk(scalar(up{__schema__=\"\"}), requests)",
284 "topk(scalar(up{__schema__!=\"a\"}), requests)",
285 "topk(scalar(up{__field__=\"x\"}), requests)",
286 ] {
287 assert!(Query::parse(query.into(), "0", "1", "public").is_err());
288 }
289 }
290}