#![deny(missing_docs)]
use std::collections::BTreeMap;
pub type Timestamp = i64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
Power,
Energy,
Counter,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Sample {
pub metric: String,
pub at: Timestamp,
pub value: f64,
pub kind: Kind,
}
impl Sample {
#[must_use]
pub fn new(metric: impl Into<String>, at: Timestamp, value: f64, kind: Kind) -> Option<Self> {
if value.is_finite() {
Some(Self {
metric: metric.into(),
at,
value,
kind,
})
} else {
None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Duration {
seconds: u64,
}
impl Duration {
#[must_use]
pub fn seconds(seconds: u64) -> Option<Self> {
(seconds > 0).then_some(Self { seconds })
}
#[must_use]
pub const fn as_secs(&self) -> u64 {
self.seconds
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Interval {
pub start: Timestamp,
pub length: Duration,
}
impl Interval {
#[must_use]
pub const fn end(&self) -> Timestamp {
self.start.saturating_add(self.length.as_secs() as i64)
}
#[must_use]
pub const fn contains(&self, at: Timestamp) -> bool {
at >= self.start && at < self.end()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rules {
pub min_coverage_pct: u8,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Reading {
Value {
value: f64,
coverage_pct: u8,
duplicates: u32,
},
Missing {
coverage_pct: u8,
},
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum AlignError {
#[error("sample of {metric} at {at} is not in the interval being aligned")]
SampleOutsideInterval {
metric: String,
at: Timestamp,
},
#[error("counter {metric} went backwards inside one interval")]
CounterWentBackwards {
metric: String,
},
}
pub fn align(
samples: &[Sample],
interval: Interval,
rules: &Rules,
) -> Result<BTreeMap<String, Reading>, AlignError> {
for sample in samples {
if !interval.contains(sample.at) {
return Err(AlignError::SampleOutsideInterval {
metric: sample.metric.clone(),
at: sample.at,
});
}
}
let mut points: BTreeMap<(String, Timestamp), f64> = BTreeMap::new();
let mut kind_by_metric: BTreeMap<String, Kind> = BTreeMap::new();
let mut brought: BTreeMap<String, u32> = BTreeMap::new();
for sample in samples {
points.insert((sample.metric.clone(), sample.at), sample.value);
kind_by_metric.insert(sample.metric.clone(), sample.kind);
*brought.entry(sample.metric.clone()).or_default() += 1;
}
let mut series: BTreeMap<String, Vec<(Timestamp, f64)>> = BTreeMap::new();
for ((metric, at), value) in points {
series.entry(metric).or_default().push((at, value));
}
let mut readings = BTreeMap::new();
for (metric, points) in series {
let duplicates = brought[&metric] - points.len() as u32;
let kind = kind_by_metric[&metric];
let reading = reading_of(
&metric,
kind,
&points,
interval,
rules.min_coverage_pct,
duplicates,
)?;
readings.insert(metric, reading);
}
Ok(readings)
}
fn reading_of(
metric: &str,
kind: Kind,
points: &[(Timestamp, f64)],
interval: Interval,
min_coverage_pct: u8,
duplicates: u32,
) -> Result<Reading, AlignError> {
let coverage_pct = coverage_pct_of(points, kind, interval);
if coverage_pct == 0 || coverage_pct < min_coverage_pct {
return Ok(Reading::Missing { coverage_pct });
}
let value = match kind {
Kind::Energy => points.iter().map(|&(_, value)| value).sum(),
Kind::Power => time_weighted_mean(points),
Kind::Counter => {
let first = points[0].1;
let last = points[points.len() - 1].1;
if last < first {
return Err(AlignError::CounterWentBackwards {
metric: metric.to_owned(),
});
}
last - first
}
};
Ok(Reading::Value {
value,
coverage_pct,
duplicates,
})
}
fn coverage_pct_of(points: &[(Timestamp, f64)], kind: Kind, interval: Interval) -> u8 {
match kind {
Kind::Energy => 100,
Kind::Power | Kind::Counter => match (points.first(), points.last()) {
(Some(&(first, _)), Some(&(last, _))) => {
let span = (last - first) as u128;
let length = interval.length.as_secs() as u128;
(span * 100 / length) as u8
}
_ => 0,
},
}
}
fn time_weighted_mean(points: &[(Timestamp, f64)]) -> f64 {
let weighted: f64 = points
.windows(2)
.map(|pair| pair[0].1 * (pair[1].0 - pair[0].0) as f64)
.sum();
let span = (points[points.len() - 1].0 - points[0].0) as f64;
weighted / span
}
#[cfg(test)]
mod tests {
use super::*;
const START: Timestamp = 1_772_949_600;
fn duration(secs: u64) -> Duration {
Duration::seconds(secs).expect("a positive length")
}
fn sample(metric: &str, offset: i64, value: f64, kind: Kind) -> Sample {
Sample::new(metric, START + offset, value, kind).expect("a finite value")
}
#[test]
fn a_sample_refuses_a_non_finite_value() {
assert!(Sample::new("hall.kw", START, f64::NAN, Kind::Power).is_none());
assert!(Sample::new("hall.kw", START, f64::INFINITY, Kind::Power).is_none());
assert!(sample("hall.kw", 0, 1.0, Kind::Power).value == 1.0);
}
#[test]
fn a_duration_refuses_zero() {
assert!(Duration::seconds(0).is_none());
assert_eq!(duration(900).as_secs(), 900);
}
#[test]
fn an_interval_contains_its_start_but_not_its_end() {
let interval = Interval {
start: START,
length: duration(900),
};
assert!(interval.contains(START));
assert!(interval.contains(START + 899));
assert!(!interval.contains(START + 900));
assert_eq!(interval.end(), START + 900);
}
#[test]
fn an_interval_end_saturates() {
let interval = Interval {
start: i64::MAX - 10,
length: duration(900),
};
assert_eq!(interval.end(), i64::MAX);
}
#[test]
fn empty_input_aligns_to_an_empty_map() {
let interval = Interval {
start: START,
length: duration(900),
};
let aligned = align(
&[],
interval,
&Rules {
min_coverage_pct: 80,
},
)
.expect("empty aligns");
assert!(aligned.is_empty());
}
}