diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index 5cf378f4..9e59b2b4 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -274,7 +274,9 @@ async fn query( let instant = match InstantQuery::parse(query.0.as_deref(), &body) { Ok(Some(instant)) => instant, Ok(None) if state.no_forward => { - return not_answered("the request has no query parameter"); + return not_answered( + "the request has no query parameter, or names Prometheus' min or max time", + ); } Ok(None) => return forward(state, "query", method, query, headers, body).await, Err(bad) => { @@ -330,7 +332,7 @@ async fn query_range( Ok(Some(range)) => range, Ok(None) if state.no_forward => { return not_answered( - "the request lacks query, start, end or step, or names a time that is not in Unix seconds", + "the request lacks query, start, end or step, or names Prometheus' min or max time", ); } Ok(None) => return forward(state, "query_range", method, query, headers, body).await, diff --git a/data_plane/src/prometheus.rs b/data_plane/src/prometheus.rs index e777dacc..5737665d 100644 --- a/data_plane/src/prometheus.rs +++ b/data_plane/src/prometheus.rs @@ -21,31 +21,28 @@ pub struct InstantQuery { /// a time it cannot represent. Leaves room for any window offset. pub const MAX_TIME_MS: i64 = i64::MAX / 4; -/// Why an instant query's parameters are refused (400, `bad_data`). +/// Why a query's parameters are refused (400, `bad_data`): the error text. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("invalid parameter \"time\": {0}")] -pub struct BadTime(pub String); +#[error("{0}")] +pub struct BadParameter(pub String); impl InstantQuery { - /// Reads `query` and `time` (Unix seconds). `Ok(None)` if either is - /// missing or `time` is in another format, such as RFC 3339 (the query - /// is then forwarded); `Err` if `time` is a number that is not finite or - /// beyond [`MAX_TIME_MS`]. - pub fn parse(url_query: Option<&str>, form: &[u8]) -> Result, BadTime> { + /// Reads `query` and `time` ([`parse_time_ms`]; empty or missing: + /// now). `Ok(None)` if `query` is missing or `time` is Prometheus' min + /// or max time (the request is then forwarded, or refused without + /// forwarding); `Err` if `time` is not a parsable time or is beyond + /// [`MAX_TIME_MS`]. + pub fn parse(url_query: Option<&str>, form: &[u8]) -> Result, BadParameter> { let params: BTreeMap = form_urlencoded::parse(url_query.unwrap_or_default().as_bytes()) .chain(form_urlencoded::parse(form)) .map(|(k, v)| (k.into_owned(), v.into_owned())) .collect(); - let time_ms = match params.get("time") { + let time_ms = match params.get("time").filter(|time| !time.is_empty()) { None => None, - Some(time) => match time.parse::() { - Err(_) => return Ok(None), - Ok(seconds) => Some(checked_seconds_to_ms(seconds).ok_or_else(|| { - BadTime(format!( - "{time} is not a time the data plane can evaluate at" - )) - })?), + Some(time) => match parse_time_ms("time", time)? { + Some(ms) => Some(ms), + None => return Ok(None), }, }; let Some(query) = params.get("query") else { @@ -71,19 +68,15 @@ pub struct RangeQuery { pub step_ms: i64, } -/// Why a range query's parameters are refused (400, `bad_data`). -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("{0}")] -pub struct BadRange(pub String); - impl RangeQuery { - /// Reads `query`, `start` and `end` (Unix seconds) and `step` (seconds - /// or a Prometheus duration such as `15s` or `1m30s`). `Ok(None)` if - /// one is missing or a time is in another format, such as RFC 3339 (the - /// query is then forwarded); `Err` if they cannot be evaluated: a time - /// beyond [`MAX_TIME_MS`], a step that is not positive, an end before - /// the start, or more than [`MAX_RANGE_STEPS`] steps. - pub fn parse(url_query: Option<&str>, form: &[u8]) -> Result, BadRange> { + /// Reads `query`, `start` and `end` ([`parse_time_ms`]) and `step` + /// (seconds or a Prometheus duration such as `15s` or `1m30s`). + /// `Ok(None)` if one is missing or a time is Prometheus' min or max + /// time (the request is then forwarded, or refused without + /// forwarding); `Err` if they cannot be evaluated: a time that is not + /// parsable or is beyond [`MAX_TIME_MS`], a step that is not positive, + /// an end before the start, or more than [`MAX_RANGE_STEPS`] steps. + pub fn parse(url_query: Option<&str>, form: &[u8]) -> Result, BadParameter> { let params: BTreeMap = form_urlencoded::parse(url_query.unwrap_or_default().as_bytes()) .chain(form_urlencoded::parse(form)) @@ -97,32 +90,24 @@ impl RangeQuery { ) else { return Ok(None); }; - let time = |name: &str, text: &str| -> Result, BadRange> { - match text.parse::() { - Err(_) => Ok(None), - Ok(seconds) => checked_seconds_to_ms(seconds).map(Some).ok_or_else(|| { - BadRange(format!( - "invalid parameter \"{name}\": {text} is not a time the data plane can evaluate at" - )) - }), - } - }; - let (Some(start_ms), Some(end_ms)) = (time("start", start)?, time("end", end)?) else { + let (Some(start_ms), Some(end_ms)) = + (parse_time_ms("start", start)?, parse_time_ms("end", end)?) + else { return Ok(None); }; let step_ms = step_ms(step).filter(|&ms| ms > 0).ok_or_else(|| { - BadRange(format!( + BadParameter(format!( "invalid parameter \"step\": {step:?} is not a positive duration" )) })?; if end_ms < start_ms { - return Err(BadRange( + return Err(BadParameter( "invalid parameter \"end\": end timestamp must not be before start time".into(), )); } // As Prometheus: refused when (end - start) / step exceeds it. if (end_ms - start_ms) / step_ms > MAX_RANGE_STEPS { - return Err(BadRange(format!( + return Err(BadParameter(format!( "exceeded maximum resolution of {MAX_RANGE_STEPS} points per timeseries. Try decreasing the query resolution (?step=XX)" ))); } @@ -174,10 +159,145 @@ fn step_ms(text: &str) -> Option { (!text.is_empty()).then_some(total) } +/// Prometheus' smallest and largest times, as its clients send them for +/// "no bound" (`v1.MinTime` and `v1.MaxTime` formatted as RFC 3339). +const PROMETHEUS_MIN_TIME: &str = "-292273086-05-16T16:47:06Z"; +const PROMETHEUS_MAX_TIME: &str = "292277025-08-17T07:12:55.999999999Z"; + +/// Query parameter `name`'s time `text` in milliseconds since the epoch, as +/// the Prometheus HTTP API reads it: Unix seconds with an optional fraction +/// (rounded to the millisecond), else RFC 3339 ([`rfc3339_ms`]). `Ok(None)` +/// for Prometheus' min or max time, which the data plane does not evaluate +/// at. `Err` is the 400 error text: Prometheus' for a value in neither +/// form, or a time beyond [`MAX_TIME_MS`]. +pub fn parse_time_ms(name: &str, text: &str) -> Result, BadParameter> { + if text == PROMETHEUS_MIN_TIME || text == PROMETHEUS_MAX_TIME { + return Ok(None); + } + match text.parse::() { + Ok(seconds) => checked_seconds_to_ms(seconds).map(Some).ok_or_else(|| { + BadParameter(format!( + "invalid parameter \"{name}\": {text} is not a time the data plane can evaluate at" + )) + }), + Err(_) => rfc3339_ms(text).map(Some).ok_or_else(|| { + BadParameter(format!( + "invalid parameter \"{name}\": cannot parse {text:?} to a valid timestamp" + )) + }), + } +} + +/// An RFC 3339 time (`2026-11-24T05:00:00Z`, `2026-11-24T05:00:00.25+01:00`) +/// in milliseconds since the epoch (fraction truncated, as Prometheus +/// truncates a parsed time), as Go's `time.Parse(time.RFC3339Nano, ..)` +/// accepts it: a four-digit year, `T`, a one- or two-digit hour, a fraction +/// of any length after `.` or `,`, and `Z` or a `±hh:mm` offset of at most +/// 24 hours and 60 minutes. +fn rfc3339_ms(text: &str) -> Option { + let bytes = text.as_bytes(); + let mut at = 0; + let year = digits(bytes, &mut at, 4, 4)?; + separator(bytes, &mut at, b'-')?; + let month = digits(bytes, &mut at, 2, 2)?; + separator(bytes, &mut at, b'-')?; + let day = digits(bytes, &mut at, 2, 2)?; + separator(bytes, &mut at, b'T')?; + let hour = digits(bytes, &mut at, 1, 2)?; + separator(bytes, &mut at, b':')?; + let minute = digits(bytes, &mut at, 2, 2)?; + separator(bytes, &mut at, b':')?; + let second = digits(bytes, &mut at, 2, 2)?; + let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if leap => 29, + 2 => 28, + _ => return None, + }; + if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 59 { + return None; + } + // Fractional seconds: `.` or `,` and one or more digits, the first + // three kept. + let mut fraction_ms = 0; + if matches!(bytes.get(at), Some(b'.' | b',')) { + let count = bytes[at + 1..] + .iter() + .take_while(|b| b.is_ascii_digit()) + .count(); + if count == 0 { + return None; + } + fraction_ms = bytes[at + 1..at + 1 + count.min(3)] + .iter() + .fold(0, |n, d| n * 10 + i64::from(d - b'0')) + * 10_i64.pow(3 - count.min(3) as u32); + at += 1 + count; + } + let offset_s = match &bytes[at..] { + b"Z" => 0, + [sign @ (b'+' | b'-'), h1, h2, b':', m1, m2] + if [h1, h2, m1, m2].iter().all(|b| b.is_ascii_digit()) => + { + let hours = i64::from((h1 - b'0') * 10 + (h2 - b'0')); + let minutes = i64::from((m1 - b'0') * 10 + (m2 - b'0')); + if hours > 24 || minutes > 60 { + return None; + } + let offset = hours * 3600 + minutes * 60; + if *sign == b'-' { + -offset + } else { + offset + } + } + _ => return None, + }; + // Days since the epoch of the civil date (H. Hinnant's algorithm). + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let year_of_era = y - era * 400; + let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + let days = era * 146_097 + day_of_era - 719_468; + let seconds = days * 86_400 + hour * 3600 + minute * 60 + second - offset_s; + Some(seconds * 1000 + fraction_ms) +} + +/// The number in `min..=max` digits at `*at` of `bytes`, moving `*at` past +/// them. +fn digits(bytes: &[u8], at: &mut usize, min: usize, max: usize) -> Option { + let count = bytes[*at..] + .iter() + .take(max) + .take_while(|b| b.is_ascii_digit()) + .count(); + if count < min { + return None; + } + let value = bytes[*at..*at + count] + .iter() + .fold(0, |n, d| n * 10 + i64::from(d - b'0')); + *at += count; + Some(value) +} + +/// Byte `c` at `*at` of `bytes`, moving `*at` past it. +fn separator(bytes: &[u8], at: &mut usize, c: u8) -> Option<()> { + (bytes.get(*at) == Some(&c)).then(|| *at += 1) +} + /// `seconds` in milliseconds, if finite and within [`MAX_TIME_MS`]. +/// As Prometheus: the whole seconds, plus the fraction rounded to the +/// millisecond (which keeps a sub-millisecond fraction exact at large +/// times, where `seconds * 1000` would not). fn checked_seconds_to_ms(seconds: f64) -> Option { - let ms = (seconds * 1000.0).round(); - (ms.is_finite() && ms.abs() <= MAX_TIME_MS as f64).then_some(ms as i64) + if !seconds.is_finite() || seconds.abs() > (MAX_TIME_MS / 1000) as f64 { + return None; + } + Some(seconds.trunc() as i64 * 1000 + (seconds.fract() * 1000.0).round() as i64) } /// A Prometheus `bad_data` error response body. @@ -398,7 +518,8 @@ mod tests { use super::*; use std::sync::Arc; - /// Parameters come from the URL or the form body; times are Unix seconds. + /// Parameters come from the URL or the form body; `time` is Unix + /// seconds or RFC 3339, an empty one is now. #[test] fn parses_instant_query_parameters() { let q = InstantQuery::parse(Some("query=up&time=1.5"), b"") @@ -410,11 +531,20 @@ mod tests { .unwrap(); assert_eq!((q.query.as_str(), q.time_ms), ("sum(x)", None)); assert!(InstantQuery::parse(Some("time=1"), b"").unwrap().is_none()); - assert!( - InstantQuery::parse(Some("query=up&time=2026-01-01T00:00:00Z"), b"") - .unwrap() - .is_none() - ); + let q = InstantQuery::parse(Some("query=up&time=2026-01-01T00:00:00Z"), b"") + .unwrap() + .unwrap(); + assert_eq!(q.time_ms, Some(1_767_225_600_000)); + assert!(InstantQuery::parse(Some("query=up&time=tomorrow"), b"").is_err()); + let q = InstantQuery::parse(Some("query=up&time="), b"") + .unwrap() + .unwrap(); + assert_eq!(q.time_ms, None); + // Prometheus' min and max times: forwarded. + for time in [PROMETHEUS_MIN_TIME, PROMETHEUS_MAX_TIME] { + let url = format!("query=up&time={time}"); + assert!(InstantQuery::parse(Some(&url), b"").unwrap().is_none()); + } for time in ["-1e300", "1e300", "NaN", "inf"] { let url = format!("query=up&time={time}"); assert!(InstantQuery::parse(Some(&url), b"").is_err(), "{time}"); @@ -439,12 +569,13 @@ mod tests { assert!(RangeQuery::parse(Some("query=up&start=0&end=60"), b"") .unwrap() .is_none()); - assert!(RangeQuery::parse( - Some("query=up&start=2026-01-01T00:00:00Z&end=1&step=1"), - b"" + let q = RangeQuery::parse( + Some("query=up&start=1970-01-01T00:00:01Z&end=2&step=1"), + b"", ) .unwrap() - .is_none()); + .unwrap(); + assert_eq!((q.start_ms, q.end_ms), (1_000, 2_000)); for bad in [ "query=up&start=0&end=60&step=0", "query=up&start=0&end=60&step=x", @@ -456,6 +587,59 @@ mod tests { } } + /// RFC 3339 times as Go's `time.Parse(time.RFC3339Nano, ..)` accepts + /// them, in milliseconds since the epoch (fractions truncated, as + /// Prometheus truncates a parsed time to the millisecond). + #[test] + fn parses_rfc3339_times() { + for (text, ms) in [ + ("1970-01-01T00:00:00Z", 0), + ("2026-11-24T05:00:00Z", 1_795_496_400_000), + ("2026-11-24T05:00:00.5Z", 1_795_496_400_500), + ("2026-11-24T05:00:00.123456789Z", 1_795_496_400_123), + ("2026-11-24T06:30:00+01:30", 1_795_496_400_000), + ("2026-11-24T00:00:00-05:00", 1_795_496_400_000), + ("2024-02-29T00:00:00Z", 1_709_164_800_000), + ("1969-12-31T23:59:59.999Z", -1), + ("0001-01-01T00:00:00Z", -62_135_596_800_000), + // Go's lenient forms: a long fraction, a comma, a one-digit + // hour, a 24-hour offset. + ("2026-11-24T05:00:00.1234567890123Z", 1_795_496_400_123), + ("2026-11-24T05:00:00,5Z", 1_795_496_400_500), + ("2026-11-24T5:00:00Z", 1_795_496_400_000), + ("2026-11-25T05:00:00+24:00", 1_795_496_400_000), + ] { + assert_eq!(rfc3339_ms(text), Some(ms), "{text}"); + } + for text in [ + "2026-11-24T05:00:00", + "2026-11-24t05:00:00Z", + "2026-11-24 05:00:00Z", + "2026-11-24T05:00:00.Z", + "2026-11-24T05:00Z", + "2023-02-29T00:00:00Z", + "2026-04-31T00:00:00Z", + "2026-11-24T05:00:60Z", + "2026-11-24T05:00:00+0100", + "2026-11-24T05:00:00+25:00", + "2026-11-24T05:00:00+01:61", + "+2026-11-24T05:00:00Z", + "2026-11-24T05:00:00Z ", + ] { + assert_eq!(rfc3339_ms(text), None, "{text}"); + } + assert_eq!( + parse_time_ms("time", "x").unwrap_err().0, + "invalid parameter \"time\": cannot parse \"x\" to a valid timestamp" + ); + assert_eq!(parse_time_ms("end", "1.0015"), Ok(Some(1_002))); + // The fraction rounded on its own, as Prometheus rounds it. + assert_eq!( + parse_time_ms("time", "1763408220.0665"), + Ok(Some(1_763_408_220_066)) + ); + } + /// Range results use Prometheus' matrix shape: one entry per series /// with its values in time order. #[test] diff --git a/data_plane/tests/time_params.rs b/data_plane/tests/time_params.rs new file mode 100644 index 00000000..8d4fb245 --- /dev/null +++ b/data_plane/tests/time_params.rs @@ -0,0 +1,253 @@ +//! Query times as the Prometheus HTTP API takes them: `time`, `start` and +//! `end` are Unix seconds (with an optional fraction) or RFC 3339 (with +//! optional fractional seconds and a zone offset), as vmalert sends them. +//! A planned query is answered from the plan in either form, with the same +//! answer; a time in neither form is refused with Prometheus' 400. + +mod common; + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use axum::Router; +use control_plane::plan_workload; +use data_plane::engine::EngineOptions; +use data_plane::ingestion::IngestionOptions; +use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; +use data_plane::{router, DataPlane, EXECUTION_HEADER}; +use http_body_util::BodyExt; +use serde_json::{json, Value}; +use tower::ServiceExt; + +const SUM: &str = "sum(sum_over_time(data[1m]))"; +const SERIES: usize = 5; + +/// The plan of `SUM` every 10 s over `SERIES` series of `data`; with +/// `no_forward`, a query the data plane does not answer from the plan is +/// refused instead of forwarded. +fn data_plane() -> Router { + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": [{ + "query": SUM, + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": {}, + "predictability": {"predictable": {"known_at": null}}, + }]}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": SERIES as f64}}, + "sources": {"data": {"series_count": SERIES, "sample_interval": 1000, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let plan = plan_workload(&workload, &common::inputs(false)).unwrap().0; + let options = EngineOptions { + no_forward: true, + view_dir: None, + ingestion: IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(0), + ..IngestionOptions::default() + }, + ..EngineOptions::default() + }; + let state = DataPlane::with_options( + serde_json::to_string(&plan).unwrap(), + "http://127.0.0.1:1".into(), + options, + ) + .unwrap(); + router(Arc::new(state)) +} + +/// One sample per second in `(0, to_s]` for every series, then a barrier +/// closing every window through `to_s`. +async fn write(app: &Router, to_s: i64) { + let timeseries = (0..SERIES) + .map(|series| TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "data".into(), + }, + Label { + name: "instance".into(), + value: format!("i{series}"), + }, + ], + samples: (1..=to_s) + .map(|s| Sample { + timestamp: s * 1000, + value: (s + series as i64) as f64, + }) + .collect(), + }) + .collect(); + let written = app + .clone() + .oneshot( + Request::post("/api/v1/write") + .body(Body::from(encode(&WriteRequest { timeseries }))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(written.status(), StatusCode::NO_CONTENT); + let barrier = app + .clone() + .oneshot( + Request::post(format!( + "/api/v1/precompute/watermark?time_ms={}", + to_s * 1000 + )) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(barrier.status(), StatusCode::OK); +} + +/// `endpoint`'s response to `SUM` with `params` (URL-encoded here): its +/// status, whether the plan answered it, and its body. +async fn get(app: &Router, endpoint: &str, params: &[(&str, &str)]) -> (StatusCode, bool, Value) { + let mut query = form_urlencoded::Serializer::new(String::new()); + query.append_pair("query", SUM); + for (name, value) in params { + query.append_pair(name, value); + } + let response = app + .clone() + .oneshot( + Request::get(format!("/api/v1/{endpoint}?{}", query.finish())) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let from_plan = response + .headers() + .get(EXECUTION_HEADER) + .is_some_and(|value| value == "plan"); + let body = response.into_body().collect().await.unwrap().to_bytes(); + (status, from_plan, serde_json::from_slice(&body).unwrap()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn rfc3339_times_are_answered_from_the_plan_like_unix_seconds() { + let app = data_plane(); + write(&app, 180).await; + + // Instant: 120 s after the epoch, in each form. + let (status, from_plan, expected) = get(&app, "query", &[("time", "120")]).await; + assert_eq!((status, from_plan), (StatusCode::OK, true), "{expected}"); + assert_eq!(expected["data"]["result"].as_array().unwrap().len(), 1); + for time in [ + "120.000", + "1970-01-01T00:02:00Z", + "1970-01-01T00:02:00.000Z", + "1970-01-01T00:02:00.000000000Z", + "1970-01-01T01:02:00+01:00", + "1969-12-31T23:32:00-00:30", + ] { + let (status, from_plan, served) = get(&app, "query", &[("time", time)]).await; + assert_eq!( + (status, from_plan), + (StatusCode::OK, true), + "{time}: {served}" + ); + assert_eq!(served, expected, "{time}"); + } + + // Range: 150 s to 180 s (inside the views' retention) every 10 s, in each form. + let (status, from_plan, expected) = get( + &app, + "query_range", + &[("start", "150"), ("end", "180"), ("step", "10")], + ) + .await; + assert_eq!((status, from_plan), (StatusCode::OK, true), "{expected}"); + for (start, end) in [ + ("1970-01-01T00:02:30Z", "1970-01-01T00:03:00Z"), + ("1970-01-01T00:02:30.0Z", "180"), + ("150", "1970-01-01T05:33:00+05:30"), + ] { + let (status, from_plan, served) = get( + &app, + "query_range", + &[("start", start), ("end", end), ("step", "10")], + ) + .await; + assert_eq!( + (status, from_plan), + (StatusCode::OK, true), + "{start}..{end}: {served}" + ); + assert_eq!(served, expected, "{start}..{end}"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn times_in_neither_form_are_refused_as_prometheus_refuses_them() { + let app = data_plane(); + write(&app, 60).await; + for bad in [ + "yesterday", + "1970-01-01T00:02:00", + "1970-01-01 00:02:00Z", + "1970-13-01T00:00:00Z", + "1970-02-30T00:00:00Z", + "1970-01-01T24:00:00Z", + "1970-01-01T00:02:00+25:00", + "70-01-01T00:02:00Z", + "1970-01-01T00:02:00.Z", + ] { + let (status, _, body) = get(&app, "query", &[("time", bad)]).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{bad:?}: {body}"); + assert_eq!( + body, + json!({"status": "error", "errorType": "bad_data", + "error": format!("invalid parameter \"time\": cannot parse {bad:?} to a valid timestamp")}), + ); + for name in ["start", "end"] { + let mut params = vec![("start", "0"), ("end", "60"), ("step", "10")]; + params.retain(|(n, _)| *n != name); + params.push((name, bad)); + let (status, _, body) = get(&app, "query_range", ¶ms).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{name}={bad:?}: {body}"); + assert_eq!( + body["error"], + format!("invalid parameter \"{name}\": cannot parse {bad:?} to a valid timestamp"), + ); + } + } + // An empty `start` or `end` is refused too; an empty `time` is now. + for name in ["start", "end"] { + let mut params = vec![("start", "0"), ("end", "60"), ("step", "10")]; + params.retain(|(n, _)| *n != name); + params.push((name, "")); + let (status, _, body) = get(&app, "query_range", ¶ms).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{name}=\"\": {body}"); + } + let (status, _, body) = get(&app, "query", &[("time", "")]).await; + assert_ne!(status, StatusCode::BAD_REQUEST, "time=\"\": {body}"); +} + +/// Prometheus' min and max times ("no bound") are valid times the plan +/// does not evaluate at: forwarded, so refused here without forwarding, +/// not rejected as unparsable. +#[tokio::test(flavor = "multi_thread")] +async fn prometheus_min_and_max_times_are_not_answered_from_the_plan() { + let app = data_plane(); + write(&app, 60).await; + for time in [ + "-292273086-05-16T16:47:06Z", + "292277025-08-17T07:12:55.999999999Z", + ] { + let (status, from_plan, body) = get(&app, "query", &[("time", time)]).await; + assert!( + status != StatusCode::BAD_REQUEST && !from_plan, + "{time}: {status} {body}" + ); + } +}