use async_trait::async_trait;
use awp_types::Measurement;
use chrono::{DateTime, Datelike as _, Duration, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::error::{KernelError, Result};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct KpiSample {
pub site: Uuid,
pub kpi: String,
pub at: DateTime<Utc>,
pub value: f64,
pub source: String,
}
impl KpiSample {
pub fn new(
site: Uuid,
kpi: impl Into<String>,
at: DateTime<Utc>,
value: f64,
source: impl Into<String>,
) -> Self {
Self { site, kpi: kpi.into(), at, value, source: source.into() }
}
pub fn validate(&self) -> Result<()> {
if self.kpi.trim().is_empty() {
return Err(KernelError::Config { reason: "a KPI sample needs the KPI's id".into() });
}
if !self.value.is_finite() {
return Err(KernelError::Config {
reason: format!(
"KPI {} measured {} at {}; a sample is a finite number, so fix the source",
self.kpi, self.value, self.at
),
});
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum KpiPeriod {
Day,
Week,
}
impl KpiPeriod {
pub fn start(self, day: NaiveDate) -> NaiveDate {
period_start(self, day)
}
pub fn days(self) -> i64 {
match self {
Self::Day => 1,
Self::Week => 7,
}
}
}
pub fn period_start(period: KpiPeriod, day: NaiveDate) -> NaiveDate {
match period {
KpiPeriod::Day => day,
KpiPeriod::Week => day - Duration::days(i64::from(day.weekday().num_days_from_monday())),
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct KpiAggregate {
pub kpi: String,
pub period: KpiPeriod,
pub start: NaiveDate,
pub count: u64,
pub sum: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last: Option<f64>,
}
impl KpiAggregate {
pub fn mean(&self) -> Option<f64> {
(self.count > 0).then(|| self.sum / self.count as f64)
}
}
pub fn aggregate(
samples: &[KpiSample],
period: KpiPeriod,
from: NaiveDate,
to_inclusive: NaiveDate,
) -> Vec<KpiAggregate> {
let kpi = samples.first().map(|sample| sample.kpi.clone()).unwrap_or_default();
let (first, last) = (period_start(period, from), period_start(period, to_inclusive));
if last < first {
return Vec::new();
}
let len = ((last - first).num_days() / period.days() + 1) as usize;
let mut buckets: Vec<KpiAggregate> = (0..len)
.map(|index| KpiAggregate {
kpi: kpi.clone(),
period,
start: first + Duration::days(index as i64 * period.days()),
count: 0,
sum: 0.0,
min: None,
max: None,
last: None,
})
.collect();
let mut ordered: Vec<&KpiSample> = samples.iter().filter(|sample| sample.kpi == kpi).collect();
ordered.sort_by_key(|sample| sample.at);
for sample in ordered {
let start = period_start(period, sample.at.date_naive());
if start < first || start > last {
continue;
}
let bucket = &mut buckets[((start - first).num_days() / period.days()) as usize];
bucket.count += 1;
bucket.sum += sample.value;
bucket.min = Some(bucket.min.map_or(sample.value, |min| min.min(sample.value)));
bucket.max = Some(bucket.max.map_or(sample.value, |max| max.max(sample.value)));
bucket.last = Some(sample.value);
}
buckets
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct KpiState {
pub site: Uuid,
pub kpi: String,
pub measuring_since: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub baseline: Option<Measurement>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_read: Option<DateTime<Utc>>,
}
impl KpiState {
pub fn new(site: Uuid, kpi: impl Into<String>, since: DateTime<Utc>) -> Self {
Self { site, kpi: kpi.into(), measuring_since: since, baseline: None, last_read: None }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct GuardrailState {
pub site: Uuid,
pub guardrail: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub breached_since: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_value: Option<f64>,
pub checked_at: DateTime<Utc>,
}
impl GuardrailState {
pub fn new(site: Uuid, guardrail: impl Into<String>, at: DateTime<Utc>) -> Self {
Self {
site,
guardrail: guardrail.into(),
breached_since: None,
last_value: None,
checked_at: at,
}
}
}
#[async_trait]
pub trait KpiStore: Send + Sync {
async fn record(&self, sample: KpiSample) -> Result<bool>;
async fn samples(
&self,
site: Uuid,
kpi: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<Vec<KpiSample>>;
async fn state(&self, site: Uuid, kpi: &str) -> Result<Option<KpiState>>;
async fn put_state(&self, state: KpiState) -> Result<()>;
async fn guardrail(&self, site: Uuid, guardrail: &str) -> Result<Option<GuardrailState>>;
async fn put_guardrail(&self, state: GuardrailState) -> Result<()>;
async fn aggregates(
&self,
site: Uuid,
kpi: &str,
period: KpiPeriod,
from: NaiveDate,
to_inclusive: NaiveDate,
) -> Result<Vec<KpiAggregate>> {
let first = period_start(period, from);
let end = period_start(period, to_inclusive) + Duration::days(period.days());
let midnight = |day: NaiveDate| day.and_time(chrono::NaiveTime::MIN).and_utc();
let samples = self.samples(site, kpi, midnight(first), midnight(end)).await?;
let mut series = aggregate(&samples, period, from, to_inclusive);
for bucket in &mut series {
bucket.kpi = kpi.to_string();
}
Ok(series)
}
}