1use 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
44pub const INLINE: &[&str] = &["kind", "unit", "semantic"];
46
47#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct FieldSeries {
51 pub field: String,
53 pub index: usize,
55 pub kind: MetricKind,
57 pub unit: Option<String>,
58 pub semantic: Option<Semantic>,
59 pub mirror: Option<String>,
62 pub width: Option<u32>,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub enum Reason {
70 SeriesField,
72 SeriesValue,
76 KindValue,
77 UnitValue,
78 SemanticValue,
79 MirrorMissing,
82 MirrorInvalid,
84 KindMissing,
87 NotACarrier,
89}
90
91impl Reason {
92 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Problem {
138 pub entry: Option<String>,
139 pub reason: Reason,
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum Series {
145 Declared(Vec<FieldSeries>),
147 Invalid(Vec<Problem>),
150 Ignored,
153 NotThisProfiles,
155}
156
157impl Series {
158 #[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 #[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#[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
197struct Given {
199 kind: Option<MetricKind>,
200 unit: Option<String>,
201 semantic: Option<Semantic>,
202 mirror: Option<String>,
203}
204
205fn 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#[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#[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#[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#[derive(Debug, Clone, PartialEq)]
371pub struct FieldValue {
372 pub measure: Measure,
373 pub json: Value,
376}
377
378#[derive(Debug, Clone, PartialEq)]
380pub enum FieldReading {
381 Sample(FieldValue),
383 Held { value: FieldValue, within: bool },
386 Absent,
388 OwnerError,
390 BeyondRange,
392 Unnamed,
394 Unknown(Unknown),
396}
397
398impl FieldReading {
399 #[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 #[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 #[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
434fn 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
491pub struct Position {
492 pub frame: u64,
493 pub record: usize,
494}
495
496#[derive(Debug, Clone, PartialEq)]
498pub struct SeriesRead {
499 pub series: usize,
501 pub reading: FieldReading,
502 pub pair: Option<(Position, Pair)>,
505}
506
507#[derive(Debug, Clone, PartialEq)]
509pub struct RecordSeries {
510 pub seq: Seq,
511 pub time: RecordTime,
512 pub fields: Vec<SeriesRead>,
514}
515
516#[derive(Debug, Clone, PartialEq)]
518pub struct Folded {
519 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#[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 #[must_use]
573 pub fn new() -> Self {
574 Self::default()
575 }
576
577 #[must_use]
579 pub const fn reader(&self) -> &frame::Reader {
580 &self.reader
581 }
582
583 pub fn refuse(&mut self, stamp: Stamp) {
586 self.reader.refuse(stamp);
587 }
588
589 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}