use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use super::{MetricKind, ascending};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Point {
pub timestamp: i64,
pub value: Value,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub labels: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub epoch: Option<String>,
}
impl Point {
#[must_use]
pub fn new(timestamp_ms: i64, value: impl Into<Value>) -> Self {
Self {
timestamp: timestamp_ms,
value: value.into(),
labels: BTreeMap::new(),
unit: None,
epoch: None,
}
}
#[must_use]
pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
self.unit = Some(unit.into());
self
}
#[must_use]
pub fn with_label(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.labels.insert(name.into(), value.into());
self
}
#[must_use]
pub fn with_epoch(mut self, epoch: impl Into<String>) -> Self {
self.epoch = Some(epoch.into());
self
}
#[must_use]
pub fn kind(&self) -> MetricKind {
self.value.kind()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "lowercase")]
pub enum Value {
Counter(u64),
Gauge(f64),
Text(String),
Boolean(bool),
Binary(Vec<u8>),
Histogram(Histogram),
}
impl Value {
#[must_use]
pub fn kind(&self) -> MetricKind {
match self {
Self::Counter(_) => MetricKind::Counter,
Self::Gauge(_) => MetricKind::Gauge,
Self::Text(_) => MetricKind::Text,
Self::Boolean(_) => MetricKind::Boolean,
Self::Binary(_) => MetricKind::Binary,
Self::Histogram(_) => MetricKind::Histogram,
}
}
}
impl From<u64> for Value {
fn from(v: u64) -> Self {
Self::Counter(v)
}
}
impl From<f64> for Value {
fn from(v: f64) -> Self {
Self::Gauge(v)
}
}
impl From<bool> for Value {
fn from(v: bool) -> Self {
Self::Boolean(v)
}
}
impl From<String> for Value {
fn from(v: String) -> Self {
Self::Text(v)
}
}
impl From<&str> for Value {
fn from(v: &str) -> Self {
Self::Text(v.to_owned())
}
}
impl From<Vec<u8>> for Value {
fn from(v: Vec<u8>) -> Self {
Self::Binary(v)
}
}
impl From<Histogram> for Value {
fn from(v: Histogram) -> Self {
Self::Histogram(v)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Histogram {
pub buckets: Vec<f64>,
pub counts: Vec<u64>,
pub count: u64,
pub sum: f64,
}
impl Histogram {
#[must_use]
pub fn new(bounds: &[f64]) -> Option<Self> {
let valid = !bounds.is_empty() && bounds.iter().all(|b| b.is_finite()) && ascending(bounds);
valid.then(|| Self {
buckets: bounds.to_vec(),
counts: vec![0; bounds.len() + 1],
count: 0,
sum: 0.0,
})
}
#[must_use]
pub fn bucket_of(&self, v: f64) -> usize {
self.buckets.partition_point(|b| *b < v)
}
pub fn observe(&mut self, v: f64) -> bool {
if !v.is_finite() {
return false;
}
let i = self.bucket_of(v);
let sum = self.sum + v;
let (Some(c), Some(n)) = (
self.counts.get(i).and_then(|c| c.checked_add(1)),
self.count.checked_add(1),
) else {
return false;
};
if !sum.is_finite() {
return false;
}
self.counts[i] = c;
self.count = n;
self.sum = sum;
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::authoring::Kind;
use crate::telemetry::{
BUCKETS, Conformance, Datum, Declaration, KIND, PUBLISHED, Payload, Problem, TypeView,
UNIT, check, declaration,
};
use serde_json::{Value as Json, json};
fn point_decl(annotations: &[(&str, Json)]) -> Declaration {
let ty = TypeView::Json {
name: crate::telemetry::POINT,
schema: PUBLISHED[1],
root: None,
};
let a = annotations
.iter()
.map(|(k, v)| ((*k).to_owned(), v.clone()))
.collect();
declaration(Kind::Stream, &a, Some(&ty), None)
}
fn conformance(d: &Declaration, datum: &Datum) -> Conformance {
check(
d,
&Payload::Decoded {
value: datum,
attachment: None,
},
)
.conformance
}
fn cbor(p: &Point) -> Vec<u8> {
let mut out = Vec::new();
ciborium::into_writer(p, &mut out).unwrap();
out
}
#[test]
fn a_point_is_the_schemas_on_the_wire() {
let p = Point::new(1_760_000_000_123, 42u64)
.with_unit("By")
.with_label("oid", "1.3.6")
.with_epoch("00000000000000aa");
assert_eq!(
serde_json::to_string(&p).unwrap(),
r#"{"timestamp":1760000000123,"value":{"type":"counter","value":42},"labels":{"oid":"1.3.6"},"unit":"By","epoch":"00000000000000aa"}"#
);
let bare = Point::new(5, Value::Gauge(-70.5));
assert_eq!(
serde_json::to_string(&bare).unwrap(),
r#"{"timestamp":5,"value":{"type":"gauge","value":-70.5}}"#,
"an empty member is left out"
);
for p in [
p,
bare,
Point::new(1, vec![0u8, 255]),
Point::new(1, true),
Point::new(1, "up"),
] {
let bytes = cbor(&p);
let item: ciborium::Value = ciborium::from_reader(bytes.as_slice()).unwrap();
let as_json: Json = item.deserialized().unwrap();
assert_eq!(as_json, serde_json::to_value(&p).unwrap(), "{p:?}");
let back: Point = ciborium::from_reader(bytes.as_slice()).unwrap();
assert_eq!(back, p);
let d = point_decl(&[]);
let datum = Datum::from_cbor_bytes(&bytes).unwrap();
assert_eq!(conformance(&d, &datum), Conformance::Conforms, "{p:?}");
let datum = Datum::from_json_bytes(&serde_json::to_vec(&p).unwrap()).unwrap();
assert_eq!(conformance(&d, &datum), Conformance::Conforms, "{p:?}");
}
let binary = serde_json::to_value(Point::new(1, vec![7u8])).unwrap();
assert_eq!(binary["value"], json!({"type": "binary", "value": [7]}));
}
#[test]
fn zensights_point_reads_as_one() {
let z = json!({"timestamp": 3, "source": "h1", "metric": "cpu/0", "value":
{"type": "gauge", "value": 1.5}, "labels": {"unit": "%"}});
let p: Point = serde_json::from_value(z).unwrap();
assert_eq!(p.value, Value::Gauge(1.5));
assert_eq!(p.unit, None, "a label named unit is context (§2.5)");
}
#[test]
fn a_histogram_observes_into_its_bounds_upper_inclusive() {
let mut h = Histogram::new(&[0.005, 0.01, 0.025]).unwrap();
for v in [0.001, 0.005, 0.007, 0.01, 0.02, 0.5, -3.0] {
assert!(h.observe(v));
}
assert_eq!(h.counts, vec![3, 2, 1, 1]);
assert_eq!(h.count, 7);
assert!((h.sum - (0.543 - 3.0)).abs() < 1e-12);
assert!(!h.observe(f64::NAN) && !h.observe(f64::INFINITY));
assert!(h.observe(f64::MAX));
assert!(!h.observe(f64::MAX), "no infinite sum");
assert_eq!(h.count, 8, "the refused observation counts nothing");
let d = point_decl(&[
(KIND, json!("histogram")),
(UNIT, json!("s")),
(BUCKETS, json!([0.005, 0.01, 0.025])),
]);
let p = Point::new(1, h.clone()).with_unit("s");
let datum = Datum::from_json_bytes(&serde_json::to_vec(&p).unwrap()).unwrap();
assert_eq!(conformance(&d, &datum), Conformance::Conforms);
let other = Point::new(1, Histogram::new(&[0.005, 0.01, 0.05]).unwrap());
let datum = Datum::from_json_bytes(&serde_json::to_vec(&other).unwrap()).unwrap();
assert_eq!(
conformance(&d, &datum),
Conformance::DoesNot(vec![Problem::BoundsDiffer])
);
assert_eq!(Histogram::new(&[]), None);
assert_eq!(Histogram::new(&[1.0, 1.0]), None);
assert_eq!(Histogram::new(&[1.0, f64::INFINITY]), None);
let mut full = Histogram::new(&[1.0]).unwrap();
full.counts[0] = u64::MAX;
full.count = u64::MAX;
assert!(!full.observe(0.5), "a count past 2^64-1 is refused");
assert_eq!(full.counts[0], u64::MAX);
}
}