use std::collections::BTreeMap;
use std::fmt;
use serde_json::Value;
use crate::authoring::Kind;
use crate::contract::{Body, Contract, Resource};
use crate::schema::{Artifact, ArtifactData, TypeId};
pub mod decode;
pub mod frames;
pub mod wire;
pub const PROFILE: &str = "telemetry.v1";
pub const PROFILE_V2: &str = "telemetry.v2";
pub const NAME: &str = "telemetry";
pub const KIND: &str = "telemetry.kind";
pub const UNIT: &str = "telemetry.unit";
pub const BUCKETS: &str = "telemetry.buckets";
pub const SEMANTIC: &str = "telemetry.semantic";
pub const SERIES: &str = "telemetry.series";
pub const VOCABULARY: &[&str] = &["kind", "unit", "buckets", "semantic"];
pub const VOCABULARY_V2: &[&str] = &["kind", "unit", "buckets", "semantic", "series"];
#[must_use]
pub fn uses_v2(c: &Contract) -> bool {
c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
}
pub const FULL_WIDTH: u32 = 64;
pub const SCHEMA_STEM: &str = "telemetry.v1";
pub const POINT: &str = "telemetry.v1.Point";
pub const VALUE: &str = "telemetry.v1.Value";
pub const HISTOGRAM: &str = "telemetry.v1.Histogram";
pub const EPOCH: &str = "telemetry.v1.Epoch";
pub const PUBLISHED: &[&str] = &[
"sha256:3d6276dd302873ca5938013a44d460267971123fd25500f189e30be718f9dc1e",
"sha256:715ce537b2150beb3863f0e5cd356281357f7ec56d93625ee64e14f0045629e9",
];
pub const MAX_UNIT: usize = 64;
pub const MAX_EPOCH: usize = 64;
#[must_use]
pub fn is_published(id: &str) -> bool {
PUBLISHED.contains(&id)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MetricKind {
Counter,
Gauge,
Histogram,
Text,
Boolean,
Binary,
}
impl MetricKind {
pub const ALL: [Self; 6] = [
Self::Counter,
Self::Gauge,
Self::Histogram,
Self::Text,
Self::Boolean,
Self::Binary,
];
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Counter => "counter",
Self::Gauge => "gauge",
Self::Histogram => "histogram",
Self::Text => "text",
Self::Boolean => "boolean",
Self::Binary => "binary",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|k| k.as_str() == s)
}
#[must_use]
pub fn is_cumulative(self) -> bool {
matches!(self, Self::Counter | Self::Histogram)
}
}
impl fmt::Display for MetricKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Semantic {
Temperature,
Power,
Bytes,
Duration,
Ratio,
Count,
Identity,
State,
}
impl Semantic {
pub const ALL: [Self; 8] = [
Self::Temperature,
Self::Power,
Self::Bytes,
Self::Duration,
Self::Ratio,
Self::Count,
Self::Identity,
Self::State,
];
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Temperature => "temperature",
Self::Power => "power",
Self::Bytes => "bytes",
Self::Duration => "duration",
Self::Ratio => "ratio",
Self::Count => "count",
Self::Identity => "identity",
Self::State => "state",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|k| k.as_str() == s)
}
}
#[must_use]
pub fn is_unit(s: &str) -> bool {
(1..=MAX_UNIT).contains(&s.len()) && s.bytes().all(|b| (0x21..=0x7e).contains(&b))
}
#[must_use]
pub fn is_epoch(s: &str) -> bool {
(1..=MAX_EPOCH).contains(&s.chars().count())
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TypeView<'a> {
Json {
name: &'a str,
schema: &'a str,
root: Option<&'a Value>,
},
Raw,
Protobuf,
Packed,
}
impl TypeView<'_> {
#[must_use]
pub fn is_profiles(&self, type_name: &str) -> bool {
matches!(self, Self::Json { name, schema, .. } if *name == type_name && is_published(schema))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Carrier {
Point,
Bare,
}
impl Carrier {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Point => "point",
Self::Bare => "bare",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EpochIn {
Point,
Attachment,
}
impl EpochIn {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Point => "point",
Self::Attachment => "attachment",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Declared {
pub carrier: Carrier,
pub kind: Option<MetricKind>,
pub unit: Option<String>,
pub buckets: Option<Vec<f64>>,
pub semantic: Option<Semantic>,
pub epoch: Option<EpochIn>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Invalid {
KindValue,
UnitValue,
BucketsValue,
SemanticValue,
KindMissing,
BucketsWithoutHistogram,
HistogramWithoutBuckets,
NotACarrier,
}
impl Invalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::KindValue => "kind_value",
Self::UnitValue => "unit_value",
Self::BucketsValue => "buckets_value",
Self::SemanticValue => "semantic_value",
Self::KindMissing => "kind_missing",
Self::BucketsWithoutHistogram => "buckets_without_histogram",
Self::HistogramWithoutBuckets => "histogram_without_buckets",
Self::NotACarrier => "not_a_carrier",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::KindValue => "telemetry.kind is not one of the six kinds",
Self::UnitValue => {
"telemetry.unit is not 1 to 64 printable ASCII characters (0x21 to 0x7E)"
}
Self::BucketsValue => {
"telemetry.buckets is not a non-empty array of finite numbers, strictly ascending"
}
Self::SemanticValue => "telemetry.semantic is not one of the eight semantics",
Self::KindMissing => "no telemetry.kind, and the type is not the profile's Point",
Self::BucketsWithoutHistogram => {
"telemetry.buckets on a resource whose declared kind is not histogram"
}
Self::HistogramWithoutBuckets => "a histogram without telemetry.buckets",
Self::NotACarrier => "the type cannot carry the declared kind",
}
}
}
impl fmt::Display for Invalid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Declaration {
Declared(Declared),
Invalid(Vec<Invalid>),
Ignored,
NotThisProfiles,
}
impl Declaration {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Declared(_) => "declared",
Self::Invalid(_) => "invalid",
Self::Ignored => "ignored",
Self::NotThisProfiles => "not_this_profiles",
}
}
#[must_use]
pub fn declared(&self) -> Option<&Declared> {
match self {
Self::Declared(d) => Some(d),
_ => None,
}
}
}
enum Read<T> {
Absent,
Valid(T),
Wrong,
}
impl<T> Read<T> {
fn of(v: Option<&Value>, f: impl FnOnce(&Value) -> Option<T>) -> Self {
match v {
None => Self::Absent,
Some(v) => f(v).map_or(Self::Wrong, Self::Valid),
}
}
fn is_wrong(&self) -> bool {
matches!(self, Self::Wrong)
}
fn valid(&self) -> Option<&T> {
match self {
Self::Valid(t) => Some(t),
_ => None,
}
}
}
fn read_buckets(v: &Value) -> Option<Vec<f64>> {
let a = v.as_array()?;
let b: Vec<f64> = a.iter().map(Value::as_f64).collect::<Option<_>>()?;
(!b.is_empty() && b.iter().all(|x| x.is_finite()) && ascending(&b)).then_some(b)
}
fn ascending(b: &[f64]) -> bool {
b.windows(2).all(|w| w[0] < w[1])
}
fn type_names(root: &Value) -> Vec<&str> {
let mut v: Vec<&str> = match root.get("type") {
Some(Value::String(s)) => vec![s.as_str()],
Some(Value::Array(a)) => {
let names: Option<Vec<&str>> = a.iter().map(Value::as_str).collect();
names.unwrap_or_default()
}
_ => Vec::new(),
};
v.sort_unstable();
v.dedup();
v
}
#[must_use]
pub fn carries(ty: &TypeView<'_>, kind: MetricKind) -> bool {
if ty.is_profiles(POINT) {
return true;
}
if ty.is_profiles(HISTOGRAM) {
return kind == MetricKind::Histogram;
}
match ty {
TypeView::Raw => kind == MetricKind::Binary,
TypeView::Protobuf | TypeView::Packed | TypeView::Json { root: None, .. } => false,
TypeView::Json {
root: Some(root), ..
} => {
let t = type_names(root);
match kind {
MetricKind::Counter => t == ["integer"],
MetricKind::Gauge => {
!t.is_empty() && t.iter().all(|n| matches!(*n, "integer" | "number"))
}
MetricKind::Boolean => t == ["boolean"],
MetricKind::Text => t == ["string"],
MetricKind::Histogram | MetricKind::Binary => false,
}
}
}
}
#[must_use]
pub fn declaration(
kind: Kind,
annotations: &BTreeMap<String, Value>,
ty: Option<&TypeView<'_>>,
attachment: Option<&TypeView<'_>>,
) -> Declaration {
let any_key = [KIND, UNIT, BUCKETS, SEMANTIC]
.iter()
.any(|k| annotations.contains_key(*k));
if matches!(kind, Kind::Event | Kind::Operation) {
return if any_key {
Declaration::Ignored
} else {
Declaration::NotThisProfiles
};
}
let point = ty.is_some_and(|t| t.is_profiles(POINT));
if !any_key && !point {
return Declaration::NotThisProfiles;
}
let k = Read::of(annotations.get(KIND), |v| {
v.as_str().and_then(MetricKind::parse)
});
let u = Read::of(annotations.get(UNIT), |v| {
v.as_str().filter(|s| is_unit(s)).map(str::to_owned)
});
let b = Read::of(annotations.get(BUCKETS), read_buckets);
let s = Read::of(annotations.get(SEMANTIC), |v| {
v.as_str().and_then(Semantic::parse)
});
let mut why = Vec::new();
for (wrong, r) in [
(k.is_wrong(), Invalid::KindValue),
(u.is_wrong(), Invalid::UnitValue),
(b.is_wrong(), Invalid::BucketsValue),
(s.is_wrong(), Invalid::SemanticValue),
] {
if wrong {
why.push(r);
}
}
if matches!(k, Read::Absent) && !point {
why.push(Invalid::KindMissing);
}
let histogram = matches!(k, Read::Valid(MetricKind::Histogram));
if matches!(b, Read::Valid(_)) && !k.is_wrong() && !histogram {
why.push(Invalid::BucketsWithoutHistogram);
}
if histogram && matches!(b, Read::Absent) {
why.push(Invalid::HistogramWithoutBuckets);
}
if let Some(declared) = k.valid()
&& !ty.is_some_and(|t| carries(t, *declared))
{
why.push(Invalid::NotACarrier);
}
if !why.is_empty() {
return Declaration::Invalid(why);
}
let kind = k.valid().copied();
let epoch = if point {
Some(EpochIn::Point)
} else if kind.is_some_and(MetricKind::is_cumulative)
&& attachment.is_some_and(|a| a.is_profiles(EPOCH))
{
Some(EpochIn::Attachment)
} else {
None
};
Declaration::Declared(Declared {
carrier: if point { Carrier::Point } else { Carrier::Bare },
kind,
unit: u.valid().cloned(),
buckets: b.valid().cloned(),
semantic: s.valid().copied(),
epoch,
})
}
#[must_use]
pub fn declaration_of(c: &Contract, r: &Resource) -> Declaration {
let Body::Data(d) = &r.body else {
return declaration(r.kind, &r.annotations, None, None);
};
let root = match &d.type_ {
TypeId::JsonSchema { name, schema } => root_schema(&c.artifacts, schema, name),
_ => None,
};
let ty = view(&d.type_, root.as_ref());
let attachment = d.attachment.as_ref().map(|a| view(a, None));
declaration(r.kind, &r.annotations, Some(&ty), attachment.as_ref())
}
fn view<'a>(t: &'a TypeId, root: Option<&'a Value>) -> TypeView<'a> {
match t {
TypeId::JsonSchema { name, schema } => TypeView::Json { name, schema, root },
TypeId::Raw { .. } => TypeView::Raw,
TypeId::Protobuf { .. } => TypeView::Protobuf,
TypeId::Packed { .. } => TypeView::Packed,
}
}
#[must_use]
pub fn root_schema(
artifacts: &BTreeMap<String, Artifact>,
schema: &str,
name: &str,
) -> Option<Value> {
fn json(a: &Artifact) -> Option<&Value> {
match &a.data {
ArtifactData::Json(v) => Some(v),
ArtifactData::Protobuf(_) => None,
}
}
let mut doc = json(artifacts.get(schema)?)?;
let mut s = doc.get("$defs")?.get(name)?.clone();
for _ in 0..64 {
let Some(Value::String(r)) = s.get("$ref").cloned() else {
return Some(s);
};
let (file, pointer) = r.split_once('#').unwrap_or((r.as_str(), ""));
if !file.is_empty() {
let base = file.rsplit('/').next().unwrap_or(file);
let stem = base.strip_suffix(".json").unwrap_or(base);
doc = artifacts
.values()
.filter(|a| a.kind == crate::schema::SchemaKind::JsonSchema && a.name == stem)
.find_map(json)?;
}
let target = if pointer.is_empty() {
doc
} else {
doc.pointer(pointer)?
};
let mut merged = target.as_object()?.clone();
for (k, v) in s.as_object()? {
if k != "$ref" && k != "$defs" {
merged.insert(k.clone(), v.clone());
}
}
if target.get("$ref").is_none() {
merged.remove("$ref");
} else {
merged.insert("$ref".to_owned(), target["$ref"].clone());
}
s = Value::Object(merged);
}
None
}
#[derive(Debug, Clone, PartialEq)]
pub enum Datum {
Null,
Bool(bool),
Int(i128),
BigInt(f64),
Float(f64),
Text(String),
Bytes(Vec<u8>),
Array(Vec<Datum>),
Map(BTreeMap<String, Datum>),
}
impl Datum {
#[must_use]
pub fn from_json(v: &Value) -> Self {
match v {
Value::Null => Self::Null,
Value::Bool(b) => Self::Bool(*b),
Value::Number(n) => {
if let Some(u) = n.as_u64() {
Self::Int(i128::from(u))
} else if let Some(i) = n.as_i64() {
Self::Int(i128::from(i))
} else {
Self::Float(n.as_f64().unwrap_or(f64::NAN))
}
}
Value::String(s) => Self::Text(s.clone()),
Value::Array(a) => Self::Array(a.iter().map(Self::from_json).collect()),
Value::Object(m) => Self::Map(
m.iter()
.map(|(k, v)| (k.clone(), Self::from_json(v)))
.collect(),
),
}
}
#[must_use]
pub fn from_cbor(v: &ciborium::Value) -> Option<Self> {
use ciborium::Value as C;
Some(match v {
C::Null => Self::Null,
C::Bool(b) => Self::Bool(*b),
C::Integer(i) => Self::Int((*i).into()),
C::Float(f) => Self::Float(*f),
C::Text(s) => Self::Text(s.clone()),
C::Bytes(b) => Self::Bytes(b.clone()),
C::Array(a) => Self::Array(a.iter().map(Self::from_cbor).collect::<Option<_>>()?),
C::Map(m) => {
let mut out = BTreeMap::new();
for (k, v) in m {
let C::Text(k) = k else { return None };
out.insert(k.clone(), Self::from_cbor(v)?);
}
Self::Map(out)
}
C::Tag(t @ (2 | 3), inner) if matches!(**inner, C::Bytes(_)) => {
let C::Bytes(m) = &**inner else {
return None;
};
decode::bignum_of(*t == 3, m)
}
C::Tag(_, inner) => Self::from_cbor(inner)?,
_ => return None,
})
}
#[must_use]
pub fn from_json_bytes(bytes: &[u8]) -> Option<Self> {
decode::json(bytes)
}
#[must_use]
pub fn from_cbor_bytes(bytes: &[u8]) -> Option<Self> {
decode::cbor(bytes)
}
#[must_use]
pub fn decode(bytes: &[u8], encoding: Option<crate::authoring::Encoding>) -> Option<Self> {
match encoding {
Some(crate::authoring::Encoding::Cbor) => decode::cbor(bytes),
_ => decode::json(bytes),
}
}
#[must_use]
pub fn attachment(bytes: &[u8], encoding: Option<crate::authoring::Encoding>) -> Self {
Self::decode(bytes, encoding).unwrap_or_else(|| Self::Bytes(bytes.to_vec()))
}
fn get(&self, k: &str) -> Option<&Self> {
match self {
Self::Map(m) => m.get(k),
_ => None,
}
}
fn number(&self) -> Option<f64> {
match self {
Self::Int(i) => Some(*i as f64),
Self::Float(f) | Self::BigInt(f) => Some(*f),
_ => None,
}
}
fn integer(&self) -> Option<i128> {
match self {
Self::Int(i) => Some(*i),
Self::Float(f) if f.is_finite() && f.fract() == 0.0 => Some(*f as i128),
Self::BigInt(f) => Some(if *f < 0.0 { i128::MIN } else { i128::MAX }),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Payload<'a> {
Decoded {
value: &'a Datum,
attachment: Option<&'a Datum>,
},
Undecodable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Problem {
NotAPoint,
EpochInvalid,
UnitInvalid,
TagDisagrees,
UnitDisagrees,
WrongType,
OutOfRange,
NotFinite,
BoundsInvalid,
BoundsDiffer,
CountsLength,
CountSum,
}
impl Problem {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotAPoint => "not_a_point",
Self::EpochInvalid => "epoch_invalid",
Self::UnitInvalid => "unit_invalid",
Self::TagDisagrees => "tag_disagrees",
Self::UnitDisagrees => "unit_disagrees",
Self::WrongType => "wrong_type",
Self::OutOfRange => "out_of_range",
Self::NotFinite => "not_finite",
Self::BoundsInvalid => "bounds_invalid",
Self::BoundsDiffer => "bounds_differ",
Self::CountsLength => "counts_length",
Self::CountSum => "count_sum",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::NotAPoint => "the payload is not a telemetry.v1.Point",
Self::EpochInvalid => "the in-band epoch is not a string of 1 to 64 characters",
Self::UnitInvalid => "the Point's unit is not a unit",
Self::TagDisagrees => "the Point's tag differs from the declared kind",
Self::UnitDisagrees => "the Point's unit differs from the declared unit",
Self::WrongType => "the value is not of the type its kind needs",
Self::OutOfRange => "a count outside 0 to 2^64-1",
Self::NotFinite => "a number that is NaN or infinite",
Self::BoundsInvalid => "the histogram's bounds are empty or not strictly ascending",
Self::BoundsDiffer => "the histogram's bounds differ from the declared buckets",
Self::CountsLength => "counts is not one longer than buckets",
Self::CountSum => "count is not the sum of counts",
}
}
}
impl fmt::Display for Problem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Unasked {
DeclarationInvalid,
Undecodable,
NotThisProfiles,
Ignored,
}
impl Unasked {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::DeclarationInvalid => "declaration_invalid",
Self::Undecodable => "undecodable",
Self::NotThisProfiles => "not_this_profiles",
Self::Ignored => "ignored",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Conformance {
Conforms,
DoesNot(Vec<Problem>),
Unobservable(Unasked),
NotAsked(Unasked),
}
impl Conformance {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Conforms => "conforms",
Self::DoesNot(_) => "does_not",
Self::Unobservable(_) => "unobservable",
Self::NotAsked(_) => "not_asked",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
Declared,
Point,
}
impl Source {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Declared => "declared",
Self::Point => "point",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Histogram {
pub bounds: Vec<f64>,
pub counts: Vec<u64>,
pub count: u64,
pub sum: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Measure {
Counter {
value: u64,
width: u32,
},
Gauge(f64),
Histogram(Histogram),
Text(String),
Boolean(bool),
Binary(Vec<u8>),
}
impl Measure {
#[must_use]
pub const fn counter(value: u64) -> Self {
Self::Counter {
value,
width: FULL_WIDTH,
}
}
#[must_use]
pub fn kind(&self) -> MetricKind {
match self {
Self::Counter { .. } => MetricKind::Counter,
Self::Gauge(_) => MetricKind::Gauge,
Self::Histogram(_) => MetricKind::Histogram,
Self::Text(_) => MetricKind::Text,
Self::Boolean(_) => MetricKind::Boolean,
Self::Binary(_) => MetricKind::Binary,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Reading {
pub value: Measure,
pub timestamp_ms: Option<i64>,
pub epoch: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Checked {
pub conformance: Conformance,
pub kind: Option<(MetricKind, Source)>,
pub unit: Option<(String, Source)>,
pub reading: Option<Reading>,
}
struct PointView<'a> {
timestamp: i64,
tag: MetricKind,
value: &'a Datum,
unit: Option<&'a str>,
epoch: Option<&'a Datum>,
}
fn point_view(d: &Datum) -> Option<PointView<'_>> {
let Datum::Map(_) = d else { return None };
let timestamp = i64::try_from(d.get("timestamp")?.integer()?).ok()?;
let v = d.get("value")?;
let Datum::Map(_) = v else { return None };
let Some(Datum::Text(tag)) = v.get("type") else {
return None;
};
let tag = MetricKind::parse(tag)?;
let value = v.get("value")?;
match d.get("labels") {
None => {}
Some(Datum::Map(m)) if m.values().all(|l| matches!(l, Datum::Text(_))) => {}
Some(_) => return None,
}
let unit = match d.get("unit") {
None => None,
Some(Datum::Text(u)) => Some(u.as_str()),
Some(_) => return None,
};
Some(PointView {
timestamp,
tag,
value,
unit,
epoch: d.get("epoch"),
})
}
fn count(i: i128) -> Result<u64, ()> {
u64::try_from(i).map_err(|_| ())
}
fn check_value(
kind: MetricKind,
v: &Datum,
point: bool,
declared: Option<&[f64]>,
out: &mut Vec<Problem>,
) -> Option<Measure> {
match kind {
MetricKind::Counter => {
let Some(i) = v.integer() else {
out.push(Problem::WrongType);
return None;
};
match count(i) {
Ok(n) => Some(Measure::counter(n)),
Err(()) => {
out.push(Problem::OutOfRange);
None
}
}
}
MetricKind::Gauge => {
let Some(f) = v.number() else {
out.push(Problem::WrongType);
return None;
};
if f.is_finite() {
Some(Measure::Gauge(f))
} else {
out.push(Problem::NotFinite);
None
}
}
MetricKind::Boolean => match v {
Datum::Bool(b) => Some(Measure::Boolean(*b)),
_ => {
out.push(Problem::WrongType);
None
}
},
MetricKind::Text => match v {
Datum::Text(s) => Some(Measure::Text(s.clone())),
_ => {
out.push(Problem::WrongType);
None
}
},
MetricKind::Binary => {
let bytes = match (point, v) {
(false, Datum::Bytes(b)) => Some(b.clone()),
(true, Datum::Array(a)) => a
.iter()
.map(|x| x.integer().and_then(|i| u8::try_from(i).ok()))
.collect(),
_ => None,
};
if bytes.is_none() {
out.push(Problem::WrongType);
}
bytes.map(Measure::Binary)
}
MetricKind::Histogram => check_histogram(v, declared, out),
}
}
fn check_histogram(v: &Datum, declared: Option<&[f64]>, out: &mut Vec<Problem>) -> Option<Measure> {
let shape = (|| {
let Some(Datum::Array(b)) = v.get("buckets") else {
return None;
};
let Some(Datum::Array(c)) = v.get("counts") else {
return None;
};
let bounds: Vec<f64> = b.iter().map(Datum::number).collect::<Option<_>>()?;
let counts: Vec<i128> = c.iter().map(Datum::integer).collect::<Option<_>>()?;
let count = v.get("count")?.integer()?;
let sum = v.get("sum")?.number()?;
Some((bounds, counts, count, sum))
})();
let Some((bounds, counts, total, sum)) = shape else {
out.push(Problem::WrongType);
return None;
};
let before = out.len();
let in_range: Option<(Vec<u64>, u64)> = (|| {
let c: Vec<u64> = counts
.iter()
.map(|i| count(*i).ok())
.collect::<Option<_>>()?;
Some((c, count(total).ok()?))
})();
if in_range.is_none() {
out.push(Problem::OutOfRange);
}
let finite = bounds.iter().all(|b| b.is_finite());
if !finite || !sum.is_finite() {
out.push(Problem::NotFinite);
}
let valid_bounds = finite && !bounds.is_empty() && ascending(&bounds);
if finite && !valid_bounds {
out.push(Problem::BoundsInvalid);
}
if valid_bounds
&& let Some(d) = declared
&& (d.len() != bounds.len() || d.iter().zip(&bounds).any(|(a, b)| a != b))
{
out.push(Problem::BoundsDiffer);
}
if counts.len() != bounds.len() + 1 {
out.push(Problem::CountsLength);
}
if let Some((c, n)) = &in_range
&& c.iter().map(|x| u128::from(*x)).sum::<u128>() != u128::from(*n)
{
out.push(Problem::CountSum);
}
if out.len() > before {
return None;
}
let (counts, count) = in_range?;
Some(Measure::Histogram(Histogram {
bounds,
counts,
count,
sum,
}))
}
#[must_use]
pub fn check(decl: &Declaration, payload: &Payload<'_>) -> Checked {
let none = |c| Checked {
conformance: c,
kind: None,
unit: None,
reading: None,
};
let d = match decl {
Declaration::NotThisProfiles => {
return none(Conformance::NotAsked(Unasked::NotThisProfiles));
}
Declaration::Ignored => return none(Conformance::NotAsked(Unasked::Ignored)),
Declaration::Invalid(_) => {
return none(Conformance::Unobservable(Unasked::DeclarationInvalid));
}
Declaration::Declared(d) => d,
};
let mut out = Checked {
conformance: Conformance::Conforms,
kind: d.kind.map(|k| (k, Source::Declared)),
unit: d.unit.clone().map(|u| (u, Source::Declared)),
reading: None,
};
let Payload::Decoded { value, attachment } = *payload else {
out.conformance = Conformance::Unobservable(Unasked::Undecodable);
return out;
};
let mut problems = Vec::new();
let epoch_of = |e: &Datum, problems: &mut Vec<Problem>| match e {
Datum::Text(s) if is_epoch(s) => Some(s.clone()),
_ => {
problems.push(Problem::EpochInvalid);
None
}
};
let (measure, timestamp_ms, epoch, point) = match d.carrier {
Carrier::Point => {
let Some(p) = point_view(value) else {
out.conformance = Conformance::DoesNot(vec![Problem::NotAPoint]);
return out;
};
let epoch = p.epoch.and_then(|e| epoch_of(e, &mut problems));
let unit = p.unit.filter(|u| is_unit(u));
if p.unit.is_some() && unit.is_none() {
problems.push(Problem::UnitInvalid);
}
if d.kind.is_some_and(|k| k != p.tag) {
problems.push(Problem::TagDisagrees);
}
if let (Some(du), Some(u)) = (&d.unit, unit)
&& du != u
{
problems.push(Problem::UnitDisagrees);
}
let m = check_value(p.tag, p.value, true, d.buckets.as_deref(), &mut problems);
(m, Some(p.timestamp), epoch, Some((p.tag, unit)))
}
Carrier::Bare => {
let kind = d.kind.expect("a valid bare declaration declares its kind");
let epoch = match (d.epoch, attachment) {
(Some(EpochIn::Attachment), Some(a)) => epoch_of(a, &mut problems),
_ => None,
};
let m = check_value(kind, value, false, d.buckets.as_deref(), &mut problems);
(m, None, epoch, None)
}
};
if !problems.is_empty() {
problems.sort_unstable();
problems.dedup();
out.conformance = Conformance::DoesNot(problems);
return out;
}
if let Some((tag, unit)) = point {
out.kind.get_or_insert((tag, Source::Point));
if out.unit.is_none() {
out.unit = unit.map(|u| (u.to_owned(), Source::Point));
}
}
out.reading = measure.map(|value| Reading {
value,
timestamp_ms,
epoch,
});
out
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sampled<'a> {
pub value: &'a Measure,
pub epoch: Option<&'a str>,
pub timestamp_ms: Option<i64>,
pub stamp_ns: Option<i128>,
pub arrival_ns: i128,
pub record: Option<RecordTime>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecordTime {
pub frame: u64,
pub when: crate::frame::When,
pub after_ms: u64,
pub at_ms: Option<u64>,
}
impl RecordTime {
#[must_use]
pub const fn jitter_ms(&self) -> u64 {
match self.when {
crate::frame::When::Scheduled { jitter_ms } => jitter_ms as u64,
_ => 0,
}
}
const fn scheduled(&self) -> bool {
matches!(self.when, crate::frame::When::Scheduled { .. })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeBasis {
Measured,
Scheduled { jitter_ms: u64 },
Arrival,
}
impl TimeBasis {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Measured => "measured",
Self::Scheduled { .. } => "scheduled",
Self::Arrival => "arrival",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Presence<'a> {
pub alone_throughout: bool,
pub earlier: Option<&'a str>,
pub later: Option<&'a str>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Via {
InBand,
Presence,
}
impl Via {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::InBand => "in_band",
Self::Presence => "presence",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Epochs {
Same(Via),
Different(Via),
Unobservable,
}
#[must_use]
pub fn epochs(
earlier: Option<&str>,
later: Option<&str>,
presence: Option<&Presence<'_>>,
) -> Epochs {
if let (Some(a), Some(b)) = (earlier, later) {
return if a == b {
Epochs::Same(Via::InBand)
} else {
Epochs::Different(Via::InBand)
};
}
match presence {
Some(p) if p.alone_throughout => Epochs::Same(Via::Presence),
Some(Presence {
earlier: Some(a),
later: Some(b),
..
}) if a != b => Epochs::Different(Via::Presence),
_ => Epochs::Unobservable,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Continuity {
SameEpoch,
Reset,
Decreased,
Unobservable,
NotAsked,
}
impl Continuity {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::SameEpoch => "same_epoch",
Self::Reset => "reset",
Self::Decreased => "decreased",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Basis {
Established(Via),
Assumed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoRate {
Kind,
Reset,
Decreased,
Elapsed,
WrapOrDecrease,
}
impl NoRate {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Kind => "kind",
Self::Reset => "reset",
Self::Decreased => "decreased",
Self::Elapsed => "elapsed",
Self::WrapOrDecrease => "wrap_or_decrease",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Rate {
pub per_s: f64,
pub unit: Option<String>,
pub elapsed_ns: i128,
pub basis: Option<TimeBasis>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Pair {
pub continuity: Continuity,
pub basis: Option<Basis>,
pub rate: Result<Rate, NoRate>,
}
impl Pair {
#[must_use]
pub fn unobservable(&self) -> Option<&'static str> {
match (self.continuity, &self.rate) {
(Continuity::Unobservable, Err(NoRate::WrapOrDecrease)) => Some("wrap_or_decrease"),
(Continuity::Unobservable, _) => Some("incomparable"),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Change {
Up(u64),
Down,
Outside,
}
fn change(earlier: &Measure, later: &Measure) -> Option<Change> {
match (earlier, later) {
(
Measure::Counter { value: a, width: w },
Measure::Counter {
value: b,
width: wb,
},
) => {
if w != wb || *w == 0 || *w > FULL_WIDTH {
return None;
}
if *w == FULL_WIDTH {
return Some(if b < a {
Change::Down
} else {
Change::Up(b - a)
});
}
let mask = (1u64 << w) - 1;
let d = b.wrapping_sub(*a) & mask;
Some(if d < 1u64 << (w - 1) {
Change::Up(d)
} else {
Change::Outside
})
}
(Measure::Histogram(a), Measure::Histogram(b)) => {
let same_bounds = a.bounds.len() == b.bounds.len()
&& a.bounds.iter().zip(&b.bounds).all(|(x, y)| x == y);
if !same_bounds || a.counts.len() != b.counts.len() {
return None;
}
let down = b.count < a.count || a.counts.iter().zip(&b.counts).any(|(x, y)| y < x);
Some(if down { Change::Down } else { Change::Up(0) })
}
_ => None,
}
}
#[must_use]
pub fn elapsed(a: &Sampled<'_>, b: &Sampled<'_>) -> (i128, Option<TimeBasis>) {
const MS: i128 = 1_000_000;
if let (Some(x), Some(y)) = (&a.record, &b.record) {
let timed = if x.scheduled() || y.scheduled() {
TimeBasis::Scheduled {
jitter_ms: x.jitter_ms() + y.jitter_ms(),
}
} else {
TimeBasis::Measured
};
if x.frame == y.frame {
let e = i128::from(y.after_ms) - i128::from(x.after_ms);
return (e * MS, Some(timed));
}
if let (Some(p), Some(q)) = (x.at_ms, y.at_ms) {
return ((i128::from(q) - i128::from(p)) * MS, Some(timed));
}
return (b.arrival_ns - a.arrival_ns, Some(TimeBasis::Arrival));
}
let e = if let (Some(x), Some(y)) = (a.timestamp_ms, b.timestamp_ms) {
(i128::from(y) - i128::from(x)) * MS
} else if let (Some(x), Some(y)) = (a.stamp_ns, b.stamp_ns) {
y - x
} else {
b.arrival_ns - a.arrival_ns
};
(e, None)
}
#[must_use]
pub fn stamp_ns(ntp64: u64) -> i128 {
let secs = i128::from(ntp64 >> 32);
let frac = ntp64 & 0xffff_ffff;
let sub = (frac * 1_000_000_000).div_ceil(1 << 32);
secs * 1_000_000_000 + i128::from(sub)
}
#[must_use]
pub fn rate_per_s(d: u64, elapsed_ns: i128) -> f64 {
d as f64 / (elapsed_ns as f64 / 1e9)
}
#[must_use]
pub fn pair(
earlier: &Sampled<'_>,
later: &Sampled<'_>,
unit: Option<&str>,
presence: Option<&Presence<'_>>,
) -> Pair {
let (ka, kb) = (earlier.value.kind(), later.value.kind());
if !ka.is_cumulative() && !kb.is_cumulative() {
return Pair {
continuity: Continuity::NotAsked,
basis: None,
rate: Err(NoRate::Kind),
};
}
let counters = ka == MetricKind::Counter && kb == MetricKind::Counter;
let no_rate = |why: NoRate| -> Result<Rate, NoRate> {
if counters {
Err(why)
} else {
Err(NoRate::Kind)
}
};
let Some(moved) = (ka == kb)
.then(|| change(earlier.value, later.value))
.flatten()
else {
return Pair {
continuity: Continuity::Unobservable,
basis: None,
rate: Err(NoRate::Kind),
};
};
let (continuity, basis) = match (epochs(earlier.epoch, later.epoch, presence), moved) {
(Epochs::Same(via), Change::Down) => (Continuity::Decreased, Basis::Established(via)),
(Epochs::Same(via), Change::Up(_)) => (Continuity::SameEpoch, Basis::Established(via)),
(Epochs::Same(via), Change::Outside) => {
return Pair {
continuity: Continuity::Unobservable,
basis: Some(Basis::Established(via)),
rate: Err(NoRate::WrapOrDecrease),
};
}
(Epochs::Different(via), _) => (Continuity::Reset, Basis::Established(via)),
(Epochs::Unobservable, Change::Down | Change::Outside) => {
(Continuity::Reset, Basis::Assumed)
}
(Epochs::Unobservable, Change::Up(_)) => (Continuity::SameEpoch, Basis::Assumed),
};
let rate = match (continuity, moved) {
(Continuity::Reset, _) => no_rate(NoRate::Reset),
(Continuity::Decreased, _) => no_rate(NoRate::Decreased),
(Continuity::SameEpoch, Change::Up(d)) if counters => {
let (e, timed) = elapsed(earlier, later);
if e <= 0 {
Err(NoRate::Elapsed)
} else {
Ok(Rate {
per_s: rate_per_s(d, e),
unit: unit.map(|u| format!("{u}/s")),
elapsed_ns: e,
basis: timed,
})
}
}
_ => Err(NoRate::Kind),
};
Pair {
continuity,
basis: Some(basis),
rate,
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn ann(pairs: &[(&str, Value)]) -> BTreeMap<String, Value> {
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), v.clone()))
.collect()
}
fn point() -> TypeView<'static> {
TypeView::Json {
name: POINT,
schema: PUBLISHED[0],
root: None,
}
}
#[test]
fn a_kind_on_a_counter_type_is_declared() {
let root = json!({"type": "integer", "minimum": 0});
let ty = TypeView::Json {
name: "Counter",
schema: "sha256:00",
root: Some(&root),
};
let d = declaration(
Kind::Stream,
&ann(&[(KIND, json!("counter")), (UNIT, json!("By"))]),
Some(&ty),
None,
);
let Declaration::Declared(d) = d else {
panic!("{d:?}")
};
assert_eq!(d.kind, Some(MetricKind::Counter));
assert_eq!(d.unit.as_deref(), Some("By"));
assert_eq!(d.carrier, Carrier::Bare);
}
#[test]
fn a_point_needs_no_kind_and_is_known_by_its_id() {
let d = declaration(Kind::Stream, &BTreeMap::new(), Some(&point()), None);
assert_eq!(d.declared().map(|d| d.carrier), Some(Carrier::Point));
let other = TypeView::Json {
name: POINT,
schema: "sha256:00",
root: None,
};
assert_eq!(
declaration(Kind::Stream, &BTreeMap::new(), Some(&other), None),
Declaration::NotThisProfiles
);
}
#[test]
fn a_counter_is_read_exactly() {
let d = declaration(
Kind::Stream,
&ann(&[(KIND, json!("counter"))]),
Some(&TypeView::Json {
name: "C",
schema: "x",
root: Some(&json!({"type": "integer"})),
}),
None,
);
let at = |v: Value| {
let datum = Datum::from_json(&v);
check(
&d,
&Payload::Decoded {
value: &datum,
attachment: None,
},
)
.conformance
};
assert_eq!(at(json!(u64::MAX)), Conformance::Conforms);
assert_eq!(
at(json!(18_446_744_073_709_551_616.0)),
Conformance::DoesNot(vec![Problem::OutOfRange])
);
assert_eq!(at(json!(5.0)), Conformance::Conforms);
assert_eq!(
at(json!(5.5)),
Conformance::DoesNot(vec![Problem::WrongType])
);
}
#[test]
fn a_decrease_is_a_reset_unless_one_epoch_is_established() {
let (a, b) = (Measure::counter(10), Measure::counter(3));
let s = |v, e| Sampled {
value: v,
epoch: e,
timestamp_ms: None,
stamp_ns: None,
arrival_ns: 0,
record: None,
};
let p = pair(&s(&a, None), &s(&b, None), None, None);
assert_eq!(
(p.continuity, p.basis),
(Continuity::Reset, Some(Basis::Assumed))
);
let p = pair(&s(&a, Some("e")), &s(&b, Some("e")), None, None);
assert_eq!(p.continuity, Continuity::Decreased);
assert_eq!(p.rate, Err(NoRate::Decreased));
}
#[test]
fn the_rate_is_the_formula() {
let (a, b) = (Measure::counter(0), Measure::counter(1_000));
let s = |v, t| Sampled {
value: v,
epoch: None,
timestamp_ms: Some(t),
stamp_ns: None,
arrival_ns: 0,
record: None,
};
let p = pair(&s(&a, 0), &s(&b, 2_000), Some("By"), None);
assert_eq!(
p.rate,
Ok(Rate {
per_s: 500.0,
unit: Some("By/s".into()),
elapsed_ns: 2_000_000_000,
basis: None,
})
);
}
#[test]
fn a_root_follows_its_refs_across_files_with_outer_keywords_winning() {
let art = |name: &str, doc: Value| Artifact {
kind: crate::schema::SchemaKind::JsonSchema,
name: name.to_owned(),
data: ArtifactData::Json(doc),
};
let a = art(
"a",
json!({"$defs": {
"Count": {"$ref": "#/$defs/Inner", "description": "outer"},
"Inner": {"$ref": "b.json#/$defs/Base", "minimum": 1},
"Loop": {"$ref": "#/$defs/Loop"},
}}),
);
let b = art(
"b",
json!({"$defs": {"Base": {"type": "integer", "minimum": 0}}}),
);
let arts = BTreeMap::from([("sha256:a".to_owned(), a), ("sha256:b".to_owned(), b)]);
assert_eq!(
root_schema(&arts, "sha256:a", "Count"),
Some(json!({"type": "integer", "minimum": 1, "description": "outer"}))
);
assert_eq!(root_schema(&arts, "sha256:a", "Loop"), None, "a loop ends");
assert_eq!(root_schema(&arts, "sha256:a", "Missing"), None);
}
#[test]
fn units_and_epochs_have_their_lengths() {
assert!(is_unit("dBm") && is_unit("bit/s") && !is_unit("") && !is_unit("m s"));
assert!(!is_unit(&"x".repeat(65)) && is_unit(&"x".repeat(64)));
assert!(is_epoch(&"é".repeat(64)) && !is_epoch(&"é".repeat(65)) && !is_epoch(""));
}
}