Skip to main content

zenkey_model/
telemetry.rs

1//! `telemetry.v1`: what a metric is, and how a reader reads one
2//! (`spec/profiles/telemetry/v1.md`, #819).
3//!
4//! The profile's session-free half: the declaration read from a resolved
5//! resource (§2.2, §2.4), one sample's conformance and the member's kind and
6//! unit (§2.5, §2.6), and the continuity and rate of a pair of samples
7//! (§2.9–§2.11).
8//!
9//! ```text
10//! declaration(kind, annotations, type, attachment) ─▶ declared │ invalid [reasons] │ ignored │ not this profile's
11//! check(declaration, payload)                      ─▶ conforms │ does_not [reasons] │ unobservable │ not_asked, + kind, unit, reading
12//! pair(earlier, later, presence)                   ─▶ same_epoch │ reset │ decreased │ unobservable │ not_asked, + epoch, rate
13//! ```
14//!
15//! There is no I/O and no clock here. A reader decodes a payload into a
16//! [`Datum`] (JSON's data model, or CBOR's with its byte strings and its
17//! non-finite floats), measures what it saw of presence and when each
18//! sample arrived, and hands them over as values. The owner's in-band
19//! epoch is the runtime's.
20//!
21//! [`decode`] reads a sample's bytes as §2.6 reads them (text 0.2): strict
22//! JSON, and CBOR with its bignums, into a [`Datum`] whose integers are
23//! exact. [`wire`] is the standard schema's types as an owner puts them:
24//! the Point, its tagged value and the histogram, with serde (#819, TB).
25//! [`stamp_ns`] is a state sample's stamp in nanoseconds, as zenoh reads it
26//! (§2.11, 0.2).
27//!
28//! `telemetry.v2` (`spec/profiles/telemetry/v2.md`, #983 T1) restates these
29//! rules by reference and binds a frame's fields to series ([`frames`]). A
30//! counter carries its width ([`Measure::Counter`]), so [`pair`] reads a
31//! narrow one in a serial window (v2 §2.20), and a frame's sample carries
32//! its record's time ([`RecordTime`]), so a rate names its basis
33//! ([`TimeBasis`], v2 §2.21). A v1 sample is a 64-bit counter with no
34//! record time, and reads as before.
35
36use 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
49/// The profile's id, as a contract lists it in `uses`.
50pub const PROFILE: &str = "telemetry.v1";
51
52/// `telemetry.v2`'s id (#983 T1): v1's rules by reference, and a frame
53/// resource's fields bound to series by `telemetry.series` (v2 §2.16).
54pub const PROFILE_V2: &str = "telemetry.v2";
55
56/// The profile's name, as an annotation key's prefix carries it.
57pub const NAME: &str = "telemetry";
58
59/// `telemetry.kind` (§4).
60pub const KIND: &str = "telemetry.kind";
61/// `telemetry.unit` (§4).
62pub const UNIT: &str = "telemetry.unit";
63/// `telemetry.buckets` (§4).
64pub const BUCKETS: &str = "telemetry.buckets";
65/// `telemetry.semantic` (§4).
66pub const SEMANTIC: &str = "telemetry.semantic";
67
68/// `telemetry.series` (v2 §4): a frame resource's fields, each bound to a
69/// series.
70pub const SERIES: &str = "telemetry.series";
71
72/// The published vocabulary (§4): the keys under `telemetry.`, which W105
73/// reads in place of core Appendix D's interim row (core 0.35).
74pub const VOCABULARY: &[&str] = &["kind", "unit", "buckets", "semantic"];
75
76/// `telemetry.v2`'s vocabulary (v2 §4): v1's four keys and `series`, which
77/// W105 reads for a contract that uses `telemetry.v2`.
78pub const VOCABULARY_V2: &[&str] = &["kind", "unit", "buckets", "semantic", "series"];
79
80/// Whether `c` uses `telemetry.v2` (v2 §1): its frame resources' fields
81/// are series by their `telemetry.series`, and every other resource reads
82/// as `telemetry.v1` reads it.
83#[must_use]
84pub fn uses_v2(c: &Contract) -> bool {
85    c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
86}
87
88/// A v1 counter's width: every count from 0 to 2^64 − 1 (§2.7).
89pub const FULL_WIDTH: u32 = 64;
90
91/// The standard schema's stem (§3): `telemetry.v1.json`.
92pub const SCHEMA_STEM: &str = "telemetry.v1";
93/// The Point's type name (§2.3).
94pub const POINT: &str = "telemetry.v1.Point";
95/// The tagged value's type name (§2.3).
96pub const VALUE: &str = "telemetry.v1.Value";
97/// The histogram's type name (§2.3, §2.8).
98pub const HISTOGRAM: &str = "telemetry.v1.Histogram";
99/// The in-band epoch's type name (§2.3, §2.9).
100pub const EPOCH: &str = "telemetry.v1.Epoch";
101
102/// The standard schema's artifact ids the profile publishes (§3), oldest
103/// first: ZenSight's file before the profile, then text 0.1's. A type of
104/// one of these artifacts is the profile's (§2.3).
105pub const PUBLISHED: &[&str] = &[
106    "sha256:3d6276dd302873ca5938013a44d460267971123fd25500f189e30be718f9dc1e",
107    "sha256:715ce537b2150beb3863f0e5cd356281357f7ec56d93625ee64e14f0045629e9",
108];
109
110/// The longest unit and the longest in-band epoch, in characters (§2.2,
111/// §2.6).
112pub const MAX_UNIT: usize = 64;
113pub const MAX_EPOCH: usize = 64;
114
115/// Whether `id` is one of the standard schema's published artifact ids.
116#[must_use]
117pub fn is_published(id: &str) -> bool {
118    PUBLISHED.contains(&id)
119}
120
121/// A metric's kind (§2.2), one spelling on the annotation and on the wire.
122#[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    /// The kind spelled `s`, compared byte for byte.
155    #[must_use]
156    pub fn parse(s: &str) -> Option<Self> {
157        Self::ALL.into_iter().find(|k| k.as_str() == s)
158    }
159
160    /// Counters and histograms have an epoch, a continuity and, for a
161    /// counter, a rate (§2.7–§2.11).
162    #[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/// A presentation hint (§2.2), never a finding.
175#[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/// A unit (§2.2): 1 to 64 characters, each printable ASCII from 0x21 to
220/// 0x7E. Never parsed or converted.
221#[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/// An in-band epoch (§2.6, §2.9): a string of 1 to 64 characters, counted
227/// as Unicode code points, as JSON Schema's `minLength`/`maxLength` count.
228#[must_use]
229pub fn is_epoch(s: &str) -> bool {
230    (1..=MAX_EPOCH).contains(&s.chars().count())
231}
232
233// ---------------------------------------------------------------------------
234// The declaration (§2.2, §2.4)
235// ---------------------------------------------------------------------------
236
237/// A resource's type, as a reader of the declaration sees it (§2.4).
238#[derive(Debug, Clone, Copy, PartialEq)]
239pub enum TypeView<'a> {
240    /// A JSON Schema type: its name, its artifact's id, and its root
241    /// schema, `$ref`s followed (core §9.8), when the reader resolved it.
242    Json {
243        name: &'a str,
244        schema: &'a str,
245        root: Option<&'a Value>,
246    },
247    /// A raw type, of any media type.
248    Raw,
249    /// A protobuf message.
250    Protobuf,
251    /// A packed record (core §7.6), which this profile's reader does not
252    /// read yet: it carries no metric kind.
253    Packed,
254}
255
256impl TypeView<'_> {
257    /// Whether this is the profile's type `name`, by its artifact's id
258    /// (§2.3).
259    #[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/// What a declaration's samples are (§2.4).
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum Carrier {
268    /// The profile's Point, which says its own kind.
269    Point,
270    /// A bare value of the declared kind.
271    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/// Where a member's in-band epoch rides (§2.4, §2.9).
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum EpochIn {
287    /// The Point's `epoch`.
288    Point,
289    /// The sample's attachment, typed `telemetry.v1.Epoch`.
290    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/// A valid declaration (§2.2).
304#[derive(Debug, Clone, PartialEq)]
305pub struct Declared {
306    pub carrier: Carrier,
307    /// The declared kind; `None` for a Point that says its own.
308    pub kind: Option<MetricKind>,
309    pub unit: Option<String>,
310    /// The bounds, as doubles (§2.2), exactly when the kind is `histogram`.
311    pub buckets: Option<Vec<f64>>,
312    pub semantic: Option<Semantic>,
313    /// Where an in-band epoch rides, if anywhere.
314    pub epoch: Option<EpochIn>,
315}
316
317/// Why a declaration is invalid (§2.2), in the order a reader checks.
318#[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    /// The reason in words, for a linter's or a tool's message.
346    #[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/// What a reader reads of a resolved resource (§2.2, §2.4).
374#[derive(Debug, Clone, PartialEq)]
375pub enum Declaration {
376    Declared(Declared),
377    /// The reasons, in §2.2's order.
378    Invalid(Vec<Invalid>),
379    /// An event or an operation that writes a key of the vocabulary: it
380    /// means nothing there (§2.1, §2.2).
381    Ignored,
382    /// Not a metric resource: no key of the vocabulary, and not the Point,
383    /// or an event or an operation that writes none.
384    NotThisProfiles,
385}
386
387impl Declaration {
388    /// The fixture's token.
389    #[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
408/// One key's value, as §2.2 reads it.
409enum 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
433/// `telemetry.buckets`' value (§2.2): a non-empty array of finite numbers,
434/// strictly ascending as doubles.
435fn 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
445/// A root schema's `type` as a set of names (core §7.3); empty when it has
446/// none, or one that is not a name or a list of names.
447fn 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/// Whether a type carries `kind` (§2.4).
462#[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/// Reads the declaration of a resource of `kind` from its resolved
491/// annotations (core §9.3), its type and its attachment's type (§2.2,
492/// §2.4). `ty` is `None` for an operation, which has no payload type.
493#[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/// [`declaration`] of a resource of a contract: its type's root schema
574/// resolved from the contract's artifacts ([`root_schema`]).
575#[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/// The root schema of the JSON Schema type `name` in the artifact `schema`
599/// (§2.4): `$defs/<name>`, its `$ref`s followed across the artifacts by
600/// stem, as core §9.8 follows them, a keyword beside a `$ref` added to its
601/// target and an outer one taking the place of the target's own. `None`
602/// when a `$ref` resolves to nothing, or the chain runs past 64 steps.
603#[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// ---------------------------------------------------------------------------
652// A decoded value (§2.6)
653// ---------------------------------------------------------------------------
654
655/// A sample's decoded data item (§2.6): JSON's data model, plus what CBOR
656/// adds, byte strings and non-finite floats. Integers are exact.
657#[derive(Debug, Clone, PartialEq)]
658pub enum Datum {
659    Null,
660    Bool(bool),
661    /// An integer: JSON text with no fraction and no exponent, CBOR's major
662    /// types 0 and 1, or a bignum (tags 2 and 3, 0.2).
663    Int(i128),
664    /// An integer beyond i128 (0.2): JSON text within the double's finite
665    /// range, or a CBOR bignum of any length, held as its nearest double
666    /// (infinite past the double's range). No range of §2.6 admits one:
667    /// as an integer it reads beyond every bound, as a number it is that
668    /// double.
669    BigInt(f64),
670    /// A float: JSON text with a fraction or an exponent, a CBOR float.
671    Float(f64),
672    Text(String),
673    Bytes(Vec<u8>),
674    Array(Vec<Datum>),
675    Map(BTreeMap<String, Datum>),
676}
677
678impl Datum {
679    /// A JSON value as a datum: an integer JSON number exactly, any other
680    /// as its double. `serde_json` holds no integer beyond 64 bits, and
681    /// keeps the last of two duplicate members: a sample's bytes are read by
682    /// [`Datum::from_json_bytes`], strict JSON (§2.6, 0.2).
683    #[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    /// A CBOR data item as a datum, keeping byte strings and non-finite
708    /// floats (§2.6); a tag reads as its content. `None` for a map key that
709    /// is not text, or a value with no datum.
710    #[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    /// One JSON text, as strict JSON reads it (§2.6, 0.2; [`decode::json`]):
741    /// `None` when the bytes are not one, the sample `undecodable`.
742    #[must_use]
743    pub fn from_json_bytes(bytes: &[u8]) -> Option<Self> {
744        decode::json(bytes)
745    }
746
747    /// One CBOR data item and nothing after it, its bignums integers (§2.6,
748    /// 0.2; [`decode::cbor`]): `None` when the bytes are not one.
749    #[must_use]
750    pub fn from_cbor_bytes(bytes: &[u8]) -> Option<Self> {
751        decode::cbor(bytes)
752    }
753
754    /// A sample's bytes as `encoding` carries them: JSON unless CBOR.
755    #[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    /// An attachment's bytes as the datum a reader checks (§2.6 check 2,
764    /// 0.2): decoded as `encoding` carries it, or, when they do not decode,
765    /// the bytes themselves, which are no string, so an Epoch attachment
766    /// that does not decode is an epoch present and not a string:
767    /// `epoch_invalid`, the sample still read. Zero bytes are such an
768    /// attachment.
769    #[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    /// A number, as a double (an integer to its nearest).
782    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    /// An integer, as JSON Schema's `integer` reads one: an integer, or an
791    /// integral finite float, the integer it equals. `None` for any other
792    /// value. An integral float beyond ±2^127 saturates to `i128`'s bound,
793    /// which is beyond every range §2.6 asks of an integer, as its value is.
794    fn integer(&self) -> Option<i128> {
795        match self {
796            Self::Int(i) => Some(*i),
797            // `as` saturates a float to the integer's bound.
798            Self::Float(f) if f.is_finite() && f.fract() == 0.0 => Some(*f as i128),
799            // Beyond i128: past every bound, on its side.
800            Self::BigInt(f) => Some(if *f < 0.0 { i128::MIN } else { i128::MAX }),
801            _ => None,
802        }
803    }
804}
805
806// ---------------------------------------------------------------------------
807// A sample's conformance (§2.5, §2.6)
808// ---------------------------------------------------------------------------
809
810/// A sample's payload, as the reader received it.
811#[derive(Debug, Clone, Copy, PartialEq)]
812pub enum Payload<'a> {
813    /// The decoded data item, and the decoded attachment, if any.
814    Decoded {
815        value: &'a Datum,
816        attachment: Option<&'a Datum>,
817    },
818    /// Bytes the core could not decode (§2.6).
819    Undecodable,
820}
821
822/// Why a sample does not conform (§2.6), in the order a reader checks.
823#[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    /// The reason in words, for a tool's message.
859    #[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/// Why a question about a sample was put and could not be answered, or
885/// was not asked (§2.6, §5).
886#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
887pub enum Unasked {
888    /// Unobservable: the declaration is invalid (§2.2).
889    DeclarationInvalid,
890    /// Unobservable: the core could not decode the sample.
891    Undecodable,
892    /// Not asked: not a metric resource.
893    NotThisProfiles,
894    /// Not asked: an event or an operation.
895    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/// The answer to "does this sample conform?" (§2.6). `DoesNot` is the
911/// finding.
912#[derive(Debug, Clone, PartialEq, Eq)]
913pub enum Conformance {
914    Conforms,
915    /// The reasons, in §2.6's order.
916    DoesNot(Vec<Problem>),
917    Unobservable(Unasked),
918    NotAsked(Unasked),
919}
920
921impl Conformance {
922    /// The fixture's token.
923    #[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/// Where a member's kind or unit came from (§2.5).
935#[derive(Debug, Clone, Copy, PartialEq, Eq)]
936pub enum Source {
937    /// The resource's annotation.
938    Declared,
939    /// The Point: its tag, or its `unit`.
940    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/// A histogram's value (§2.8).
954#[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/// A conforming sample's value, by its kind.
963#[derive(Debug, Clone, PartialEq)]
964pub enum Measure {
965    /// A count modulo 2^`width`: a v1 counter's width is 64
966    /// ([`FULL_WIDTH`]), a frame's counter field's its declared width, from
967    /// 1 to 64 (core §7.6, v2 §2.20).
968    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    /// A 64-bit counter, as every v1 carrier holds one (§2.7).
981    #[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/// What a conforming sample says: its value, its measurement time (a
1003/// Point's `timestamp`) and its in-band epoch.
1004#[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/// One sample, read (§2.5, §2.6).
1012#[derive(Debug, Clone, PartialEq)]
1013pub struct Checked {
1014    pub conformance: Conformance,
1015    /// The member's kind as this sample gives it, or `None`: unobservable
1016    /// or not this profile's (§2.5).
1017    pub kind: Option<(MetricKind, Source)>,
1018    /// The member's unit as this sample gives it, or `None`: unknown,
1019    /// never dimensionless (§2.5).
1020    pub unit: Option<(String, Source)>,
1021    /// The sample's value, when it conforms.
1022    pub reading: Option<Reading>,
1023}
1024
1025/// A Point, its shape checked (§2.6, check 1).
1026struct 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
1063/// A count (§2.6, check 7): `Ok` in 0 to 2^64−1, `Err` out of range.
1064fn count(i: i128) -> Result<u64, ()> {
1065    u64::try_from(i).map_err(|_| ())
1066}
1067
1068/// The value checks (§2.6, checks 6 to 12) of `v` as a `kind`, a Point's
1069/// value or a bare one, against the declared bounds of a histogram.
1070fn 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/// Reads one sample of a member whose resource's declaration is `decl`
1199/// (§2.5, §2.6): its conformance, the member's kind and unit as the sample
1200/// gives them, and its value when it conforms.
1201#[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// ---------------------------------------------------------------------------
1290// A pair: its continuity and its rate (§2.9–§2.11)
1291// ---------------------------------------------------------------------------
1292
1293/// One sample of a pair, as the reader holds it (§2.10, §2.11).
1294#[derive(Debug, Clone, Copy, PartialEq)]
1295pub struct Sampled<'a> {
1296    /// The conforming sample's value; its kind is the sample's.
1297    pub value: &'a Measure,
1298    /// Its in-band epoch (§2.9), if it carries one.
1299    pub epoch: Option<&'a str>,
1300    /// The Point's `timestamp`, for a Point.
1301    pub timestamp_ms: Option<i64>,
1302    /// The owner's stamp, in nanoseconds since the Unix epoch, for state:
1303    /// [`stamp_ns`] of its NTP64 value (0.2).
1304    pub stamp_ns: Option<i128>,
1305    /// When the reader received it, in nanoseconds on its monotonic clock.
1306    pub arrival_ns: i128,
1307    /// A frame's sample: its record's time (v2 §2.21). `None` for every v1
1308    /// carrier, whose time base is §2.11's list.
1309    pub record: Option<RecordTime>,
1310}
1311
1312/// A frame record's time, as a frame's sample carries it (v2 §2.21, core
1313/// §7.7): what [`crate::frame::RecordRead`] reads, and which frame of the
1314/// key the record came in.
1315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1316pub struct RecordTime {
1317    /// Which frame of its key it came in, as its reader counts them: two
1318    /// records with one number came in one frame, and are timed by their
1319    /// offsets from its record 0.
1320    pub frame: u64,
1321    pub when: crate::frame::When,
1322    /// After record 0: its measured offset, or `step_ms` × its index when
1323    /// scheduled. 0 for record 0.
1324    pub after_ms: u64,
1325    /// Its instant in milliseconds from the deployment epoch, `None` when
1326    /// its frame's time is unknown.
1327    pub at_ms: Option<u64>,
1328}
1329
1330impl RecordTime {
1331    /// How far its time may lie from the instant it gives: a scheduled
1332    /// record's `jitter_ms`, else 0.
1333    #[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/// What a frame's rate is timed by (v2 §2.21). A v1 rate names none.
1347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1348pub enum TimeBasis {
1349    /// Both records' times measured on the owner's clocks.
1350    Measured,
1351    /// At least one record's time scheduled: the elapsed time is exact to
1352    /// within `jitter_ms` either way, the sum of the scheduled records'
1353    /// `jitter_ms`. Never a measured rate.
1354    Scheduled { jitter_ms: u64 },
1355    /// The reader's arrivals: a record's time was unknown.
1356    Arrival,
1357}
1358
1359impl TimeBasis {
1360    /// The fixture's token.
1361    #[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/// What the reader observed of the owning service's instance tokens, or of
1372/// a member's tokens for a template that declares `epoch` (§2.9).
1373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1374pub struct Presence<'a> {
1375    /// One instance (or member epoch) alone, without a loss on the presence
1376    /// view, from before the earlier arrival to after the later one's.
1377    pub alone_throughout: bool,
1378    /// The only instance present at the earlier arrival; `None` when there
1379    /// was none, several, or the reader cannot tell.
1380    pub earlier: Option<&'a str>,
1381    /// The only instance present at the later arrival, likewise.
1382    pub later: Option<&'a str>,
1383}
1384
1385/// How an epoch was established (§2.9).
1386#[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/// The epoch evidence for a pair (§2.9).
1403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1404pub enum Epochs {
1405    Same(Via),
1406    Different(Via),
1407    Unobservable,
1408}
1409
1410/// §2.9: in-band when both carry an epoch, else presence, else
1411/// unobservable.
1412#[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/// The answer to a pair's continuity (§2.10). `Decreased` is the finding.
1437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1438pub enum Continuity {
1439    SameEpoch,
1440    Reset,
1441    Decreased,
1442    /// The two samples cannot be compared (`incomparable`: their kinds,
1443    /// their widths, or a histogram's bounds or length differ), or a narrow
1444    /// counter's change within one epoch lies outside its serial window
1445    /// (`wrap_or_decrease`, v2 §2.20). [`Pair::unobservable`] says which.
1446    Unobservable,
1447    /// Neither sample is a counter or a histogram (`kind`).
1448    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/// Whether a pair's epoch was established, and how, or assumed (§2.10).
1465#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1466pub enum Basis {
1467    Established(Via),
1468    Assumed,
1469}
1470
1471/// Why a pair has no rate (§2.11).
1472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1473pub enum NoRate {
1474    /// Not asked: the pair is not of two counters, an incomparable pair
1475    /// included, since two counters are always comparable (0.2, F-146).
1476    Kind,
1477    Reset,
1478    Decreased,
1479    /// The elapsed time is 0 or less.
1480    Elapsed,
1481    /// A narrow counter's change within one epoch lies outside its serial
1482    /// window: a wrap or a decrease, which the two values cannot tell apart
1483    /// (v2 §2.20).
1484    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/// A counter's rate over a pair (§2.11).
1501#[derive(Debug, Clone, PartialEq)]
1502pub struct Rate {
1503    /// Per second, by §2.11's formula.
1504    pub per_s: f64,
1505    /// The counter's unit followed by `/s`; `None` when it is unknown.
1506    pub unit: Option<String>,
1507    /// The elapsed time the rate is over, in nanoseconds, above 0.
1508    pub elapsed_ns: i128,
1509    /// A frame's rate's time basis (v2 §2.21); `None` for a v1 pair, timed
1510    /// by §2.11's list.
1511    pub basis: Option<TimeBasis>,
1512}
1513
1514/// A pair, judged (§2.10, §2.11).
1515#[derive(Debug, Clone, PartialEq)]
1516pub struct Pair {
1517    pub continuity: Continuity,
1518    /// `None` when the epoch was not asked of the pair.
1519    pub basis: Option<Basis>,
1520    pub rate: Result<Rate, NoRate>,
1521}
1522
1523impl Pair {
1524    /// Why an unobservable pair is: `incomparable` (§2.10), or
1525    /// `wrap_or_decrease` (v2 §2.20). `None` for any other continuity.
1526    #[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/// How a later value moved from an earlier one of one member (§2.10, v2
1537/// §2.20).
1538#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1539enum Change {
1540    /// No decrease: a counter's increase by this much (0 for a histogram).
1541    Up(u64),
1542    /// A decrease (§2.10).
1543    Down,
1544    /// A narrow counter's change outside its serial window (v2 §2.20).
1545    Outside,
1546}
1547
1548/// How `later` moved from `earlier` (§2.10); `None` when the two cannot be
1549/// compared: their kinds, a counter's widths, or a histogram's bounds or
1550/// length differ. A counter of width w below 64 is read in a serial window
1551/// (v2 §2.20): the increase d = (b − a) mod 2^w when d < 2^(w−1), else
1552/// outside it. At width 64, b below a is a decrease.
1553fn 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/// The elapsed time between two samples, in nanoseconds, and what it is
1594/// timed by: two frame records by their times (v2 §2.21), else the first
1595/// time base of §2.11's list both have. [`pair`] times a rate by it; a
1596/// reader shows it for a pair with no rate too.
1597#[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/// A state sample's stamp in nanoseconds (§2.11, 0.2, F-142), from its raw
1628/// NTP64 value: the seconds (the high 32 bits) times 10^9, plus the 32-bit
1629/// fraction times 10^9 divided by 2^32, rounded up. uhlc's
1630/// `NTP64::as_nanos`, which zenoh reads a stamp's time with; a pair's
1631/// elapsed time is the later stamp's nanoseconds less the earlier's, each
1632/// converted alone.
1633#[must_use]
1634pub fn stamp_ns(ntp64: u64) -> i128 {
1635    let secs = i128::from(ntp64 >> 32);
1636    // Below 2^32 times 10^9, so below 2^62: no overflow in a u64.
1637    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/// §2.11's rate: `double(d) / (double(e) / 1e9)`, rounding to nearest.
1643#[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/// Judges a pair of conforming samples of one member, in arrival order
1649/// (§2.9–§2.11). `unit` is the counter's unit (§2.5), for the rate's. A
1650/// counter narrower than 64 bits is read in its serial window, and two
1651/// frame records are timed by their records (`telemetry.v2` §2.20,
1652/// §2.21).
1653#[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        // Incomparable (§2.10): two kinds, two counter widths (v2 §2.20),
1681        // or two histograms' bounds; no rate is asked of it (§2.11).
1682        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            // A wrap or a decrease within one epoch: the values cannot say
1693            // which (v2 §2.20).
1694            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}