Skip to main content

zenkey_model/telemetry/
frames.rs

1//! `telemetry.v2`'s frames (`spec/profiles/telemetry/v2.md` §2.16–§2.21,
2//! #983 T1): a frame resource's fields bound to metric series.
3//!
4//! ```text
5//! series(fields, annotations, mirror) ─▶ declared [FieldSeries…] │ invalid [problems] │ ignored │ not this profile's
6//! reading_of(series, field, slot, state) ─▶ sample │ held │ absent │ owner_error │ beyond_range │ unnamed │ unknown
7//! Fold::apply(layout, series, stamp, frame, arrival) ─▶ each record's readings, each counter sample's pair
8//! ```
9//!
10//! - **The declaration** is the frame resource's `telemetry.series`
11//!   ([`series`], [`series_of`]): each entry binds one field to a series,
12//!   inline (`{kind, unit, semantic}`) or by a **mirror**, a non-frame
13//!   metric resource of the interface with no parameter, whose `telemetry.v1`
14//!   declaration lends its kind, unit and semantic (v2 §2.16). A field's
15//!   packed type carries the kind ([`carries`]).
16//! - **The series** is (frame key, field), never the mirrored key (v2
17//!   §2.17): the mirror is a label.
18//! - **A sample** is a record that includes the field with a value
19//!   ([`reading_of`], v2 §2.18). An omitted field holds a value, `known`
20//!   by no change or `within` its deadband (core §7.7), and is no sample.
21//!   A reserved code, an absent field, the escape and an unknown field are
22//!   no value, never 0.
23//! - **The epoch is the run** (v2 §2.19): a [`Fold`] reads one key's frames
24//!   through a [`crate::frame::Reader`], and two samples are of one epoch
25//!   when no frame between them was read as a rewind or another run's.
26//! - **A counter** carries its field's width ([`Measure::Counter`]), and
27//!   [`crate::telemetry::pair`] reads a narrow one in a serial window (v2
28//!   §2.20). Its rate is timed by its records ([`RecordTime`], v2 §2.21).
29
30use std::collections::BTreeMap;
31use std::fmt;
32
33use serde_json::Value;
34
35use crate::contract::{Body, Contract, Resource};
36use crate::frame::{self, Applied, FieldState, Frame, Layout, Slot, Unknown};
37use crate::packed::{Field, FieldKind};
38use crate::wire::{Seq, Stamp};
39
40use super::{
41    Declaration, Measure, MetricKind, Pair, RecordTime, SERIES, Sampled, Semantic, is_unit, pair,
42};
43
44/// The members an inline series may hold (v2 §2.16).
45pub const INLINE: &[&str] = &["kind", "unit", "semantic"];
46
47/// One field's series (v2 §2.16, §2.17): which field, and the kind, unit
48/// and semantic its entry gives it.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct FieldSeries {
51    /// The field's name.
52    pub field: String,
53    /// The field's index in the record type.
54    pub index: usize,
55    /// `counter`, `gauge`, `boolean` or `text`: what a field carries.
56    pub kind: MetricKind,
57    pub unit: Option<String>,
58    pub semantic: Option<Semantic>,
59    /// The mirrored resource's template, for a mirror; `None` inline. A
60    /// label, never the series' identity (v2 §2.17).
61    pub mirror: Option<String>,
62    /// A counter field's width, from 1 to 64; `None` for any other kind.
63    pub width: Option<u32>,
64}
65
66/// Why a frame resource's `telemetry.series` is invalid (v2 §2.16), in the
67/// order a reader checks each entry.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub enum Reason {
70    /// The entry names no field of the record type.
71    SeriesField,
72    /// The annotation is not a non-empty table; or an entry is neither a
73    /// string nor a table, or holds a member other than `kind`, `unit` and
74    /// `semantic`.
75    SeriesValue,
76    KindValue,
77    UnitValue,
78    SemanticValue,
79    /// The mirror names no single resource of the interface, or a frame
80    /// resource, a template with a parameter, or no metric resource.
81    MirrorMissing,
82    /// The mirror's own declaration is invalid (v1 §2.2).
83    MirrorInvalid,
84    /// Nothing gives the series a kind: an inline series with no `kind`,
85    /// or a mirror that declares none (a Point with no `telemetry.kind`).
86    KindMissing,
87    /// The field's type cannot carry the series' kind.
88    NotACarrier,
89}
90
91impl Reason {
92    /// The fixture's token.
93    #[must_use]
94    pub const fn as_str(self) -> &'static str {
95        match self {
96            Self::SeriesValue => "series_value",
97            Self::SeriesField => "series_field",
98            Self::KindValue => "kind_value",
99            Self::UnitValue => "unit_value",
100            Self::SemanticValue => "semantic_value",
101            Self::KindMissing => "kind_missing",
102            Self::MirrorMissing => "mirror_missing",
103            Self::MirrorInvalid => "mirror_invalid",
104            Self::NotACarrier => "not_a_carrier",
105        }
106    }
107
108    /// The reason in words, for a linter's or a tool's message.
109    #[must_use]
110    pub const fn says(self) -> &'static str {
111        match self {
112            Self::SeriesValue => {
113                "telemetry.series is not a table of fields, each a mirror or {kind, unit, semantic}"
114            }
115            Self::SeriesField => "the entry names no field of the frame's record type",
116            Self::KindValue => "kind is not one of the six kinds",
117            Self::UnitValue => "unit is not 1 to 64 printable ASCII characters (0x21 to 0x7E)",
118            Self::SemanticValue => "semantic is not one of the eight semantics",
119            Self::KindMissing => "nothing gives the series a kind",
120            Self::MirrorMissing => {
121                "the mirror names no single non-frame metric resource of the interface with no parameter"
122            }
123            Self::MirrorInvalid => "the mirrored resource's own declaration is invalid",
124            Self::NotACarrier => "the field's type cannot carry the series' kind",
125        }
126    }
127}
128
129impl fmt::Display for Reason {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        f.write_str(self.as_str())
132    }
133}
134
135/// One reason, and the entry it is of: `None` for the annotation whole.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Problem {
138    pub entry: Option<String>,
139    pub reason: Reason,
140}
141
142/// What a reader reads of a frame resource (v2 §2.16).
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum Series {
145    /// Its series, in field order.
146    Declared(Vec<FieldSeries>),
147    /// Its problems: the annotation whole first, then each entry in byte
148    /// order of its name, each in [`Reason`]'s order.
149    Invalid(Vec<Problem>),
150    /// No `telemetry.series`, and another `telemetry.*` key: v1's keys mean
151    /// nothing on a frame resource.
152    Ignored,
153    /// No key of the vocabulary.
154    NotThisProfiles,
155}
156
157impl Series {
158    /// The fixture's token.
159    #[must_use]
160    pub const fn as_str(&self) -> &'static str {
161        match self {
162            Self::Declared(_) => "declared",
163            Self::Invalid(_) => "invalid",
164            Self::Ignored => "ignored",
165            Self::NotThisProfiles => "not_this_profiles",
166        }
167    }
168
169    /// The series, when the declaration is valid.
170    #[must_use]
171    pub fn declared(&self) -> Option<&[FieldSeries]> {
172        match self {
173            Self::Declared(s) => Some(s),
174            _ => None,
175        }
176    }
177}
178
179/// Whether a field's packed type carries `kind` (v2 §2.16): a counter a
180/// `counter`, a gauge an `int` or a `fixed`, a boolean a `bool`, a text an
181/// `enum`. Nothing carries a histogram or bytes, and a `time` carries no
182/// kind.
183#[must_use]
184pub fn carries(field: &Field, kind: MetricKind) -> bool {
185    matches!(
186        (kind, &field.kind),
187        (MetricKind::Counter, FieldKind::Counter)
188            | (
189                MetricKind::Gauge,
190                FieldKind::Int { .. } | FieldKind::Fixed { .. }
191            )
192            | (MetricKind::Boolean, FieldKind::Bool)
193            | (MetricKind::Text, FieldKind::Enum { .. })
194    )
195}
196
197/// What an entry gives a series before its field is weighed.
198struct Given {
199    kind: Option<MetricKind>,
200    unit: Option<String>,
201    semantic: Option<Semantic>,
202    mirror: Option<String>,
203}
204
205/// Reads one entry: its reasons, and what it gives when it has none
206/// before the carrier's check.
207fn entry(value: &Value, mirror: &dyn Fn(&str) -> Option<Declaration>) -> (Vec<Reason>, Given) {
208    let mut why = Vec::new();
209    let mut given = Given {
210        kind: None,
211        unit: None,
212        semantic: None,
213        mirror: None,
214    };
215    match value {
216        Value::Object(m) => {
217            if m.keys().any(|k| !INLINE.contains(&k.as_str())) {
218                why.push(Reason::SeriesValue);
219            }
220            let kind = m
221                .get("kind")
222                .map(|v| v.as_str().and_then(MetricKind::parse));
223            let unit = m
224                .get("unit")
225                .map(|v| v.as_str().filter(|u| is_unit(u)).map(str::to_owned));
226            let semantic = m
227                .get("semantic")
228                .map(|v| v.as_str().and_then(Semantic::parse));
229            for (wrong, r) in [
230                (matches!(kind, Some(None)), Reason::KindValue),
231                (matches!(unit, Some(None)), Reason::UnitValue),
232                (matches!(semantic, Some(None)), Reason::SemanticValue),
233            ] {
234                if wrong {
235                    why.push(r);
236                }
237            }
238            if kind.is_none() {
239                why.push(Reason::KindMissing);
240            }
241            given.kind = kind.flatten();
242            given.unit = unit.flatten();
243            given.semantic = semantic.flatten();
244        }
245        Value::String(name) => {
246            given.mirror = Some(name.clone());
247            match mirror(name) {
248                None | Some(Declaration::NotThisProfiles | Declaration::Ignored) => {
249                    why.push(Reason::MirrorMissing);
250                }
251                Some(Declaration::Invalid(_)) => why.push(Reason::MirrorInvalid),
252                Some(Declaration::Declared(d)) => match d.kind {
253                    None => why.push(Reason::KindMissing),
254                    Some(k) => {
255                        given.kind = Some(k);
256                        given.unit = d.unit;
257                        given.semantic = d.semantic;
258                    }
259                },
260            }
261        }
262        _ => why.push(Reason::SeriesValue),
263    }
264    (why, given)
265}
266
267/// Reads a frame resource's series from its record type's `fields` and
268/// its resolved annotations (core §9.3, v2 §2.16). `mirror` answers what a
269/// mirror names: `None` when it names no single resource of the
270/// interface, a frame resource or a template with a parameter, else that
271/// resource's `telemetry.v1` declaration ([`super::declaration_of`]).
272#[must_use]
273pub fn series(
274    fields: &[Field],
275    annotations: &BTreeMap<String, Value>,
276    mirror: &dyn Fn(&str) -> Option<Declaration>,
277) -> Series {
278    let Some(table) = annotations.get(SERIES) else {
279        let v1 = [super::KIND, super::UNIT, super::BUCKETS, super::SEMANTIC];
280        return if v1.iter().any(|k| annotations.contains_key(*k)) {
281            Series::Ignored
282        } else {
283            Series::NotThisProfiles
284        };
285    };
286    let whole = |reason| {
287        Series::Invalid(vec![Problem {
288            entry: None,
289            reason,
290        }])
291    };
292    let Some(table) = table.as_object().filter(|t| !t.is_empty()) else {
293        return whole(Reason::SeriesValue);
294    };
295    let mut entries: Vec<(&String, &Value)> = table.iter().collect();
296    entries.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
297    let mut problems = Vec::new();
298    let mut out = Vec::new();
299    for (name, value) in entries {
300        let at = fields.iter().position(|f| &f.name == name);
301        let (mut why, given) = entry(value, mirror);
302        if at.is_none() {
303            why.insert(0, Reason::SeriesField);
304        }
305        if let (Some(i), Some(kind)) = (at, given.kind)
306            && !carries(&fields[i], kind)
307        {
308            why.push(Reason::NotACarrier);
309        }
310        if why.is_empty() {
311            let i = at.expect("an entry with no reason names a field");
312            out.push(FieldSeries {
313                field: name.clone(),
314                index: i,
315                kind: given.kind.expect("an entry with no reason has a kind"),
316                unit: given.unit,
317                semantic: given.semantic,
318                mirror: given.mirror,
319                width: matches!(fields[i].kind, FieldKind::Counter).then_some(fields[i].width),
320            });
321        }
322        problems.extend(why.into_iter().map(|reason| Problem {
323            entry: Some(name.clone()),
324            reason,
325        }));
326    }
327    if !problems.is_empty() {
328        return Series::Invalid(problems);
329    }
330    out.sort_by_key(|s| s.index);
331    Series::Declared(out)
332}
333
334/// What a mirror names in `c` (v2 §2.16): the `telemetry.v1` declaration
335/// of the one resource whose template is `name`, when it is no frame
336/// resource and has no parameter; `None` otherwise.
337#[must_use]
338pub fn mirror_in(c: &Contract, name: &str) -> Option<Declaration> {
339    let mut named = c.resources.iter().filter(|r| r.template.as_str() == name);
340    let r = named.next()?;
341    if named.next().is_some() || !r.params.is_empty() {
342        return None;
343    }
344    if let Body::Data(d) = &r.body
345        && d.frame.is_some()
346    {
347        return None;
348    }
349    Some(super::declaration_of(c, r))
350}
351
352/// [`series`] of a contract's frame resource, its mirrors read in the
353/// contract ([`mirror_in`]). `None` for a resource that is no frame
354/// resource, or whose record type does not resolve (a contract that does
355/// not load).
356#[must_use]
357pub fn series_of(c: &Contract, r: &Resource) -> Option<Series> {
358    let layout = Layout::of_resource(c, r).ok().flatten()?;
359    Some(series(layout.fields(), &r.annotations, &|name| {
360        mirror_in(c, name)
361    }))
362}
363
364// ---------------------------------------------------------------------------
365// Readings (v2 §2.18)
366// ---------------------------------------------------------------------------
367
368/// A series field's value: the metric's, and §7.6's JSON reading, which
369/// keeps a `fixed` gauge's decimal exact.
370#[derive(Debug, Clone, PartialEq)]
371pub struct FieldValue {
372    pub measure: Measure,
373    /// Core §7.6's JSON reading: an integer, a `fixed` field's decimal
374    /// string, a boolean or an enum value's name.
375    pub json: Value,
376}
377
378/// One series field of one record, as a reader reads it (v2 §2.18).
379#[derive(Debug, Clone, PartialEq)]
380pub enum FieldReading {
381    /// Included with a value: a sample.
382    Sample(FieldValue),
383    /// Not included: the value it holds, `known` by no change since it was
384    /// (`within` false) or `within` its deadband. No sample.
385    Held { value: FieldValue, within: bool },
386    /// No value: included absent, or `not_available`.
387    Absent,
388    /// No value: `error`, the owner's error.
389    OwnerError,
390    /// No value: `out_of_range`, beyond the declared range.
391    BeyondRange,
392    /// No value: a code this revision does not name, an enum's escape.
393    Unnamed,
394    /// No value: the field's state is `unknown` (core §7.7), with why.
395    Unknown(Unknown),
396}
397
398impl FieldReading {
399    /// The fixture's token.
400    #[must_use]
401    pub const fn as_str(&self) -> &'static str {
402        match self {
403            Self::Sample(_) => "sample",
404            Self::Held { .. } => "held",
405            Self::Absent => "absent",
406            Self::OwnerError => "owner_error",
407            Self::BeyondRange => "beyond_range",
408            Self::Unnamed => "unnamed",
409            Self::Unknown(_) => "unknown",
410        }
411    }
412
413    /// The sample's value, when it is one.
414    #[must_use]
415    pub const fn sample(&self) -> Option<&FieldValue> {
416        match self {
417            Self::Sample(v) => Some(v),
418            _ => None,
419        }
420    }
421
422    /// The value it shows: a sample's, or a held one's. `None` for every
423    /// reading that is no value, which a reader never shows as one, nor as
424    /// 0.
425    #[must_use]
426    pub const fn value(&self) -> Option<&FieldValue> {
427        match self {
428            Self::Sample(v) | Self::Held { value: v, .. } => Some(v),
429            _ => None,
430        }
431    }
432}
433
434/// The value of `code` in `field` as a series of `kind`, or `None` for a
435/// code it does not name (an enum's escape).
436fn value_of(s: &FieldSeries, field: &Field, code: u64) -> Option<FieldValue> {
437    let json = field.value(code, None).ok()?;
438    let measure = match s.kind {
439        MetricKind::Counter => Measure::Counter {
440            value: code,
441            width: field.width,
442        },
443        MetricKind::Gauge => Measure::Gauge(match &json {
444            Value::String(d) => d.parse::<f64>().ok()?,
445            v => v.as_i64()? as f64,
446        }),
447        MetricKind::Boolean => Measure::Boolean(json.as_bool()?),
448        MetricKind::Text => Measure::Text(json.as_str()?.to_owned()),
449        MetricKind::Histogram | MetricKind::Binary => return None,
450    };
451    Some(FieldValue { measure, json })
452}
453
454/// Reads one series field of one record (v2 §2.18): its slot in the
455/// record (core §7.7's body) and its state as the key's
456/// [`crate::frame::Reader`] read it. A sample is a slot that included the
457/// field with a code that is a value; an omitted field holding a value is
458/// held, no sample; a reserved code, an absent field, an escape and an
459/// unknown state are no value, included or held.
460#[must_use]
461pub fn reading_of(s: &FieldSeries, field: &Field, slot: Slot, state: FieldState) -> FieldReading {
462    let (code, within) = match state {
463        FieldState::Unknown(why) => return FieldReading::Unknown(why),
464        FieldState::Absent => return FieldReading::Absent,
465        FieldState::Known(c) => (c, false),
466        FieldState::Within(c) => (c, true),
467    };
468    match field.reserved_name(code) {
469        Some("error") => return FieldReading::OwnerError,
470        Some("out_of_range") => return FieldReading::BeyondRange,
471        Some(_) => return FieldReading::Absent,
472        None => {}
473    }
474    let Some(value) = value_of(s, field, code) else {
475        return FieldReading::Unnamed;
476    };
477    if matches!(slot, Slot::Code(c) if c == code) && !within {
478        FieldReading::Sample(value)
479    } else {
480        FieldReading::Held { value, within }
481    }
482}
483
484// ---------------------------------------------------------------------------
485// A key's fold: readings, epochs and pairs (v2 §2.18–§2.21)
486// ---------------------------------------------------------------------------
487
488/// Where a sample lies among a [`Fold`]'s frames: the frame, counted from 0
489/// as the fold applied them, and the record's index in it.
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
491pub struct Position {
492    pub frame: u64,
493    pub record: usize,
494}
495
496/// One series field of one record, folded.
497#[derive(Debug, Clone, PartialEq)]
498pub struct SeriesRead {
499    /// The series' index in the slice the fold was handed.
500    pub series: usize,
501    pub reading: FieldReading,
502    /// A counter's sample after another of its series: the earlier sample,
503    /// and the pair they form.
504    pub pair: Option<(Position, Pair)>,
505}
506
507/// One record of a frame, folded.
508#[derive(Debug, Clone, PartialEq)]
509pub struct RecordSeries {
510    pub seq: Seq,
511    pub time: RecordTime,
512    /// One per series, in the series' order.
513    pub fields: Vec<SeriesRead>,
514}
515
516/// A frame, folded.
517#[derive(Debug, Clone, PartialEq)]
518pub struct Folded {
519    /// The frame as the key's reader read it (core §7.7).
520    pub applied: Applied,
521    pub records: Vec<RecordSeries>,
522}
523
524#[derive(Debug, Clone)]
525struct Last {
526    measure: Measure,
527    epoch: String,
528    at: Position,
529    time: RecordTime,
530    arrival_ns: i128,
531}
532
533impl Last {
534    fn sampled(&self) -> Sampled<'_> {
535        Sampled {
536            value: &self.measure,
537            epoch: Some(&self.epoch),
538            timestamp_ms: None,
539            stamp_ns: None,
540            arrival_ns: self.arrival_ns,
541            record: Some(self.time),
542        }
543    }
544}
545
546/// One frame key's series, as a reader folds its frames (v2 §2.18–§2.21):
547/// the key's [`crate::frame::Reader`], the epoch it reads its samples
548/// under, and each counter series' last sample.
549///
550/// - **The epoch is the run.** A frame the reader reads as its first, as
551///   another run's or as a rewind starts a new epoch; a gap does not. So
552///   two samples are of one epoch, established in band, when no frame
553///   between them was read so, and of two otherwise: a pair across a
554///   rewind is a reset, never a decrease (v2 §2.19).
555/// - **A pair** is two consecutive samples of one counter series, whatever
556///   was omitted, unknown or lost between them: two included values are
557///   exact (v2 §2.18). It is judged by [`crate::telemetry::pair`], with no
558///   presence: the epoch is always in band.
559/// - **Each frame** is handed over in the order it arrived, with its
560///   arrival on the reader's monotonic clock, the time base of a pair whose
561///   record time is unknown (v2 §2.21).
562#[derive(Debug, Clone, Default)]
563pub struct Fold {
564    reader: frame::Reader,
565    frames: u64,
566    epochs: u64,
567    last: BTreeMap<usize, Last>,
568}
569
570impl Fold {
571    /// A fold that holds nothing: its first frame starts an epoch.
572    #[must_use]
573    pub fn new() -> Self {
574        Self::default()
575    }
576
577    /// The key's reader.
578    #[must_use]
579    pub const fn reader(&self) -> &frame::Reader {
580        &self.reader
581    }
582
583    /// Notes a frame at `stamp` its layout refused (core §7.7): never
584    /// applied, so the next frame follows a gap ([`frame::Reader::refuse`]).
585    pub fn refuse(&mut self, stamp: Stamp) {
586        self.reader.refuse(stamp);
587    }
588
589    /// Folds a frame of the key: `stamp` its envelope's, `frame` its body
590    /// read under `layout`, `series` the resource's declared series
591    /// ([`Series::Declared`]) and `arrival_ns` when it arrived, on the
592    /// reader's monotonic clock.
593    pub fn apply(
594        &mut self,
595        layout: &Layout,
596        series: &[FieldSeries],
597        stamp: Stamp,
598        frame: &Frame,
599        arrival_ns: i128,
600    ) -> Folded {
601        let applied = self.reader.apply(layout, stamp, frame);
602        if applied.follows.resets() && !matches!(applied.follows, frame::Follows::Gap { .. }) {
603            self.epochs += 1;
604        }
605        let epoch = format!("{}/{}", stamp.run.hex(), self.epochs);
606        let n = self.frames;
607        self.frames += 1;
608        let fields = layout.fields();
609        let mut records = Vec::with_capacity(frame.records.len());
610        for (i, (rec, read)) in frame.records.iter().zip(&applied.records).enumerate() {
611            let time = RecordTime {
612                frame: n,
613                when: read.when,
614                after_ms: read.after_ms,
615                at_ms: read.at_ms,
616            };
617            let at = Position {
618                frame: n,
619                record: i,
620            };
621            let mut out = Vec::with_capacity(series.len());
622            for (k, s) in series.iter().enumerate() {
623                let (Some(field), Some(slot), Some(state)) = (
624                    fields.get(s.index),
625                    rec.slots.get(s.index),
626                    read.fields.get(s.index),
627                ) else {
628                    continue;
629                };
630                let reading = reading_of(s, field, *slot, *state);
631                let pair = match (&reading, s.kind) {
632                    (FieldReading::Sample(v), MetricKind::Counter) => {
633                        let now = Last {
634                            measure: v.measure.clone(),
635                            epoch: epoch.clone(),
636                            at,
637                            time,
638                            arrival_ns,
639                        };
640                        let judged = self.last.get(&s.index).map(|before| {
641                            (
642                                before.at,
643                                pair(&before.sampled(), &now.sampled(), s.unit.as_deref(), None),
644                            )
645                        });
646                        self.last.insert(s.index, now);
647                        judged
648                    }
649                    _ => None,
650                };
651                out.push(SeriesRead {
652                    series: k,
653                    reading,
654                    pair,
655                });
656            }
657            records.push(RecordSeries {
658                seq: read.seq,
659                time,
660                fields: out,
661            });
662        }
663        Folded { applied, records }
664    }
665}
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670    use crate::telemetry::{Continuity, NoRate, TimeBasis};
671    use serde_json::json;
672
673    fn link() -> Vec<Field> {
674        let doc = json!({"types": {"Link": {"fields": [
675            {"name": "dropped", "type": "counter", "width": 8, "optional": true},
676            {"name": "queue_depth", "type": "int", "minimum": 0, "maximum": 1022,
677             "reserved": ["error", "out_of_range"], "optional": true},
678            {"name": "mode", "type": "enum", "values": ["idle", "tx"], "escape": true},
679            {"name": "at", "type": "time"},
680        ]}}});
681        crate::packed::layout_in(&doc, "Link")
682            .unwrap()
683            .fields()
684            .cloned()
685            .collect()
686    }
687
688    fn ann(v: Value) -> BTreeMap<String, Value> {
689        BTreeMap::from([(SERIES.to_owned(), v)])
690    }
691
692    #[test]
693    fn an_entry_is_checked_against_its_field_and_its_mirror() {
694        let none = |_: &str| None;
695        let s = series(
696            &link(),
697            &ann(json!({"dropped": {"kind": "counter", "unit": "1"}, "mode": {"kind": "text"}})),
698            &none,
699        );
700        let d = s.declared().expect("declared");
701        assert_eq!(d[0].width, Some(8));
702        assert_eq!(d[1].kind, MetricKind::Text);
703        let s = series(
704            &link(),
705            &ann(json!({"at": {"kind": "gauge"}, "nope": "x/y", "queue_depth": 3})),
706            &none,
707        );
708        let Series::Invalid(p) = s else {
709            panic!("{s:?}")
710        };
711        let got: Vec<_> = p
712            .iter()
713            .map(|p| (p.entry.as_deref().unwrap(), p.reason.as_str()))
714            .collect();
715        assert_eq!(
716            got,
717            [
718                ("at", "not_a_carrier"),
719                ("nope", "series_field"),
720                ("nope", "mirror_missing"),
721                ("queue_depth", "series_value"),
722            ]
723        );
724        assert_eq!(
725            series(&link(), &BTreeMap::new(), &none),
726            Series::NotThisProfiles
727        );
728        assert_eq!(series(&link(), &ann(json!({})), &none).as_str(), "invalid");
729    }
730
731    #[test]
732    fn only_an_included_value_is_a_sample() {
733        let f = link();
734        let s = FieldSeries {
735            field: "queue_depth".into(),
736            index: 1,
737            kind: MetricKind::Gauge,
738            unit: None,
739            semantic: None,
740            mirror: None,
741            width: None,
742        };
743        let r = |slot, state| reading_of(&s, &f[1], slot, state).as_str();
744        assert_eq!(r(Slot::Code(4), FieldState::Known(4)), "sample");
745        assert_eq!(r(Slot::Omitted, FieldState::Known(4)), "held");
746        assert_eq!(r(Slot::Omitted, FieldState::Within(4)), "held");
747        let top = (1u64 << f[1].width) - 1;
748        assert_eq!(r(Slot::Code(top), FieldState::Known(top)), "owner_error");
749        assert_eq!(
750            r(Slot::Code(top - 1), FieldState::Known(top - 1)),
751            "beyond_range"
752        );
753        assert_eq!(r(Slot::Absent, FieldState::Absent), "absent");
754    }
755
756    #[test]
757    fn a_narrow_counter_reads_in_its_serial_window() {
758        let at = |frame, after_ms| RecordTime {
759            frame,
760            when: frame::When::Measured,
761            after_ms,
762            at_ms: Some(1_000 * frame + after_ms),
763        };
764        let s = |v, t| Sampled {
765            value: v,
766            epoch: Some("r"),
767            timestamp_ms: None,
768            stamp_ns: None,
769            arrival_ns: 0,
770            record: Some(t),
771        };
772        let c = |value| Measure::Counter { value, width: 8 };
773        let (a, b, z) = (c(250), c(4), c(0));
774        let p = pair(&s(&a, at(0, 0)), &s(&b, at(1, 0)), None, None);
775        assert_eq!(p.continuity, Continuity::SameEpoch);
776        let r = p.rate.unwrap();
777        assert_eq!((r.per_s, r.basis), (10.0, Some(TimeBasis::Measured)));
778        let p = pair(&s(&b, at(0, 0)), &s(&z, at(1, 0)), None, None);
779        assert_eq!(p.continuity, Continuity::Unobservable);
780        assert_eq!(p.rate, Err(NoRate::WrapOrDecrease));
781        assert_eq!(p.unobservable(), Some("wrap_or_decrease"));
782    }
783}