use std::time::{Duration, SystemTime};
use super::aggregate::{Aggregate, Asking, Op, Shape};
use super::codec::Point;
use super::labels::{BIN, Kept};
use super::matching::Found;
use super::query::Asked;
use super::series::{Kind, Labels, Series};
use super::snapshot::Window;
use crate::calendar::Calendar;
use crate::{Error, Result, unix_millis};
impl Series {
pub fn query(&self) -> SeriesQuery<'_> {
query(std::slice::from_ref(self))
}
}
pub fn query(series: &[Series]) -> SeriesQuery<'_> {
SeriesQuery { series, from: None, to: None, every: None, calendar: None, estimate: false, skip_nan: false }
}
#[derive(Clone, Debug)]
#[must_use = "a query answers by aggregate"]
pub struct SeriesQuery<'a> {
series: &'a [Series],
from: Option<SystemTime>,
to: Option<SystemTime>,
every: Option<Duration>,
calendar: Option<(Calendar, String)>,
estimate: bool,
skip_nan: bool,
}
impl SeriesQuery<'_> {
pub fn from(mut self, from: SystemTime) -> Self {
self.from = Some(from);
self
}
pub fn to(mut self, to: SystemTime) -> Self {
self.to = Some(to);
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 estimate(mut self) -> Self {
self.estimate = true;
self
}
pub fn skip_nan(mut self) -> Self {
self.skip_nan = true;
self
}
pub fn aggregate(&self, op: Op) -> Result<Aggregate> {
let calendar = self.calendar.as_ref().map(|(unit, zone)| (*unit, zone.as_str()));
let (estimate, skip_nan) = (self.estimate, self.skip_nan);
let asking = Asking { every: self.every, calendar, estimate, skip_nan, ..Asking::default() };
let shape = Shape::of(op, asking)?;
let (name, kind) = self.name_and_kind()?;
let mut members = self.series.iter().enumerate().map(member).collect::<Result<Vec<_>>>()?;
let asked = self.asked(&members)?;
let window = Window { from: asked.from, to: asked.to, cutoff: i64::MIN };
for member in &members {
shape.check(&member.found)?;
}
let labels = shared_labels(self.series, op, kind);
let buckets = super::counting::count_held(&shape, &mut members, window, &asked)?;
Ok(Aggregate { name, labels, buckets, more: false })
}
fn name_and_kind(&self) -> Result<(String, Kind)> {
let first = self.series.first().ok_or_else(|| Error::invalid("an aggregate of no series"))?;
if let Some(other) = self.series.iter().find(|series| series.name != first.name || series.kind != first.kind) {
let (first_kind, other_kind) = (first.kind, other.kind);
return Err(Error::invalid(format!(
"a group's series share a name and a kind: {first}, a {first_kind}, and {other}, a {other_kind}"
)));
}
Ok((first.name.clone(), first.kind))
}
fn asked(&self, members: &[Held]) -> Result<Asked> {
let times = members.iter().flat_map(|member| member.points.iter().map(|point| point.at));
let (first, last) = times.fold((i64::MAX, i64::MIN), |(first, last), at| (first.min(at), last.max(at)));
let from = self.from.map_or(first, unix_millis);
let to = self.to.map_or_else(|| last.saturating_add(1).max(from), unix_millis);
if to < from {
return Err(Error::invalid("a query whose range ends before it starts"));
}
let now = unix_millis(SystemTime::now());
Ok(Asked { name: None, conditions: Vec::new(), from, to, now })
}
}
pub(super) struct Held {
pub(super) found: Found,
pub(super) points: Vec<Point>,
}
fn member((at, series): (usize, &Series)) -> Result<Held> {
let kept = Kept::held(&series.name, &series.labels).map_err(|error| error.within(series))?;
let mut points: Vec<Point> =
series.samples.iter().map(|sample| Point { at: unix_millis(sample.at), value: sample.value }).collect();
points.sort_by_key(|point| point.at);
points.dedup_by(|later, earlier| later.at == earlier.at && later.value.to_bits() == earlier.value.to_bits());
if let Some(pair) = points.windows(2).find(|pair| pair[0].at == pair[1].at) {
let at = super::timestamp::rfc3339(pair[0].at);
return Err(
Error::invalid(format!("two samples at {at}, one millisecond, which a series has one of")).within(series)
);
}
Ok(Held { found: Found { id: at as i64, kind: series.kind, kept }, points })
}
fn shared_labels(series: &[Series], op: Op, kind: Kind) -> Labels {
let mut shared = series.first().map(|series| series.labels.clone()).unwrap_or_default();
shared.retain(|label, value| series.iter().all(|series| series.labels.get(label) == Some(value)));
if matches!(op, Op::Percentile(_)) && kind == Kind::Histogram {
shared.remove("le");
shared.remove(BIN);
}
shared
}
#[cfg(test)]
#[path = "held_tests.rs"]
mod tests;