use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use sha2::{Digest, Sha256};
use super::aggregate::{Asking, Op, Shape};
use super::engine::Engine;
use super::explain::Plan;
use super::labels::{MOST_LABELS, MOST_NAME_BYTES, MOST_VALUE_BYTES, NAME};
use super::latest::Latest;
use super::page::{AggregatePage, Cursor, MOST, Paging, SeriesPage, Start};
use crate::calendar::Calendar;
use crate::{Error, Result, unix_millis};
const MOST_VALUES: usize = 1000;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Condition {
OneOf(Vec<String>),
NoneOf(Vec<String>),
Prefix(String),
}
#[derive(Clone, Copy, Debug)]
pub struct Not<T>(pub T);
#[derive(Clone, Copy, Debug)]
pub struct Prefix<T>(pub T);
pub trait Values {
fn values(self) -> Vec<String>;
}
impl Values for &str {
fn values(self) -> Vec<String> {
vec![self.to_owned()]
}
}
impl Values for String {
fn values(self) -> Vec<String> {
vec![self]
}
}
impl Values for &String {
fn values(self) -> Vec<String> {
vec![self.clone()]
}
}
impl<T: Values, const N: usize> Values for [T; N] {
fn values(self) -> Vec<String> {
self.into_iter().flat_map(Values::values).collect()
}
}
impl<T: Values> Values for Vec<T> {
fn values(self) -> Vec<String> {
self.into_iter().flat_map(Values::values).collect()
}
}
impl<T: Values + Clone> Values for &[T] {
fn values(self) -> Vec<String> {
self.iter().cloned().flat_map(Values::values).collect()
}
}
macro_rules! values_as_text {
($($kind:ty),*) => {$(
impl Values for $kind {
fn values(self) -> Vec<String> {
vec![self.to_string()]
}
}
)*};
}
values_as_text!(i8, i16, i32, i64, u8, u16, u32, u64, usize, bool);
impl<T: Values> From<T> for Condition {
fn from(values: T) -> Condition {
Condition::OneOf(values.values())
}
}
impl<T: Values> From<Not<T>> for Condition {
fn from(Not(values): Not<T>) -> Condition {
Condition::NoneOf(values.values())
}
}
impl<T: Into<String>> From<Prefix<T>> for Condition {
fn from(Prefix(prefix): Prefix<T>) -> Condition {
Condition::Prefix(prefix.into())
}
}
pub(crate) type Checked<T> = Box<dyn FnOnce() -> Result<T> + Send>;
#[derive(Clone)]
pub struct Query {
pub(super) engine: Arc<Engine>,
name: Option<String>,
conditions: Vec<(String, Condition)>,
since: Option<Duration>,
from: Option<SystemTime>,
to: Option<SystemTime>,
every: Option<Duration>,
calendar: Option<(Calendar, String)>,
by: Option<Vec<String>>,
without: Option<Vec<String>>,
estimate: bool,
limit: Option<usize>,
after: Option<String>,
}
impl fmt::Debug for Query {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Query")
.field("name", &self.name)
.field("conditions", &self.conditions)
.field("since", &self.since)
.field("from", &self.from)
.field("to", &self.to)
.field("every", &self.every)
.field("calendar", &self.calendar)
.field("by", &self.by)
.field("without", &self.without)
.field("estimate", &self.estimate)
.field("limit", &self.limit)
.field("after", &self.after)
.finish()
}
}
#[derive(Clone, Debug)]
pub(super) struct Asked {
pub(super) name: Option<String>,
pub(super) conditions: Vec<(String, Condition)>,
pub(super) from: i64,
pub(super) to: i64,
pub(super) now: i64,
}
impl Query {
pub(super) fn of(engine: Arc<Engine>) -> Query {
Query {
engine,
name: None,
conditions: Vec::new(),
since: None,
from: None,
to: None,
every: None,
calendar: None,
by: None,
without: None,
estimate: false,
limit: None,
after: None,
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn filter(mut self, label: impl Into<String>, condition: impl Into<Condition>) -> Self {
self.conditions.push((label.into(), condition.into()));
self
}
pub fn since(mut self, span: Duration) -> Self {
self.since = Some(span);
self
}
pub fn from(mut self, at: SystemTime) -> Self {
self.from = Some(at);
self
}
pub fn to(mut self, at: SystemTime) -> Self {
self.to = Some(at);
self
}
pub fn every(mut self, span: Duration) -> Self {
self.every = Some(span);
self
}
pub fn calendar(mut self, unit: Calendar, zone: &str) -> Self {
self.calendar = Some((unit, zone.to_owned()));
self
}
pub fn by(mut self, labels: &[&str]) -> Self {
self.by.get_or_insert_default().extend(labels.iter().map(|label| (*label).to_owned()));
self
}
pub fn without(mut self, labels: &[&str]) -> Self {
self.without.get_or_insert_default().extend(labels.iter().map(|label| (*label).to_owned()));
self
}
pub fn estimate(mut self) -> Self {
self.estimate = true;
self
}
pub fn limit(mut self, samples: usize) -> Self {
self.limit = Some(samples);
self
}
pub fn after(mut self, next: &str) -> Self {
self.after = Some(next.to_owned());
self
}
pub fn read(&self) -> Result<SeriesPage> {
self.checked_read().and_then(|read| read())
}
pub(crate) fn checked_read(&self) -> Result<Checked<SeriesPage>> {
let checked = self.plain("read").and_then(|()| self.paged(None));
let query = self.clone();
self.once_checked(checked, move |engine, (asked, paging)| {
let (series, place) = engine.read(&asked, paging.as_ref())?;
let next = place.zip(paging).map(|(place, paging)| Cursor::after(&asked, &paging, Start::Series(place)));
Ok(SeriesPage::of(series, next.map(|next| next.written()), query))
})
}
pub fn aggregate(&self, op: Op) -> Result<AggregatePage> {
self.checked_aggregate(op).and_then(|aggregate| aggregate())
}
pub(crate) fn checked_aggregate(&self, op: Op) -> Result<Checked<AggregatePage>> {
let checked = self.shape(op).and_then(|shape| Ok((self.paged(Some(op))?, shape)));
let query = self.clone();
self.once_checked(checked, move |engine, ((asked, paging), shape)| {
let (groups, place) = engine.aggregate(&asked, &shape, paging.as_ref())?;
let next = place.zip(paging).map(|(place, paging)| Cursor::after(&asked, &paging, Start::Group(place)));
Ok(AggregatePage::of(groups, next.map(|next| next.written()), query, op))
})
}
pub fn latest(&self) -> Result<Vec<Latest>> {
self.checked_latest().and_then(|latest| latest())
}
pub(crate) fn checked_latest(&self) -> Result<Checked<Vec<Latest>>> {
let checked = self.plain("latest").and_then(|()| self.unpaged("latest")).and_then(|()| self.asked());
self.once_checked(checked, |engine, asked| engine.latest(&asked))
}
pub fn explain(&self, op: impl Into<Option<Op>>) -> Result<Plan> {
self.checked_explain(op.into()).and_then(|explain| explain())
}
pub(crate) fn checked_explain(&self, op: Option<Op>) -> Result<Checked<Plan>> {
let shape = self.unpaged("explain").and_then(|()| match op {
Some(op) => self.shape(op).map(Some),
None => self.plain("a read").map(|()| None),
});
let checked = shape.and_then(|shape| Ok((self.asked()?, shape)));
self.once_checked(checked, |engine, (asked, shape)| engine.explain(&asked, shape.as_ref()))
}
fn once_checked<C: Send + 'static, T: 'static>(
&self,
checked: Result<C>,
run: impl FnOnce(&Engine, C) -> Result<T> + Send + 'static,
) -> Result<Checked<T>> {
let checked = checked.map_err(|error| error.within("metrics"))?;
let engine = Arc::clone(&self.engine);
Ok(Box::new(move || run(&engine, checked).map_err(|error| error.within("metrics"))))
}
fn shape(&self, op: Op) -> Result<Shape> {
let asking = Asking {
every: self.every,
calendar: self.calendar.as_ref().map(|(unit, zone)| (*unit, zone.as_str())),
by: self.by.as_deref(),
without: self.without.as_deref(),
name: self.name.as_deref(),
estimate: self.estimate,
};
Shape::of(op, asking)
}
fn plain(&self, call: &str) -> Result<()> {
let asks = self.every.is_some() || self.calendar.is_some() || self.by.is_some() || self.without.is_some();
if asks || self.estimate {
return Err(Error::invalid(format!(
"`every`, `calendar`, `by`, `without` and `estimate` are an aggregate's: {call} takes none"
)));
}
Ok(())
}
fn unpaged(&self, call: &str) -> Result<()> {
if self.limit.is_some() || self.after.is_some() {
return Err(Error::invalid(format!(
"`limit` and `after` are a read's and an aggregate's: {call} takes neither"
)));
}
Ok(())
}
pub(super) fn paged(&self, op: Option<Op>) -> Result<(Asked, Option<Paging>)> {
let mut asked = self.asked()?;
let Some(limit) = self.limit else {
if self.after.is_some() {
return Err(Error::invalid("`after` goes on from a page: a call takes it with `limit`"));
}
return Ok((asked, None));
};
if limit == 0 || limit > MOST {
return Err(Error::invalid(format!("a page of 1 to {MOST} samples or buckets, not {limit}")));
}
let query = self.digest(&asked, op);
let Some(after) = &self.after else { return Ok((asked, Some(Paging { limit, query, from: Start::First }))) };
let cursor = Cursor::read(after)?;
if cursor.query != query {
return Err(Error::invalid(format!("after {after:?}: a page's next of another query")));
}
(asked.from, asked.to, asked.now) = (cursor.from, cursor.to, cursor.now);
Ok((asked, Some(Paging { limit, query, from: cursor.start })))
}
fn digest(&self, asked: &Asked, op: Option<Op>) -> String {
let (from, to) = (self.from.map(unix_millis), self.to.map(unix_millis));
let mut given = format!("{:?}~{from:?}~{to:?}~{op:?}~{:?}~{:?}", self.since, self.every, self.calendar);
given.push_str(&format!("~{:?}~{:?}~{}", self.by, self.without, self.estimate));
for (label, condition) in &asked.conditions {
given.push_str(&format!("~{label:?}={condition:?}"));
}
let hash = Sha256::digest(given.as_bytes());
hash[..8].iter().map(|byte| format!("{byte:02x}")).collect()
}
pub(super) fn asked(&self) -> Result<Asked> {
let now = self.engine.now();
let from = match (self.since, self.from) {
(Some(_), Some(_)) => {
return Err(Error::invalid("a query starts `since` before now or `from` a time, not both"));
}
(Some(span), None) => now.saturating_sub(crate::clock::millis(span)),
(None, Some(from)) => unix_millis(from),
(None, None) => i64::MIN,
};
let to = self.to.map_or(now.saturating_add(1).max(from), unix_millis);
if to < from {
return Err(Error::invalid("a query whose range ends before it starts"));
}
let mut conditions = Vec::with_capacity(self.conditions.len() + 1);
if let Some(name) = &self.name {
conditions.push((NAME.to_owned(), Condition::OneOf(vec![name.clone()])));
}
for (label, condition) in &self.conditions {
conditions.push((label.clone(), check(label, condition)?));
}
if !conditions.iter().any(|(_, condition)| !matches!(condition, Condition::NoneOf(_))) {
return Err(Error::invalid(
"a query finds its series by a name, or a label's value, list or prefix: `Not` alone would read every \
series",
));
}
if conditions.len() > MOST_LABELS {
return Err(Error::invalid(format!("a query of more than {MOST_LABELS} conditions")));
}
Ok(Asked { name: self.name.clone(), conditions, from, to, now })
}
}
fn check(label: &str, condition: &Condition) -> Result<Condition> {
let condition_of = || format!("label {label:?}");
if super::labels::is_own(label) {
return Err(Error::invalid(format!("{}: a name beginning with __ is the store's own", condition_of())));
}
if label.is_empty() || label.len() > MOST_NAME_BYTES {
return Err(Error::invalid(format!("{}: a name of 1 to {MOST_NAME_BYTES} bytes", condition_of())));
}
let checked = |values: &Vec<String>| -> Result<Vec<String>> {
if values.is_empty() || values.len() > MOST_VALUES {
return Err(Error::invalid(format!("{}: a condition lists 1 to {MOST_VALUES} values", condition_of())));
}
if values.iter().any(|value| value.len() > MOST_VALUE_BYTES) {
return Err(Error::invalid(format!("{}: a value of {MOST_VALUE_BYTES} bytes at most", condition_of())));
}
let mut values = values.clone();
values.sort_unstable();
values.dedup();
Ok(values)
};
Ok(match condition {
Condition::OneOf(values) => Condition::OneOf(checked(values)?),
Condition::NoneOf(values) => Condition::NoneOf(checked(values)?),
Condition::Prefix(prefix) if prefix.is_empty() || prefix.len() > MOST_VALUE_BYTES => {
return Err(Error::invalid(format!("{}: a prefix of 1 to {MOST_VALUE_BYTES} bytes", condition_of())));
}
Condition::Prefix(prefix) => Condition::Prefix(prefix.clone()),
})
}
#[cfg(test)]
#[path = "query_tests.rs"]
mod tests;