1use std::collections::BTreeMap;
37use std::fmt;
38
39use serde_json::Value;
40
41use crate::authoring::Kind;
42use crate::contract::{Body, Contract, Resource};
43use crate::schema::{Artifact, ArtifactData, TypeId};
44
45pub mod decode;
46pub mod frames;
47pub mod wire;
48
49pub const PROFILE: &str = "telemetry.v1";
51
52pub const PROFILE_V2: &str = "telemetry.v2";
55
56pub const NAME: &str = "telemetry";
58
59pub const KIND: &str = "telemetry.kind";
61pub const UNIT: &str = "telemetry.unit";
63pub const BUCKETS: &str = "telemetry.buckets";
65pub const SEMANTIC: &str = "telemetry.semantic";
67
68pub const SERIES: &str = "telemetry.series";
71
72pub const VOCABULARY: &[&str] = &["kind", "unit", "buckets", "semantic"];
75
76pub const VOCABULARY_V2: &[&str] = &["kind", "unit", "buckets", "semantic", "series"];
79
80#[must_use]
84pub fn uses_v2(c: &Contract) -> bool {
85 c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
86}
87
88pub const FULL_WIDTH: u32 = 64;
90
91pub const SCHEMA_STEM: &str = "telemetry.v1";
93pub const POINT: &str = "telemetry.v1.Point";
95pub const VALUE: &str = "telemetry.v1.Value";
97pub const HISTOGRAM: &str = "telemetry.v1.Histogram";
99pub const EPOCH: &str = "telemetry.v1.Epoch";
101
102pub const PUBLISHED: &[&str] = &[
106 "sha256:3d6276dd302873ca5938013a44d460267971123fd25500f189e30be718f9dc1e",
107 "sha256:715ce537b2150beb3863f0e5cd356281357f7ec56d93625ee64e14f0045629e9",
108];
109
110pub const MAX_UNIT: usize = 64;
113pub const MAX_EPOCH: usize = 64;
114
115#[must_use]
117pub fn is_published(id: &str) -> bool {
118 PUBLISHED.contains(&id)
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
123pub enum MetricKind {
124 Counter,
125 Gauge,
126 Histogram,
127 Text,
128 Boolean,
129 Binary,
130}
131
132impl MetricKind {
133 pub const ALL: [Self; 6] = [
134 Self::Counter,
135 Self::Gauge,
136 Self::Histogram,
137 Self::Text,
138 Self::Boolean,
139 Self::Binary,
140 ];
141
142 #[must_use]
143 pub fn as_str(self) -> &'static str {
144 match self {
145 Self::Counter => "counter",
146 Self::Gauge => "gauge",
147 Self::Histogram => "histogram",
148 Self::Text => "text",
149 Self::Boolean => "boolean",
150 Self::Binary => "binary",
151 }
152 }
153
154 #[must_use]
156 pub fn parse(s: &str) -> Option<Self> {
157 Self::ALL.into_iter().find(|k| k.as_str() == s)
158 }
159
160 #[must_use]
163 pub fn is_cumulative(self) -> bool {
164 matches!(self, Self::Counter | Self::Histogram)
165 }
166}
167
168impl fmt::Display for MetricKind {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 f.write_str(self.as_str())
171 }
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
176pub enum Semantic {
177 Temperature,
178 Power,
179 Bytes,
180 Duration,
181 Ratio,
182 Count,
183 Identity,
184 State,
185}
186
187impl Semantic {
188 pub const ALL: [Self; 8] = [
189 Self::Temperature,
190 Self::Power,
191 Self::Bytes,
192 Self::Duration,
193 Self::Ratio,
194 Self::Count,
195 Self::Identity,
196 Self::State,
197 ];
198
199 #[must_use]
200 pub fn as_str(self) -> &'static str {
201 match self {
202 Self::Temperature => "temperature",
203 Self::Power => "power",
204 Self::Bytes => "bytes",
205 Self::Duration => "duration",
206 Self::Ratio => "ratio",
207 Self::Count => "count",
208 Self::Identity => "identity",
209 Self::State => "state",
210 }
211 }
212
213 #[must_use]
214 pub fn parse(s: &str) -> Option<Self> {
215 Self::ALL.into_iter().find(|k| k.as_str() == s)
216 }
217}
218
219#[must_use]
222pub fn is_unit(s: &str) -> bool {
223 (1..=MAX_UNIT).contains(&s.len()) && s.bytes().all(|b| (0x21..=0x7e).contains(&b))
224}
225
226#[must_use]
229pub fn is_epoch(s: &str) -> bool {
230 (1..=MAX_EPOCH).contains(&s.chars().count())
231}
232
233#[derive(Debug, Clone, Copy, PartialEq)]
239pub enum TypeView<'a> {
240 Json {
243 name: &'a str,
244 schema: &'a str,
245 root: Option<&'a Value>,
246 },
247 Raw,
249 Protobuf,
251 Packed,
254}
255
256impl TypeView<'_> {
257 #[must_use]
260 pub fn is_profiles(&self, type_name: &str) -> bool {
261 matches!(self, Self::Json { name, schema, .. } if *name == type_name && is_published(schema))
262 }
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum Carrier {
268 Point,
270 Bare,
272}
273
274impl Carrier {
275 #[must_use]
276 pub fn as_str(self) -> &'static str {
277 match self {
278 Self::Point => "point",
279 Self::Bare => "bare",
280 }
281 }
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum EpochIn {
287 Point,
289 Attachment,
291}
292
293impl EpochIn {
294 #[must_use]
295 pub fn as_str(self) -> &'static str {
296 match self {
297 Self::Point => "point",
298 Self::Attachment => "attachment",
299 }
300 }
301}
302
303#[derive(Debug, Clone, PartialEq)]
305pub struct Declared {
306 pub carrier: Carrier,
307 pub kind: Option<MetricKind>,
309 pub unit: Option<String>,
310 pub buckets: Option<Vec<f64>>,
312 pub semantic: Option<Semantic>,
313 pub epoch: Option<EpochIn>,
315}
316
317#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
319pub enum Invalid {
320 KindValue,
321 UnitValue,
322 BucketsValue,
323 SemanticValue,
324 KindMissing,
325 BucketsWithoutHistogram,
326 HistogramWithoutBuckets,
327 NotACarrier,
328}
329
330impl Invalid {
331 #[must_use]
332 pub fn as_str(self) -> &'static str {
333 match self {
334 Self::KindValue => "kind_value",
335 Self::UnitValue => "unit_value",
336 Self::BucketsValue => "buckets_value",
337 Self::SemanticValue => "semantic_value",
338 Self::KindMissing => "kind_missing",
339 Self::BucketsWithoutHistogram => "buckets_without_histogram",
340 Self::HistogramWithoutBuckets => "histogram_without_buckets",
341 Self::NotACarrier => "not_a_carrier",
342 }
343 }
344
345 #[must_use]
347 pub fn says(self) -> &'static str {
348 match self {
349 Self::KindValue => "telemetry.kind is not one of the six kinds",
350 Self::UnitValue => {
351 "telemetry.unit is not 1 to 64 printable ASCII characters (0x21 to 0x7E)"
352 }
353 Self::BucketsValue => {
354 "telemetry.buckets is not a non-empty array of finite numbers, strictly ascending"
355 }
356 Self::SemanticValue => "telemetry.semantic is not one of the eight semantics",
357 Self::KindMissing => "no telemetry.kind, and the type is not the profile's Point",
358 Self::BucketsWithoutHistogram => {
359 "telemetry.buckets on a resource whose declared kind is not histogram"
360 }
361 Self::HistogramWithoutBuckets => "a histogram without telemetry.buckets",
362 Self::NotACarrier => "the type cannot carry the declared kind",
363 }
364 }
365}
366
367impl fmt::Display for Invalid {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 f.write_str(self.as_str())
370 }
371}
372
373#[derive(Debug, Clone, PartialEq)]
375pub enum Declaration {
376 Declared(Declared),
377 Invalid(Vec<Invalid>),
379 Ignored,
382 NotThisProfiles,
385}
386
387impl Declaration {
388 #[must_use]
390 pub fn as_str(&self) -> &'static str {
391 match self {
392 Self::Declared(_) => "declared",
393 Self::Invalid(_) => "invalid",
394 Self::Ignored => "ignored",
395 Self::NotThisProfiles => "not_this_profiles",
396 }
397 }
398
399 #[must_use]
400 pub fn declared(&self) -> Option<&Declared> {
401 match self {
402 Self::Declared(d) => Some(d),
403 _ => None,
404 }
405 }
406}
407
408enum Read<T> {
410 Absent,
411 Valid(T),
412 Wrong,
413}
414
415impl<T> Read<T> {
416 fn of(v: Option<&Value>, f: impl FnOnce(&Value) -> Option<T>) -> Self {
417 match v {
418 None => Self::Absent,
419 Some(v) => f(v).map_or(Self::Wrong, Self::Valid),
420 }
421 }
422 fn is_wrong(&self) -> bool {
423 matches!(self, Self::Wrong)
424 }
425 fn valid(&self) -> Option<&T> {
426 match self {
427 Self::Valid(t) => Some(t),
428 _ => None,
429 }
430 }
431}
432
433fn read_buckets(v: &Value) -> Option<Vec<f64>> {
436 let a = v.as_array()?;
437 let b: Vec<f64> = a.iter().map(Value::as_f64).collect::<Option<_>>()?;
438 (!b.is_empty() && b.iter().all(|x| x.is_finite()) && ascending(&b)).then_some(b)
439}
440
441fn ascending(b: &[f64]) -> bool {
442 b.windows(2).all(|w| w[0] < w[1])
443}
444
445fn type_names(root: &Value) -> Vec<&str> {
448 let mut v: Vec<&str> = match root.get("type") {
449 Some(Value::String(s)) => vec![s.as_str()],
450 Some(Value::Array(a)) => {
451 let names: Option<Vec<&str>> = a.iter().map(Value::as_str).collect();
452 names.unwrap_or_default()
453 }
454 _ => Vec::new(),
455 };
456 v.sort_unstable();
457 v.dedup();
458 v
459}
460
461#[must_use]
463pub fn carries(ty: &TypeView<'_>, kind: MetricKind) -> bool {
464 if ty.is_profiles(POINT) {
465 return true;
466 }
467 if ty.is_profiles(HISTOGRAM) {
468 return kind == MetricKind::Histogram;
469 }
470 match ty {
471 TypeView::Raw => kind == MetricKind::Binary,
472 TypeView::Protobuf | TypeView::Packed | TypeView::Json { root: None, .. } => false,
473 TypeView::Json {
474 root: Some(root), ..
475 } => {
476 let t = type_names(root);
477 match kind {
478 MetricKind::Counter => t == ["integer"],
479 MetricKind::Gauge => {
480 !t.is_empty() && t.iter().all(|n| matches!(*n, "integer" | "number"))
481 }
482 MetricKind::Boolean => t == ["boolean"],
483 MetricKind::Text => t == ["string"],
484 MetricKind::Histogram | MetricKind::Binary => false,
485 }
486 }
487 }
488}
489
490#[must_use]
494pub fn declaration(
495 kind: Kind,
496 annotations: &BTreeMap<String, Value>,
497 ty: Option<&TypeView<'_>>,
498 attachment: Option<&TypeView<'_>>,
499) -> Declaration {
500 let any_key = [KIND, UNIT, BUCKETS, SEMANTIC]
501 .iter()
502 .any(|k| annotations.contains_key(*k));
503 if matches!(kind, Kind::Event | Kind::Operation) {
504 return if any_key {
505 Declaration::Ignored
506 } else {
507 Declaration::NotThisProfiles
508 };
509 }
510 let point = ty.is_some_and(|t| t.is_profiles(POINT));
511 if !any_key && !point {
512 return Declaration::NotThisProfiles;
513 }
514 let k = Read::of(annotations.get(KIND), |v| {
515 v.as_str().and_then(MetricKind::parse)
516 });
517 let u = Read::of(annotations.get(UNIT), |v| {
518 v.as_str().filter(|s| is_unit(s)).map(str::to_owned)
519 });
520 let b = Read::of(annotations.get(BUCKETS), read_buckets);
521 let s = Read::of(annotations.get(SEMANTIC), |v| {
522 v.as_str().and_then(Semantic::parse)
523 });
524 let mut why = Vec::new();
525 for (wrong, r) in [
526 (k.is_wrong(), Invalid::KindValue),
527 (u.is_wrong(), Invalid::UnitValue),
528 (b.is_wrong(), Invalid::BucketsValue),
529 (s.is_wrong(), Invalid::SemanticValue),
530 ] {
531 if wrong {
532 why.push(r);
533 }
534 }
535 if matches!(k, Read::Absent) && !point {
536 why.push(Invalid::KindMissing);
537 }
538 let histogram = matches!(k, Read::Valid(MetricKind::Histogram));
539 if matches!(b, Read::Valid(_)) && !k.is_wrong() && !histogram {
540 why.push(Invalid::BucketsWithoutHistogram);
541 }
542 if histogram && matches!(b, Read::Absent) {
543 why.push(Invalid::HistogramWithoutBuckets);
544 }
545 if let Some(declared) = k.valid()
546 && !ty.is_some_and(|t| carries(t, *declared))
547 {
548 why.push(Invalid::NotACarrier);
549 }
550 if !why.is_empty() {
551 return Declaration::Invalid(why);
552 }
553 let kind = k.valid().copied();
554 let epoch = if point {
555 Some(EpochIn::Point)
556 } else if kind.is_some_and(MetricKind::is_cumulative)
557 && attachment.is_some_and(|a| a.is_profiles(EPOCH))
558 {
559 Some(EpochIn::Attachment)
560 } else {
561 None
562 };
563 Declaration::Declared(Declared {
564 carrier: if point { Carrier::Point } else { Carrier::Bare },
565 kind,
566 unit: u.valid().cloned(),
567 buckets: b.valid().cloned(),
568 semantic: s.valid().copied(),
569 epoch,
570 })
571}
572
573#[must_use]
576pub fn declaration_of(c: &Contract, r: &Resource) -> Declaration {
577 let Body::Data(d) = &r.body else {
578 return declaration(r.kind, &r.annotations, None, None);
579 };
580 let root = match &d.type_ {
581 TypeId::JsonSchema { name, schema } => root_schema(&c.artifacts, schema, name),
582 _ => None,
583 };
584 let ty = view(&d.type_, root.as_ref());
585 let attachment = d.attachment.as_ref().map(|a| view(a, None));
586 declaration(r.kind, &r.annotations, Some(&ty), attachment.as_ref())
587}
588
589fn view<'a>(t: &'a TypeId, root: Option<&'a Value>) -> TypeView<'a> {
590 match t {
591 TypeId::JsonSchema { name, schema } => TypeView::Json { name, schema, root },
592 TypeId::Raw { .. } => TypeView::Raw,
593 TypeId::Protobuf { .. } => TypeView::Protobuf,
594 TypeId::Packed { .. } => TypeView::Packed,
595 }
596}
597
598#[must_use]
604pub fn root_schema(
605 artifacts: &BTreeMap<String, Artifact>,
606 schema: &str,
607 name: &str,
608) -> Option<Value> {
609 fn json(a: &Artifact) -> Option<&Value> {
610 match &a.data {
611 ArtifactData::Json(v) => Some(v),
612 ArtifactData::Protobuf(_) => None,
613 }
614 }
615 let mut doc = json(artifacts.get(schema)?)?;
616 let mut s = doc.get("$defs")?.get(name)?.clone();
617 for _ in 0..64 {
618 let Some(Value::String(r)) = s.get("$ref").cloned() else {
619 return Some(s);
620 };
621 let (file, pointer) = r.split_once('#').unwrap_or((r.as_str(), ""));
622 if !file.is_empty() {
623 let base = file.rsplit('/').next().unwrap_or(file);
624 let stem = base.strip_suffix(".json").unwrap_or(base);
625 doc = artifacts
626 .values()
627 .filter(|a| a.kind == crate::schema::SchemaKind::JsonSchema && a.name == stem)
628 .find_map(json)?;
629 }
630 let target = if pointer.is_empty() {
631 doc
632 } else {
633 doc.pointer(pointer)?
634 };
635 let mut merged = target.as_object()?.clone();
636 for (k, v) in s.as_object()? {
637 if k != "$ref" && k != "$defs" {
638 merged.insert(k.clone(), v.clone());
639 }
640 }
641 if target.get("$ref").is_none() {
642 merged.remove("$ref");
643 } else {
644 merged.insert("$ref".to_owned(), target["$ref"].clone());
645 }
646 s = Value::Object(merged);
647 }
648 None
649}
650
651#[derive(Debug, Clone, PartialEq)]
658pub enum Datum {
659 Null,
660 Bool(bool),
661 Int(i128),
664 BigInt(f64),
670 Float(f64),
672 Text(String),
673 Bytes(Vec<u8>),
674 Array(Vec<Datum>),
675 Map(BTreeMap<String, Datum>),
676}
677
678impl Datum {
679 #[must_use]
684 pub fn from_json(v: &Value) -> Self {
685 match v {
686 Value::Null => Self::Null,
687 Value::Bool(b) => Self::Bool(*b),
688 Value::Number(n) => {
689 if let Some(u) = n.as_u64() {
690 Self::Int(i128::from(u))
691 } else if let Some(i) = n.as_i64() {
692 Self::Int(i128::from(i))
693 } else {
694 Self::Float(n.as_f64().unwrap_or(f64::NAN))
695 }
696 }
697 Value::String(s) => Self::Text(s.clone()),
698 Value::Array(a) => Self::Array(a.iter().map(Self::from_json).collect()),
699 Value::Object(m) => Self::Map(
700 m.iter()
701 .map(|(k, v)| (k.clone(), Self::from_json(v)))
702 .collect(),
703 ),
704 }
705 }
706
707 #[must_use]
711 pub fn from_cbor(v: &ciborium::Value) -> Option<Self> {
712 use ciborium::Value as C;
713 Some(match v {
714 C::Null => Self::Null,
715 C::Bool(b) => Self::Bool(*b),
716 C::Integer(i) => Self::Int((*i).into()),
717 C::Float(f) => Self::Float(*f),
718 C::Text(s) => Self::Text(s.clone()),
719 C::Bytes(b) => Self::Bytes(b.clone()),
720 C::Array(a) => Self::Array(a.iter().map(Self::from_cbor).collect::<Option<_>>()?),
721 C::Map(m) => {
722 let mut out = BTreeMap::new();
723 for (k, v) in m {
724 let C::Text(k) = k else { return None };
725 out.insert(k.clone(), Self::from_cbor(v)?);
726 }
727 Self::Map(out)
728 }
729 C::Tag(t @ (2 | 3), inner) if matches!(**inner, C::Bytes(_)) => {
730 let C::Bytes(m) = &**inner else {
731 return None;
732 };
733 decode::bignum_of(*t == 3, m)
734 }
735 C::Tag(_, inner) => Self::from_cbor(inner)?,
736 _ => return None,
737 })
738 }
739
740 #[must_use]
743 pub fn from_json_bytes(bytes: &[u8]) -> Option<Self> {
744 decode::json(bytes)
745 }
746
747 #[must_use]
750 pub fn from_cbor_bytes(bytes: &[u8]) -> Option<Self> {
751 decode::cbor(bytes)
752 }
753
754 #[must_use]
756 pub fn decode(bytes: &[u8], encoding: Option<crate::authoring::Encoding>) -> Option<Self> {
757 match encoding {
758 Some(crate::authoring::Encoding::Cbor) => decode::cbor(bytes),
759 _ => decode::json(bytes),
760 }
761 }
762
763 #[must_use]
770 pub fn attachment(bytes: &[u8], encoding: Option<crate::authoring::Encoding>) -> Self {
771 Self::decode(bytes, encoding).unwrap_or_else(|| Self::Bytes(bytes.to_vec()))
772 }
773
774 fn get(&self, k: &str) -> Option<&Self> {
775 match self {
776 Self::Map(m) => m.get(k),
777 _ => None,
778 }
779 }
780
781 fn number(&self) -> Option<f64> {
783 match self {
784 Self::Int(i) => Some(*i as f64),
785 Self::Float(f) | Self::BigInt(f) => Some(*f),
786 _ => None,
787 }
788 }
789
790 fn integer(&self) -> Option<i128> {
795 match self {
796 Self::Int(i) => Some(*i),
797 Self::Float(f) if f.is_finite() && f.fract() == 0.0 => Some(*f as i128),
799 Self::BigInt(f) => Some(if *f < 0.0 { i128::MIN } else { i128::MAX }),
801 _ => None,
802 }
803 }
804}
805
806#[derive(Debug, Clone, Copy, PartialEq)]
812pub enum Payload<'a> {
813 Decoded {
815 value: &'a Datum,
816 attachment: Option<&'a Datum>,
817 },
818 Undecodable,
820}
821
822#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
824pub enum Problem {
825 NotAPoint,
826 EpochInvalid,
827 UnitInvalid,
828 TagDisagrees,
829 UnitDisagrees,
830 WrongType,
831 OutOfRange,
832 NotFinite,
833 BoundsInvalid,
834 BoundsDiffer,
835 CountsLength,
836 CountSum,
837}
838
839impl Problem {
840 #[must_use]
841 pub fn as_str(self) -> &'static str {
842 match self {
843 Self::NotAPoint => "not_a_point",
844 Self::EpochInvalid => "epoch_invalid",
845 Self::UnitInvalid => "unit_invalid",
846 Self::TagDisagrees => "tag_disagrees",
847 Self::UnitDisagrees => "unit_disagrees",
848 Self::WrongType => "wrong_type",
849 Self::OutOfRange => "out_of_range",
850 Self::NotFinite => "not_finite",
851 Self::BoundsInvalid => "bounds_invalid",
852 Self::BoundsDiffer => "bounds_differ",
853 Self::CountsLength => "counts_length",
854 Self::CountSum => "count_sum",
855 }
856 }
857
858 #[must_use]
860 pub fn says(self) -> &'static str {
861 match self {
862 Self::NotAPoint => "the payload is not a telemetry.v1.Point",
863 Self::EpochInvalid => "the in-band epoch is not a string of 1 to 64 characters",
864 Self::UnitInvalid => "the Point's unit is not a unit",
865 Self::TagDisagrees => "the Point's tag differs from the declared kind",
866 Self::UnitDisagrees => "the Point's unit differs from the declared unit",
867 Self::WrongType => "the value is not of the type its kind needs",
868 Self::OutOfRange => "a count outside 0 to 2^64-1",
869 Self::NotFinite => "a number that is NaN or infinite",
870 Self::BoundsInvalid => "the histogram's bounds are empty or not strictly ascending",
871 Self::BoundsDiffer => "the histogram's bounds differ from the declared buckets",
872 Self::CountsLength => "counts is not one longer than buckets",
873 Self::CountSum => "count is not the sum of counts",
874 }
875 }
876}
877
878impl fmt::Display for Problem {
879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 f.write_str(self.as_str())
881 }
882}
883
884#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
887pub enum Unasked {
888 DeclarationInvalid,
890 Undecodable,
892 NotThisProfiles,
894 Ignored,
896}
897
898impl Unasked {
899 #[must_use]
900 pub fn as_str(self) -> &'static str {
901 match self {
902 Self::DeclarationInvalid => "declaration_invalid",
903 Self::Undecodable => "undecodable",
904 Self::NotThisProfiles => "not_this_profiles",
905 Self::Ignored => "ignored",
906 }
907 }
908}
909
910#[derive(Debug, Clone, PartialEq, Eq)]
913pub enum Conformance {
914 Conforms,
915 DoesNot(Vec<Problem>),
917 Unobservable(Unasked),
918 NotAsked(Unasked),
919}
920
921impl Conformance {
922 #[must_use]
924 pub fn as_str(&self) -> &'static str {
925 match self {
926 Self::Conforms => "conforms",
927 Self::DoesNot(_) => "does_not",
928 Self::Unobservable(_) => "unobservable",
929 Self::NotAsked(_) => "not_asked",
930 }
931 }
932}
933
934#[derive(Debug, Clone, Copy, PartialEq, Eq)]
936pub enum Source {
937 Declared,
939 Point,
941}
942
943impl Source {
944 #[must_use]
945 pub fn as_str(self) -> &'static str {
946 match self {
947 Self::Declared => "declared",
948 Self::Point => "point",
949 }
950 }
951}
952
953#[derive(Debug, Clone, PartialEq)]
955pub struct Histogram {
956 pub bounds: Vec<f64>,
957 pub counts: Vec<u64>,
958 pub count: u64,
959 pub sum: f64,
960}
961
962#[derive(Debug, Clone, PartialEq)]
964pub enum Measure {
965 Counter {
969 value: u64,
970 width: u32,
971 },
972 Gauge(f64),
973 Histogram(Histogram),
974 Text(String),
975 Boolean(bool),
976 Binary(Vec<u8>),
977}
978
979impl Measure {
980 #[must_use]
982 pub const fn counter(value: u64) -> Self {
983 Self::Counter {
984 value,
985 width: FULL_WIDTH,
986 }
987 }
988
989 #[must_use]
990 pub fn kind(&self) -> MetricKind {
991 match self {
992 Self::Counter { .. } => MetricKind::Counter,
993 Self::Gauge(_) => MetricKind::Gauge,
994 Self::Histogram(_) => MetricKind::Histogram,
995 Self::Text(_) => MetricKind::Text,
996 Self::Boolean(_) => MetricKind::Boolean,
997 Self::Binary(_) => MetricKind::Binary,
998 }
999 }
1000}
1001
1002#[derive(Debug, Clone, PartialEq)]
1005pub struct Reading {
1006 pub value: Measure,
1007 pub timestamp_ms: Option<i64>,
1008 pub epoch: Option<String>,
1009}
1010
1011#[derive(Debug, Clone, PartialEq)]
1013pub struct Checked {
1014 pub conformance: Conformance,
1015 pub kind: Option<(MetricKind, Source)>,
1018 pub unit: Option<(String, Source)>,
1021 pub reading: Option<Reading>,
1023}
1024
1025struct PointView<'a> {
1027 timestamp: i64,
1028 tag: MetricKind,
1029 value: &'a Datum,
1030 unit: Option<&'a str>,
1031 epoch: Option<&'a Datum>,
1032}
1033
1034fn point_view(d: &Datum) -> Option<PointView<'_>> {
1035 let Datum::Map(_) = d else { return None };
1036 let timestamp = i64::try_from(d.get("timestamp")?.integer()?).ok()?;
1037 let v = d.get("value")?;
1038 let Datum::Map(_) = v else { return None };
1039 let Some(Datum::Text(tag)) = v.get("type") else {
1040 return None;
1041 };
1042 let tag = MetricKind::parse(tag)?;
1043 let value = v.get("value")?;
1044 match d.get("labels") {
1045 None => {}
1046 Some(Datum::Map(m)) if m.values().all(|l| matches!(l, Datum::Text(_))) => {}
1047 Some(_) => return None,
1048 }
1049 let unit = match d.get("unit") {
1050 None => None,
1051 Some(Datum::Text(u)) => Some(u.as_str()),
1052 Some(_) => return None,
1053 };
1054 Some(PointView {
1055 timestamp,
1056 tag,
1057 value,
1058 unit,
1059 epoch: d.get("epoch"),
1060 })
1061}
1062
1063fn count(i: i128) -> Result<u64, ()> {
1065 u64::try_from(i).map_err(|_| ())
1066}
1067
1068fn check_value(
1071 kind: MetricKind,
1072 v: &Datum,
1073 point: bool,
1074 declared: Option<&[f64]>,
1075 out: &mut Vec<Problem>,
1076) -> Option<Measure> {
1077 match kind {
1078 MetricKind::Counter => {
1079 let Some(i) = v.integer() else {
1080 out.push(Problem::WrongType);
1081 return None;
1082 };
1083 match count(i) {
1084 Ok(n) => Some(Measure::counter(n)),
1085 Err(()) => {
1086 out.push(Problem::OutOfRange);
1087 None
1088 }
1089 }
1090 }
1091 MetricKind::Gauge => {
1092 let Some(f) = v.number() else {
1093 out.push(Problem::WrongType);
1094 return None;
1095 };
1096 if f.is_finite() {
1097 Some(Measure::Gauge(f))
1098 } else {
1099 out.push(Problem::NotFinite);
1100 None
1101 }
1102 }
1103 MetricKind::Boolean => match v {
1104 Datum::Bool(b) => Some(Measure::Boolean(*b)),
1105 _ => {
1106 out.push(Problem::WrongType);
1107 None
1108 }
1109 },
1110 MetricKind::Text => match v {
1111 Datum::Text(s) => Some(Measure::Text(s.clone())),
1112 _ => {
1113 out.push(Problem::WrongType);
1114 None
1115 }
1116 },
1117 MetricKind::Binary => {
1118 let bytes = match (point, v) {
1119 (false, Datum::Bytes(b)) => Some(b.clone()),
1120 (true, Datum::Array(a)) => a
1121 .iter()
1122 .map(|x| x.integer().and_then(|i| u8::try_from(i).ok()))
1123 .collect(),
1124 _ => None,
1125 };
1126 if bytes.is_none() {
1127 out.push(Problem::WrongType);
1128 }
1129 bytes.map(Measure::Binary)
1130 }
1131 MetricKind::Histogram => check_histogram(v, declared, out),
1132 }
1133}
1134
1135fn check_histogram(v: &Datum, declared: Option<&[f64]>, out: &mut Vec<Problem>) -> Option<Measure> {
1136 let shape = (|| {
1137 let Some(Datum::Array(b)) = v.get("buckets") else {
1138 return None;
1139 };
1140 let Some(Datum::Array(c)) = v.get("counts") else {
1141 return None;
1142 };
1143 let bounds: Vec<f64> = b.iter().map(Datum::number).collect::<Option<_>>()?;
1144 let counts: Vec<i128> = c.iter().map(Datum::integer).collect::<Option<_>>()?;
1145 let count = v.get("count")?.integer()?;
1146 let sum = v.get("sum")?.number()?;
1147 Some((bounds, counts, count, sum))
1148 })();
1149 let Some((bounds, counts, total, sum)) = shape else {
1150 out.push(Problem::WrongType);
1151 return None;
1152 };
1153 let before = out.len();
1154 let in_range: Option<(Vec<u64>, u64)> = (|| {
1155 let c: Vec<u64> = counts
1156 .iter()
1157 .map(|i| count(*i).ok())
1158 .collect::<Option<_>>()?;
1159 Some((c, count(total).ok()?))
1160 })();
1161 if in_range.is_none() {
1162 out.push(Problem::OutOfRange);
1163 }
1164 let finite = bounds.iter().all(|b| b.is_finite());
1165 if !finite || !sum.is_finite() {
1166 out.push(Problem::NotFinite);
1167 }
1168 let valid_bounds = finite && !bounds.is_empty() && ascending(&bounds);
1169 if finite && !valid_bounds {
1170 out.push(Problem::BoundsInvalid);
1171 }
1172 if valid_bounds
1173 && let Some(d) = declared
1174 && (d.len() != bounds.len() || d.iter().zip(&bounds).any(|(a, b)| a != b))
1175 {
1176 out.push(Problem::BoundsDiffer);
1177 }
1178 if counts.len() != bounds.len() + 1 {
1179 out.push(Problem::CountsLength);
1180 }
1181 if let Some((c, n)) = &in_range
1182 && c.iter().map(|x| u128::from(*x)).sum::<u128>() != u128::from(*n)
1183 {
1184 out.push(Problem::CountSum);
1185 }
1186 if out.len() > before {
1187 return None;
1188 }
1189 let (counts, count) = in_range?;
1190 Some(Measure::Histogram(Histogram {
1191 bounds,
1192 counts,
1193 count,
1194 sum,
1195 }))
1196}
1197
1198#[must_use]
1202pub fn check(decl: &Declaration, payload: &Payload<'_>) -> Checked {
1203 let none = |c| Checked {
1204 conformance: c,
1205 kind: None,
1206 unit: None,
1207 reading: None,
1208 };
1209 let d = match decl {
1210 Declaration::NotThisProfiles => {
1211 return none(Conformance::NotAsked(Unasked::NotThisProfiles));
1212 }
1213 Declaration::Ignored => return none(Conformance::NotAsked(Unasked::Ignored)),
1214 Declaration::Invalid(_) => {
1215 return none(Conformance::Unobservable(Unasked::DeclarationInvalid));
1216 }
1217 Declaration::Declared(d) => d,
1218 };
1219 let mut out = Checked {
1220 conformance: Conformance::Conforms,
1221 kind: d.kind.map(|k| (k, Source::Declared)),
1222 unit: d.unit.clone().map(|u| (u, Source::Declared)),
1223 reading: None,
1224 };
1225 let Payload::Decoded { value, attachment } = *payload else {
1226 out.conformance = Conformance::Unobservable(Unasked::Undecodable);
1227 return out;
1228 };
1229 let mut problems = Vec::new();
1230 let epoch_of = |e: &Datum, problems: &mut Vec<Problem>| match e {
1231 Datum::Text(s) if is_epoch(s) => Some(s.clone()),
1232 _ => {
1233 problems.push(Problem::EpochInvalid);
1234 None
1235 }
1236 };
1237 let (measure, timestamp_ms, epoch, point) = match d.carrier {
1238 Carrier::Point => {
1239 let Some(p) = point_view(value) else {
1240 out.conformance = Conformance::DoesNot(vec![Problem::NotAPoint]);
1241 return out;
1242 };
1243 let epoch = p.epoch.and_then(|e| epoch_of(e, &mut problems));
1244 let unit = p.unit.filter(|u| is_unit(u));
1245 if p.unit.is_some() && unit.is_none() {
1246 problems.push(Problem::UnitInvalid);
1247 }
1248 if d.kind.is_some_and(|k| k != p.tag) {
1249 problems.push(Problem::TagDisagrees);
1250 }
1251 if let (Some(du), Some(u)) = (&d.unit, unit)
1252 && du != u
1253 {
1254 problems.push(Problem::UnitDisagrees);
1255 }
1256 let m = check_value(p.tag, p.value, true, d.buckets.as_deref(), &mut problems);
1257 (m, Some(p.timestamp), epoch, Some((p.tag, unit)))
1258 }
1259 Carrier::Bare => {
1260 let kind = d.kind.expect("a valid bare declaration declares its kind");
1261 let epoch = match (d.epoch, attachment) {
1262 (Some(EpochIn::Attachment), Some(a)) => epoch_of(a, &mut problems),
1263 _ => None,
1264 };
1265 let m = check_value(kind, value, false, d.buckets.as_deref(), &mut problems);
1266 (m, None, epoch, None)
1267 }
1268 };
1269 if !problems.is_empty() {
1270 problems.sort_unstable();
1271 problems.dedup();
1272 out.conformance = Conformance::DoesNot(problems);
1273 return out;
1274 }
1275 if let Some((tag, unit)) = point {
1276 out.kind.get_or_insert((tag, Source::Point));
1277 if out.unit.is_none() {
1278 out.unit = unit.map(|u| (u.to_owned(), Source::Point));
1279 }
1280 }
1281 out.reading = measure.map(|value| Reading {
1282 value,
1283 timestamp_ms,
1284 epoch,
1285 });
1286 out
1287}
1288
1289#[derive(Debug, Clone, Copy, PartialEq)]
1295pub struct Sampled<'a> {
1296 pub value: &'a Measure,
1298 pub epoch: Option<&'a str>,
1300 pub timestamp_ms: Option<i64>,
1302 pub stamp_ns: Option<i128>,
1305 pub arrival_ns: i128,
1307 pub record: Option<RecordTime>,
1310}
1311
1312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1316pub struct RecordTime {
1317 pub frame: u64,
1321 pub when: crate::frame::When,
1322 pub after_ms: u64,
1325 pub at_ms: Option<u64>,
1328}
1329
1330impl RecordTime {
1331 #[must_use]
1334 pub const fn jitter_ms(&self) -> u64 {
1335 match self.when {
1336 crate::frame::When::Scheduled { jitter_ms } => jitter_ms as u64,
1337 _ => 0,
1338 }
1339 }
1340
1341 const fn scheduled(&self) -> bool {
1342 matches!(self.when, crate::frame::When::Scheduled { .. })
1343 }
1344}
1345
1346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1348pub enum TimeBasis {
1349 Measured,
1351 Scheduled { jitter_ms: u64 },
1355 Arrival,
1357}
1358
1359impl TimeBasis {
1360 #[must_use]
1362 pub const fn as_str(self) -> &'static str {
1363 match self {
1364 Self::Measured => "measured",
1365 Self::Scheduled { .. } => "scheduled",
1366 Self::Arrival => "arrival",
1367 }
1368 }
1369}
1370
1371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1374pub struct Presence<'a> {
1375 pub alone_throughout: bool,
1378 pub earlier: Option<&'a str>,
1381 pub later: Option<&'a str>,
1383}
1384
1385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1387pub enum Via {
1388 InBand,
1389 Presence,
1390}
1391
1392impl Via {
1393 #[must_use]
1394 pub fn as_str(self) -> &'static str {
1395 match self {
1396 Self::InBand => "in_band",
1397 Self::Presence => "presence",
1398 }
1399 }
1400}
1401
1402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1404pub enum Epochs {
1405 Same(Via),
1406 Different(Via),
1407 Unobservable,
1408}
1409
1410#[must_use]
1413pub fn epochs(
1414 earlier: Option<&str>,
1415 later: Option<&str>,
1416 presence: Option<&Presence<'_>>,
1417) -> Epochs {
1418 if let (Some(a), Some(b)) = (earlier, later) {
1419 return if a == b {
1420 Epochs::Same(Via::InBand)
1421 } else {
1422 Epochs::Different(Via::InBand)
1423 };
1424 }
1425 match presence {
1426 Some(p) if p.alone_throughout => Epochs::Same(Via::Presence),
1427 Some(Presence {
1428 earlier: Some(a),
1429 later: Some(b),
1430 ..
1431 }) if a != b => Epochs::Different(Via::Presence),
1432 _ => Epochs::Unobservable,
1433 }
1434}
1435
1436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1438pub enum Continuity {
1439 SameEpoch,
1440 Reset,
1441 Decreased,
1442 Unobservable,
1447 NotAsked,
1449}
1450
1451impl Continuity {
1452 #[must_use]
1453 pub fn as_str(self) -> &'static str {
1454 match self {
1455 Self::SameEpoch => "same_epoch",
1456 Self::Reset => "reset",
1457 Self::Decreased => "decreased",
1458 Self::Unobservable => "unobservable",
1459 Self::NotAsked => "not_asked",
1460 }
1461 }
1462}
1463
1464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1466pub enum Basis {
1467 Established(Via),
1468 Assumed,
1469}
1470
1471#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1473pub enum NoRate {
1474 Kind,
1477 Reset,
1478 Decreased,
1479 Elapsed,
1481 WrapOrDecrease,
1485}
1486
1487impl NoRate {
1488 #[must_use]
1489 pub fn as_str(self) -> &'static str {
1490 match self {
1491 Self::Kind => "kind",
1492 Self::Reset => "reset",
1493 Self::Decreased => "decreased",
1494 Self::Elapsed => "elapsed",
1495 Self::WrapOrDecrease => "wrap_or_decrease",
1496 }
1497 }
1498}
1499
1500#[derive(Debug, Clone, PartialEq)]
1502pub struct Rate {
1503 pub per_s: f64,
1505 pub unit: Option<String>,
1507 pub elapsed_ns: i128,
1509 pub basis: Option<TimeBasis>,
1512}
1513
1514#[derive(Debug, Clone, PartialEq)]
1516pub struct Pair {
1517 pub continuity: Continuity,
1518 pub basis: Option<Basis>,
1520 pub rate: Result<Rate, NoRate>,
1521}
1522
1523impl Pair {
1524 #[must_use]
1527 pub fn unobservable(&self) -> Option<&'static str> {
1528 match (self.continuity, &self.rate) {
1529 (Continuity::Unobservable, Err(NoRate::WrapOrDecrease)) => Some("wrap_or_decrease"),
1530 (Continuity::Unobservable, _) => Some("incomparable"),
1531 _ => None,
1532 }
1533 }
1534}
1535
1536#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1539enum Change {
1540 Up(u64),
1542 Down,
1544 Outside,
1546}
1547
1548fn change(earlier: &Measure, later: &Measure) -> Option<Change> {
1554 match (earlier, later) {
1555 (
1556 Measure::Counter { value: a, width: w },
1557 Measure::Counter {
1558 value: b,
1559 width: wb,
1560 },
1561 ) => {
1562 if w != wb || *w == 0 || *w > FULL_WIDTH {
1563 return None;
1564 }
1565 if *w == FULL_WIDTH {
1566 return Some(if b < a {
1567 Change::Down
1568 } else {
1569 Change::Up(b - a)
1570 });
1571 }
1572 let mask = (1u64 << w) - 1;
1573 let d = b.wrapping_sub(*a) & mask;
1574 Some(if d < 1u64 << (w - 1) {
1575 Change::Up(d)
1576 } else {
1577 Change::Outside
1578 })
1579 }
1580 (Measure::Histogram(a), Measure::Histogram(b)) => {
1581 let same_bounds = a.bounds.len() == b.bounds.len()
1582 && a.bounds.iter().zip(&b.bounds).all(|(x, y)| x == y);
1583 if !same_bounds || a.counts.len() != b.counts.len() {
1584 return None;
1585 }
1586 let down = b.count < a.count || a.counts.iter().zip(&b.counts).any(|(x, y)| y < x);
1587 Some(if down { Change::Down } else { Change::Up(0) })
1588 }
1589 _ => None,
1590 }
1591}
1592
1593#[must_use]
1598pub fn elapsed(a: &Sampled<'_>, b: &Sampled<'_>) -> (i128, Option<TimeBasis>) {
1599 const MS: i128 = 1_000_000;
1600 if let (Some(x), Some(y)) = (&a.record, &b.record) {
1601 let timed = if x.scheduled() || y.scheduled() {
1602 TimeBasis::Scheduled {
1603 jitter_ms: x.jitter_ms() + y.jitter_ms(),
1604 }
1605 } else {
1606 TimeBasis::Measured
1607 };
1608 if x.frame == y.frame {
1609 let e = i128::from(y.after_ms) - i128::from(x.after_ms);
1610 return (e * MS, Some(timed));
1611 }
1612 if let (Some(p), Some(q)) = (x.at_ms, y.at_ms) {
1613 return ((i128::from(q) - i128::from(p)) * MS, Some(timed));
1614 }
1615 return (b.arrival_ns - a.arrival_ns, Some(TimeBasis::Arrival));
1616 }
1617 let e = if let (Some(x), Some(y)) = (a.timestamp_ms, b.timestamp_ms) {
1618 (i128::from(y) - i128::from(x)) * MS
1619 } else if let (Some(x), Some(y)) = (a.stamp_ns, b.stamp_ns) {
1620 y - x
1621 } else {
1622 b.arrival_ns - a.arrival_ns
1623 };
1624 (e, None)
1625}
1626
1627#[must_use]
1634pub fn stamp_ns(ntp64: u64) -> i128 {
1635 let secs = i128::from(ntp64 >> 32);
1636 let frac = ntp64 & 0xffff_ffff;
1638 let sub = (frac * 1_000_000_000).div_ceil(1 << 32);
1639 secs * 1_000_000_000 + i128::from(sub)
1640}
1641
1642#[must_use]
1644pub fn rate_per_s(d: u64, elapsed_ns: i128) -> f64 {
1645 d as f64 / (elapsed_ns as f64 / 1e9)
1646}
1647
1648#[must_use]
1654pub fn pair(
1655 earlier: &Sampled<'_>,
1656 later: &Sampled<'_>,
1657 unit: Option<&str>,
1658 presence: Option<&Presence<'_>>,
1659) -> Pair {
1660 let (ka, kb) = (earlier.value.kind(), later.value.kind());
1661 if !ka.is_cumulative() && !kb.is_cumulative() {
1662 return Pair {
1663 continuity: Continuity::NotAsked,
1664 basis: None,
1665 rate: Err(NoRate::Kind),
1666 };
1667 }
1668 let counters = ka == MetricKind::Counter && kb == MetricKind::Counter;
1669 let no_rate = |why: NoRate| -> Result<Rate, NoRate> {
1670 if counters {
1671 Err(why)
1672 } else {
1673 Err(NoRate::Kind)
1674 }
1675 };
1676 let Some(moved) = (ka == kb)
1677 .then(|| change(earlier.value, later.value))
1678 .flatten()
1679 else {
1680 return Pair {
1683 continuity: Continuity::Unobservable,
1684 basis: None,
1685 rate: Err(NoRate::Kind),
1686 };
1687 };
1688 let (continuity, basis) = match (epochs(earlier.epoch, later.epoch, presence), moved) {
1689 (Epochs::Same(via), Change::Down) => (Continuity::Decreased, Basis::Established(via)),
1690 (Epochs::Same(via), Change::Up(_)) => (Continuity::SameEpoch, Basis::Established(via)),
1691 (Epochs::Same(via), Change::Outside) => {
1692 return Pair {
1695 continuity: Continuity::Unobservable,
1696 basis: Some(Basis::Established(via)),
1697 rate: Err(NoRate::WrapOrDecrease),
1698 };
1699 }
1700 (Epochs::Different(via), _) => (Continuity::Reset, Basis::Established(via)),
1701 (Epochs::Unobservable, Change::Down | Change::Outside) => {
1702 (Continuity::Reset, Basis::Assumed)
1703 }
1704 (Epochs::Unobservable, Change::Up(_)) => (Continuity::SameEpoch, Basis::Assumed),
1705 };
1706 let rate = match (continuity, moved) {
1707 (Continuity::Reset, _) => no_rate(NoRate::Reset),
1708 (Continuity::Decreased, _) => no_rate(NoRate::Decreased),
1709 (Continuity::SameEpoch, Change::Up(d)) if counters => {
1710 let (e, timed) = elapsed(earlier, later);
1711 if e <= 0 {
1712 Err(NoRate::Elapsed)
1713 } else {
1714 Ok(Rate {
1715 per_s: rate_per_s(d, e),
1716 unit: unit.map(|u| format!("{u}/s")),
1717 elapsed_ns: e,
1718 basis: timed,
1719 })
1720 }
1721 }
1722 _ => Err(NoRate::Kind),
1723 };
1724 Pair {
1725 continuity,
1726 basis: Some(basis),
1727 rate,
1728 }
1729}
1730
1731#[cfg(test)]
1732mod tests {
1733 use super::*;
1734 use serde_json::json;
1735
1736 fn ann(pairs: &[(&str, Value)]) -> BTreeMap<String, Value> {
1737 pairs
1738 .iter()
1739 .map(|(k, v)| ((*k).to_owned(), v.clone()))
1740 .collect()
1741 }
1742
1743 fn point() -> TypeView<'static> {
1744 TypeView::Json {
1745 name: POINT,
1746 schema: PUBLISHED[0],
1747 root: None,
1748 }
1749 }
1750
1751 #[test]
1752 fn a_kind_on_a_counter_type_is_declared() {
1753 let root = json!({"type": "integer", "minimum": 0});
1754 let ty = TypeView::Json {
1755 name: "Counter",
1756 schema: "sha256:00",
1757 root: Some(&root),
1758 };
1759 let d = declaration(
1760 Kind::Stream,
1761 &ann(&[(KIND, json!("counter")), (UNIT, json!("By"))]),
1762 Some(&ty),
1763 None,
1764 );
1765 let Declaration::Declared(d) = d else {
1766 panic!("{d:?}")
1767 };
1768 assert_eq!(d.kind, Some(MetricKind::Counter));
1769 assert_eq!(d.unit.as_deref(), Some("By"));
1770 assert_eq!(d.carrier, Carrier::Bare);
1771 }
1772
1773 #[test]
1774 fn a_point_needs_no_kind_and_is_known_by_its_id() {
1775 let d = declaration(Kind::Stream, &BTreeMap::new(), Some(&point()), None);
1776 assert_eq!(d.declared().map(|d| d.carrier), Some(Carrier::Point));
1777 let other = TypeView::Json {
1778 name: POINT,
1779 schema: "sha256:00",
1780 root: None,
1781 };
1782 assert_eq!(
1783 declaration(Kind::Stream, &BTreeMap::new(), Some(&other), None),
1784 Declaration::NotThisProfiles
1785 );
1786 }
1787
1788 #[test]
1789 fn a_counter_is_read_exactly() {
1790 let d = declaration(
1791 Kind::Stream,
1792 &ann(&[(KIND, json!("counter"))]),
1793 Some(&TypeView::Json {
1794 name: "C",
1795 schema: "x",
1796 root: Some(&json!({"type": "integer"})),
1797 }),
1798 None,
1799 );
1800 let at = |v: Value| {
1801 let datum = Datum::from_json(&v);
1802 check(
1803 &d,
1804 &Payload::Decoded {
1805 value: &datum,
1806 attachment: None,
1807 },
1808 )
1809 .conformance
1810 };
1811 assert_eq!(at(json!(u64::MAX)), Conformance::Conforms);
1812 assert_eq!(
1813 at(json!(18_446_744_073_709_551_616.0)),
1814 Conformance::DoesNot(vec![Problem::OutOfRange])
1815 );
1816 assert_eq!(at(json!(5.0)), Conformance::Conforms);
1817 assert_eq!(
1818 at(json!(5.5)),
1819 Conformance::DoesNot(vec![Problem::WrongType])
1820 );
1821 }
1822
1823 #[test]
1824 fn a_decrease_is_a_reset_unless_one_epoch_is_established() {
1825 let (a, b) = (Measure::counter(10), Measure::counter(3));
1826 let s = |v, e| Sampled {
1827 value: v,
1828 epoch: e,
1829 timestamp_ms: None,
1830 stamp_ns: None,
1831 arrival_ns: 0,
1832 record: None,
1833 };
1834 let p = pair(&s(&a, None), &s(&b, None), None, None);
1835 assert_eq!(
1836 (p.continuity, p.basis),
1837 (Continuity::Reset, Some(Basis::Assumed))
1838 );
1839 let p = pair(&s(&a, Some("e")), &s(&b, Some("e")), None, None);
1840 assert_eq!(p.continuity, Continuity::Decreased);
1841 assert_eq!(p.rate, Err(NoRate::Decreased));
1842 }
1843
1844 #[test]
1845 fn the_rate_is_the_formula() {
1846 let (a, b) = (Measure::counter(0), Measure::counter(1_000));
1847 let s = |v, t| Sampled {
1848 value: v,
1849 epoch: None,
1850 timestamp_ms: Some(t),
1851 stamp_ns: None,
1852 arrival_ns: 0,
1853 record: None,
1854 };
1855 let p = pair(&s(&a, 0), &s(&b, 2_000), Some("By"), None);
1856 assert_eq!(
1857 p.rate,
1858 Ok(Rate {
1859 per_s: 500.0,
1860 unit: Some("By/s".into()),
1861 elapsed_ns: 2_000_000_000,
1862 basis: None,
1863 })
1864 );
1865 }
1866
1867 #[test]
1868 fn a_root_follows_its_refs_across_files_with_outer_keywords_winning() {
1869 let art = |name: &str, doc: Value| Artifact {
1870 kind: crate::schema::SchemaKind::JsonSchema,
1871 name: name.to_owned(),
1872 data: ArtifactData::Json(doc),
1873 };
1874 let a = art(
1875 "a",
1876 json!({"$defs": {
1877 "Count": {"$ref": "#/$defs/Inner", "description": "outer"},
1878 "Inner": {"$ref": "b.json#/$defs/Base", "minimum": 1},
1879 "Loop": {"$ref": "#/$defs/Loop"},
1880 }}),
1881 );
1882 let b = art(
1883 "b",
1884 json!({"$defs": {"Base": {"type": "integer", "minimum": 0}}}),
1885 );
1886 let arts = BTreeMap::from([("sha256:a".to_owned(), a), ("sha256:b".to_owned(), b)]);
1887 assert_eq!(
1888 root_schema(&arts, "sha256:a", "Count"),
1889 Some(json!({"type": "integer", "minimum": 1, "description": "outer"}))
1890 );
1891 assert_eq!(root_schema(&arts, "sha256:a", "Loop"), None, "a loop ends");
1892 assert_eq!(root_schema(&arts, "sha256:a", "Missing"), None);
1893 }
1894
1895 #[test]
1896 fn units_and_epochs_have_their_lengths() {
1897 assert!(is_unit("dBm") && is_unit("bit/s") && !is_unit("") && !is_unit("m s"));
1898 assert!(!is_unit(&"x".repeat(65)) && is_unit(&"x".repeat(64)));
1899 assert!(is_epoch(&"é".repeat(64)) && !is_epoch(&"é".repeat(65)) && !is_epoch(""));
1900 }
1901}