adk_kernel/charter/kpi.rs
1//! KPI measurements and their daily and weekly aggregates (spec 3.5 §7.11).
2
3use async_trait::async_trait;
4use awp_types::Measurement;
5use chrono::{DateTime, Datelike as _, Duration, NaiveDate, Utc};
6use serde::{Deserialize, Serialize};
7use uuid::Uuid;
8
9use crate::error::{KernelError, Result};
10
11/// One measurement of a KPI, as the tracker read it from the KPI's source (spec 3.5 §7.11).
12///
13/// A KPI has at most one sample per instant: [`KpiStore::record`] keeps the first.
14///
15/// # Example
16///
17/// ```rust
18/// use adk_kernel::charter::KpiSample;
19///
20/// let sample = KpiSample::new(uuid::Uuid::nil(), "leads", chrono::Utc::now(), 4.0, "commerce");
21/// assert_eq!(serde_json::to_value(&sample).unwrap()["kpi"], "leads");
22/// ```
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25#[non_exhaustive]
26pub struct KpiSample {
27 /// The site.
28 pub site: Uuid,
29 /// The KPI's id in the charter.
30 pub kpi: String,
31 /// When it was measured.
32 pub at: DateTime<Utc>,
33 /// The value.
34 pub value: f64,
35 /// The source it came from (the KPI's `SourceRef`).
36 pub source: String,
37}
38
39impl KpiSample {
40 /// A sample of `kpi` on `site` measured at `at` from `source`.
41 pub fn new(
42 site: Uuid,
43 kpi: impl Into<String>,
44 at: DateTime<Utc>,
45 value: f64,
46 source: impl Into<String>,
47 ) -> Self {
48 Self { site, kpi: kpi.into(), at, value, source: source.into() }
49 }
50
51 /// Refuses a sample a store must not keep: an empty KPI id or a value that is not a
52 /// finite number.
53 ///
54 /// # Errors
55 ///
56 /// Returns [`KernelError::Config`] naming the fault.
57 pub fn validate(&self) -> Result<()> {
58 if self.kpi.trim().is_empty() {
59 return Err(KernelError::Config { reason: "a KPI sample needs the KPI's id".into() });
60 }
61 if !self.value.is_finite() {
62 return Err(KernelError::Config {
63 reason: format!(
64 "KPI {} measured {} at {}; a sample is a finite number, so fix the source",
65 self.kpi, self.value, self.at
66 ),
67 });
68 }
69 Ok(())
70 }
71}
72
73/// The length of an aggregate's period (spec 3.5 §7.11): a UTC day, or an ISO week from
74/// Monday.
75///
76/// # Example
77///
78/// ```rust
79/// use chrono::NaiveDate;
80/// use adk_kernel::charter::KpiPeriod;
81///
82/// let thursday = NaiveDate::from_ymd_opt(2026, 10, 22).unwrap();
83/// assert_eq!(KpiPeriod::Week.start(thursday), NaiveDate::from_ymd_opt(2026, 10, 19).unwrap());
84/// assert_eq!(KpiPeriod::Day.start(thursday), thursday);
85/// ```
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88#[non_exhaustive]
89pub enum KpiPeriod {
90 /// A UTC day.
91 Day,
92 /// An ISO week, Monday to Sunday, in UTC.
93 Week,
94}
95
96impl KpiPeriod {
97 /// The first day of the period holding `day`.
98 pub fn start(self, day: NaiveDate) -> NaiveDate {
99 period_start(self, day)
100 }
101
102 /// The number of days in a period.
103 pub fn days(self) -> i64 {
104 match self {
105 Self::Day => 1,
106 Self::Week => 7,
107 }
108 }
109}
110
111/// The first day of the `period` holding `day` (spec 3.5 §7.11): `day` itself, or the Monday
112/// of its ISO week.
113pub fn period_start(period: KpiPeriod, day: NaiveDate) -> NaiveDate {
114 match period {
115 KpiPeriod::Day => day,
116 KpiPeriod::Week => day - Duration::days(i64::from(day.weekday().num_days_from_monday())),
117 }
118}
119
120/// A KPI's samples over one period (spec 3.5 §7.11). A period without samples has
121/// `count` 0 and no `min`, `max` or `last`, so a series has no gaps.
122///
123/// # Example
124///
125/// ```rust
126/// use chrono::{NaiveDate, TimeZone, Utc};
127/// use adk_kernel::charter::{KpiPeriod, KpiSample, aggregate};
128///
129/// let site = uuid::Uuid::nil();
130/// let at = |d, h| Utc.with_ymd_and_hms(2026, 10, d, h, 0, 0).unwrap();
131/// let samples = [KpiSample::new(site, "leads", at(20, 9), 3.0, "commerce"), KpiSample::new(site, "leads", at(20, 18), 5.0, "commerce")];
132/// let days = aggregate(&samples, KpiPeriod::Day, NaiveDate::from_ymd_opt(2026, 10, 19).unwrap(), NaiveDate::from_ymd_opt(2026, 10, 21).unwrap());
133/// assert_eq!(days.iter().map(|d| d.count).collect::<Vec<_>>(), [0, 2, 0]);
134/// assert_eq!(days[1].mean(), Some(4.0));
135/// assert_eq!(days[1].last, Some(5.0));
136/// ```
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase")]
139#[non_exhaustive]
140pub struct KpiAggregate {
141 /// The KPI.
142 pub kpi: String,
143 /// The period's length.
144 pub period: KpiPeriod,
145 /// The period's first day.
146 pub start: NaiveDate,
147 /// How many samples it holds.
148 pub count: u64,
149 /// Their sum.
150 pub sum: f64,
151 /// The smallest.
152 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub min: Option<f64>,
154 /// The largest.
155 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub max: Option<f64>,
157 /// The latest.
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub last: Option<f64>,
160}
161
162impl KpiAggregate {
163 /// The mean of the period's samples, `None` for an empty period.
164 pub fn mean(&self) -> Option<f64> {
165 (self.count > 0).then(|| self.sum / self.count as f64)
166 }
167}
168
169/// The aggregates of `samples` per `period` (spec 3.5 §7.11), one for every period from the
170/// one holding `from` through the one holding `to_inclusive`, in order, empty periods
171/// included; samples of other KPIs than the first sample's, and samples outside those
172/// periods, are left out.
173pub fn aggregate(
174 samples: &[KpiSample],
175 period: KpiPeriod,
176 from: NaiveDate,
177 to_inclusive: NaiveDate,
178) -> Vec<KpiAggregate> {
179 let kpi = samples.first().map(|sample| sample.kpi.clone()).unwrap_or_default();
180 let (first, last) = (period_start(period, from), period_start(period, to_inclusive));
181 if last < first {
182 return Vec::new();
183 }
184 let len = ((last - first).num_days() / period.days() + 1) as usize;
185 let mut buckets: Vec<KpiAggregate> = (0..len)
186 .map(|index| KpiAggregate {
187 kpi: kpi.clone(),
188 period,
189 start: first + Duration::days(index as i64 * period.days()),
190 count: 0,
191 sum: 0.0,
192 min: None,
193 max: None,
194 last: None,
195 })
196 .collect();
197 let mut ordered: Vec<&KpiSample> = samples.iter().filter(|sample| sample.kpi == kpi).collect();
198 ordered.sort_by_key(|sample| sample.at);
199 for sample in ordered {
200 let start = period_start(period, sample.at.date_naive());
201 if start < first || start > last {
202 continue;
203 }
204 let bucket = &mut buckets[((start - first).num_days() / period.days()) as usize];
205 bucket.count += 1;
206 bucket.sum += sample.value;
207 bucket.min = Some(bucket.min.map_or(sample.value, |min| min.min(sample.value)));
208 bucket.max = Some(bucket.max.map_or(sample.value, |max| max.max(sample.value)));
209 bucket.last = Some(sample.value);
210 }
211 buckets
212}
213
214/// What the tracker knows about one KPI between ticks (spec 3.5 §7.11, A-I14): when its
215/// measure-only period began, the baseline it locked when the period ended, and when it
216/// last read the source.
217///
218/// # Example
219///
220/// ```rust
221/// use adk_kernel::charter::KpiState;
222///
223/// let state = KpiState::new(uuid::Uuid::nil(), "leads", chrono::Utc::now());
224/// assert!(state.baseline.is_none());
225/// ```
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227#[serde(rename_all = "camelCase")]
228#[non_exhaustive]
229pub struct KpiState {
230 /// The site.
231 pub site: Uuid,
232 /// The KPI.
233 pub kpi: String,
234 /// When its measure-only period began: the first tick that saw the KPI.
235 pub measuring_since: DateTime<Utc>,
236 /// The baseline the tracker locked when the measure-only period ended.
237 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub baseline: Option<Measurement>,
239 /// When the tracker last read the KPI's source.
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub last_read: Option<DateTime<Utc>>,
242}
243
244impl KpiState {
245 /// A KPI first seen at `since`, with no baseline and no reading.
246 pub fn new(site: Uuid, kpi: impl Into<String>, since: DateTime<Utc>) -> Self {
247 Self { site, kpi: kpi.into(), measuring_since: since, baseline: None, last_read: None }
248 }
249}
250
251/// Whether a guardrail is breached, and since when (spec 3.5 §7.11, A-I15): a breach pauses
252/// and demotes its jobs once, when it begins, and a later breach after a recovery does so
253/// again.
254///
255/// # Example
256///
257/// ```rust
258/// use adk_kernel::charter::GuardrailState;
259///
260/// let state = GuardrailState::new(uuid::Uuid::nil(), "unsubscribes", chrono::Utc::now());
261/// assert!(state.breached_since.is_none());
262/// ```
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265#[non_exhaustive]
266pub struct GuardrailState {
267 /// The site.
268 pub site: Uuid,
269 /// The guardrail.
270 pub guardrail: String,
271 /// When the current breach began; `None` while the metric is within the threshold.
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub breached_since: Option<DateTime<Utc>>,
274 /// The metric's value at the last check.
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub last_value: Option<f64>,
277 /// When it was last checked.
278 pub checked_at: DateTime<Utc>,
279}
280
281impl GuardrailState {
282 /// A guardrail checked at `at` and found within its threshold.
283 pub fn new(site: Uuid, guardrail: impl Into<String>, at: DateTime<Utc>) -> Self {
284 Self {
285 site,
286 guardrail: guardrail.into(),
287 breached_since: None,
288 last_value: None,
289 checked_at: at,
290 }
291 }
292}
293
294/// The KPI time series of every site and the tracker's state (spec 3.5 §7.11), on
295/// in-memory, SQLite, PostgreSQL and Redis.
296///
297/// # Example
298///
299/// ```rust
300/// use chrono::{NaiveDate, TimeZone, Utc};
301/// use adk_kernel::charter::{InMemoryKpiStore, KpiPeriod, KpiSample, KpiStore};
302///
303/// # #[tokio::main(flavor = "current_thread")]
304/// # async fn main() -> adk_kernel::Result<()> {
305/// let store = InMemoryKpiStore::new();
306/// let site = uuid::Uuid::nil();
307/// let at = Utc.with_ymd_and_hms(2026, 10, 20, 9, 0, 0).unwrap();
308/// assert!(store.record(KpiSample::new(site, "leads", at, 3.0, "commerce")).await?);
309/// assert!(!store.record(KpiSample::new(site, "leads", at, 9.0, "commerce")).await?, "one sample per instant");
310/// let day = NaiveDate::from_ymd_opt(2026, 10, 20).unwrap();
311/// let week = store.aggregates(site, "leads", KpiPeriod::Week, day, day).await?;
312/// assert_eq!((week.len(), week[0].sum), (1, 3.0));
313/// # Ok(())
314/// # }
315/// ```
316#[async_trait]
317pub trait KpiStore: Send + Sync {
318 /// Records `sample`; `false`, keeping the stored one, when the KPI already has a sample
319 /// at that instant (to the microsecond).
320 ///
321 /// # Errors
322 ///
323 /// Returns [`KernelError::Config`] for a sample [`KpiSample::validate`] refuses, or
324 /// [`KernelError::Store`] when the backend fails.
325 async fn record(&self, sample: KpiSample) -> Result<bool>;
326
327 /// The samples of `kpi` on `site` measured in `[from, to)`, oldest first.
328 ///
329 /// # Errors
330 ///
331 /// Returns [`KernelError::Store`] when the backend fails.
332 async fn samples(
333 &self,
334 site: Uuid,
335 kpi: &str,
336 from: DateTime<Utc>,
337 to: DateTime<Utc>,
338 ) -> Result<Vec<KpiSample>>;
339
340 /// The tracker's state of `kpi` on `site`, or `None`.
341 ///
342 /// # Errors
343 ///
344 /// Returns [`KernelError::Store`] when the backend fails.
345 async fn state(&self, site: Uuid, kpi: &str) -> Result<Option<KpiState>>;
346
347 /// Writes the tracker's state of one KPI over the stored one.
348 ///
349 /// # Errors
350 ///
351 /// Returns [`KernelError::Store`] when the backend fails.
352 async fn put_state(&self, state: KpiState) -> Result<()>;
353
354 /// The state of `guardrail` on `site`, or `None`.
355 ///
356 /// # Errors
357 ///
358 /// Returns [`KernelError::Store`] when the backend fails.
359 async fn guardrail(&self, site: Uuid, guardrail: &str) -> Result<Option<GuardrailState>>;
360
361 /// Writes the state of one guardrail over the stored one.
362 ///
363 /// # Errors
364 ///
365 /// Returns [`KernelError::Store`] when the backend fails.
366 async fn put_guardrail(&self, state: GuardrailState) -> Result<()>;
367
368 /// The aggregates of `kpi` per `period` from the period holding `from` through the one
369 /// holding `to_inclusive`: one per period, in order, empty periods included
370 /// ([`aggregate`]).
371 ///
372 /// # Errors
373 ///
374 /// Returns [`KernelError::Store`] when the backend fails.
375 async fn aggregates(
376 &self,
377 site: Uuid,
378 kpi: &str,
379 period: KpiPeriod,
380 from: NaiveDate,
381 to_inclusive: NaiveDate,
382 ) -> Result<Vec<KpiAggregate>> {
383 let first = period_start(period, from);
384 let end = period_start(period, to_inclusive) + Duration::days(period.days());
385 let midnight = |day: NaiveDate| day.and_time(chrono::NaiveTime::MIN).and_utc();
386 let samples = self.samples(site, kpi, midnight(first), midnight(end)).await?;
387 let mut series = aggregate(&samples, period, from, to_inclusive);
388 for bucket in &mut series {
389 bucket.kpi = kpi.to_string();
390 }
391 Ok(series)
392 }
393}