Skip to main content

zenkey_model/telemetry/
wire.rs

1//! The standard schema's types as an owner puts them (§2.3; #819, TB): the
2//! Point, its tagged value and the histogram, with serde, so a value of
3//! each is the schema's on the wire, in JSON and in CBOR alike.
4//!
5//! | `telemetry.v1.json` | Here |
6//! |---|---|
7//! | `telemetry.v1.Point`: `timestamp`, `value`, `labels`, `unit`, `epoch` | [`Point`]: an optional member left out when it is empty, labels in key order |
8//! | `telemetry.v1.Value`: `{"type": <kind>, "value": …}`, one branch per kind | [`Value`], internally tagged, the tag spelled as `telemetry.kind` spells it (§2.2) |
9//! | `binary`: an array of byte values, in JSON and in CBOR alike | [`Value::Binary`], a `Vec<u8>` serialized as a sequence, never a byte string |
10//! | `telemetry.v1.Histogram`: `buckets`, `counts`, `count`, `sum` | [`Histogram`], and [`Histogram::observe`], which keeps §2.8's shape |
11//! | `telemetry.v1.Epoch` | [`Point::epoch`], a string |
12//!
13//! These are session-free, so they live beside the readers: the runtime's
14//! writers check what they put through [`super::check`], as any reader
15//! would, and fill the epoch an application leaves out (`zenkey::telemetry`).
16//! A value of these types is not a conforming sample by construction: a
17//! counter Point on a resource declared `gauge`, a histogram over bounds
18//! other than the declared ones, or a gauge that is not finite all
19//! serialize, and the writer refuses them.
20//!
21//! ZenSight's `TelemetryPoint` reads as a [`Point`]: its `source` and
22//! `metric` are members the schema does not name, which every reader
23//! tolerates (core §9.8), and its value is the same tagged union.
24
25use std::collections::BTreeMap;
26
27use serde::{Deserialize, Serialize};
28
29use super::{MetricKind, ascending};
30
31/// One measurement of one member (§2.3): the series is the key, never a
32/// label (§2.12).
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub struct Point {
35    /// The measurement time, Unix epoch milliseconds: when the value was
36    /// taken, not when it was put (§2.12).
37    pub timestamp: i64,
38    /// The measured value, tagged with its kind.
39    pub value: Value,
40    /// Context, never identity (§2.12). Left out when empty.
41    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
42    pub labels: BTreeMap<String, String>,
43    /// The member's unit where the resource declares none (§2.5). A
44    /// declared `telemetry.unit` is authoritative, and a Point that
45    /// disagrees does not conform (§2.6).
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub unit: Option<String>,
48    /// Its in-band epoch (§2.9). The runtime's writer fills it with the
49    /// owner's instance id, or the member's epoch, when it is left out on a
50    /// counter or a histogram.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub epoch: Option<String>,
53}
54
55impl Point {
56    /// A Point of `value`, measured at `timestamp_ms` (Unix epoch
57    /// milliseconds). `zenkey::telemetry::point` stamps one with the clock
58    /// now; this module reads no clock.
59    #[must_use]
60    pub fn new(timestamp_ms: i64, value: impl Into<Value>) -> Self {
61        Self {
62            timestamp: timestamp_ms,
63            value: value.into(),
64            labels: BTreeMap::new(),
65            unit: None,
66            epoch: None,
67        }
68    }
69
70    /// With the unit `unit` (§2.5).
71    #[must_use]
72    pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
73        self.unit = Some(unit.into());
74        self
75    }
76
77    /// With the label `name` = `value`, context (§2.12).
78    #[must_use]
79    pub fn with_label(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
80        self.labels.insert(name.into(), value.into());
81        self
82    }
83
84    /// With the in-band epoch `epoch` (§2.9). An owner rarely writes it: the
85    /// runtime's writer does, and refuses one other than its own.
86    #[must_use]
87    pub fn with_epoch(mut self, epoch: impl Into<String>) -> Self {
88        self.epoch = Some(epoch.into());
89        self
90    }
91
92    /// The Point's tag (§2.5).
93    #[must_use]
94    pub fn kind(&self) -> MetricKind {
95        self.value.kind()
96    }
97}
98
99/// A Point's value, internally tagged: `{"type": <kind>, "value": …}`
100/// (§2.3), one variant per kind of §2.2, in the schema's order.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102#[serde(tag = "type", content = "value", rename_all = "lowercase")]
103pub enum Value {
104    /// A count from 0 to 2^64−1 that never decreases within one epoch
105    /// (§2.7).
106    Counter(u64),
107    /// A number, which may go up or down. JSON has no NaN or infinity: one
108    /// serializes as `null`, which does not conform (§2.6).
109    Gauge(f64),
110    Text(String),
111    Boolean(bool),
112    /// Bytes, as an array of byte values in JSON and in CBOR alike.
113    Binary(Vec<u8>),
114    Histogram(Histogram),
115}
116
117impl Value {
118    /// The kind its tag names.
119    #[must_use]
120    pub fn kind(&self) -> MetricKind {
121        match self {
122            Self::Counter(_) => MetricKind::Counter,
123            Self::Gauge(_) => MetricKind::Gauge,
124            Self::Text(_) => MetricKind::Text,
125            Self::Boolean(_) => MetricKind::Boolean,
126            Self::Binary(_) => MetricKind::Binary,
127            Self::Histogram(_) => MetricKind::Histogram,
128        }
129    }
130}
131
132impl From<u64> for Value {
133    fn from(v: u64) -> Self {
134        Self::Counter(v)
135    }
136}
137
138impl From<f64> for Value {
139    fn from(v: f64) -> Self {
140        Self::Gauge(v)
141    }
142}
143
144impl From<bool> for Value {
145    fn from(v: bool) -> Self {
146        Self::Boolean(v)
147    }
148}
149
150impl From<String> for Value {
151    fn from(v: String) -> Self {
152        Self::Text(v)
153    }
154}
155
156impl From<&str> for Value {
157    fn from(v: &str) -> Self {
158        Self::Text(v.to_owned())
159    }
160}
161
162impl From<Vec<u8>> for Value {
163    fn from(v: Vec<u8>) -> Self {
164        Self::Binary(v)
165    }
166}
167
168impl From<Histogram> for Value {
169    fn from(v: Histogram) -> Self {
170        Self::Histogram(v)
171    }
172}
173
174/// A fixed-bucket distribution (§2.8), cumulative within one epoch, as
175/// ZenSight's `HistogramValue` is.
176#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
177pub struct Histogram {
178    /// The bounds, strictly ascending and finite, `+Inf` implicit: equal by
179    /// value to the resource's `telemetry.buckets`.
180    pub buckets: Vec<f64>,
181    /// A count per bucket, not cumulative, one more than the bounds, the
182    /// overflow last.
183    pub counts: Vec<u64>,
184    /// The sum of `counts`.
185    pub count: u64,
186    /// The sum of every value observed, which may be negative.
187    pub sum: f64,
188}
189
190impl Histogram {
191    /// An empty histogram over `bounds`, the declared `telemetry.buckets`
192    /// (the declaration's [`super::Declared::buckets`]). `None` unless they
193    /// are a valid set of bounds (§2.2): non-empty, finite, strictly
194    /// ascending.
195    #[must_use]
196    pub fn new(bounds: &[f64]) -> Option<Self> {
197        let valid = !bounds.is_empty() && bounds.iter().all(|b| b.is_finite()) && ascending(bounds);
198        valid.then(|| Self {
199            buckets: bounds.to_vec(),
200            counts: vec![0; bounds.len() + 1],
201            count: 0,
202            sum: 0.0,
203        })
204    }
205
206    /// The bucket a value falls in (§2.8): the first bound at or above it,
207    /// `(buckets[i-1], buckets[i]]`, upper-inclusive; past the last bound,
208    /// the overflow.
209    #[must_use]
210    pub fn bucket_of(&self, v: f64) -> usize {
211        self.buckets.partition_point(|b| *b < v)
212    }
213
214    /// Records one observation: its bucket's count and `count` up by one,
215    /// `v` added to `sum`. Refused, `false` and nothing changed, for a
216    /// value that is not finite (it has no bucket), and for one that would
217    /// take a count past 2^64−1 or the sum to an infinity, either of which
218    /// would make the histogram one no reader reads (§2.6).
219    pub fn observe(&mut self, v: f64) -> bool {
220        if !v.is_finite() {
221            return false;
222        }
223        let i = self.bucket_of(v);
224        let sum = self.sum + v;
225        let (Some(c), Some(n)) = (
226            self.counts.get(i).and_then(|c| c.checked_add(1)),
227            self.count.checked_add(1),
228        ) else {
229            return false;
230        };
231        if !sum.is_finite() {
232            return false;
233        }
234        self.counts[i] = c;
235        self.count = n;
236        self.sum = sum;
237        true
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244    use crate::authoring::Kind;
245    use crate::telemetry::{
246        BUCKETS, Conformance, Datum, Declaration, KIND, PUBLISHED, Payload, Problem, TypeView,
247        UNIT, check, declaration,
248    };
249    use serde_json::{Value as Json, json};
250
251    fn point_decl(annotations: &[(&str, Json)]) -> Declaration {
252        let ty = TypeView::Json {
253            name: crate::telemetry::POINT,
254            schema: PUBLISHED[1],
255            root: None,
256        };
257        let a = annotations
258            .iter()
259            .map(|(k, v)| ((*k).to_owned(), v.clone()))
260            .collect();
261        declaration(Kind::Stream, &a, Some(&ty), None)
262    }
263
264    fn conformance(d: &Declaration, datum: &Datum) -> Conformance {
265        check(
266            d,
267            &Payload::Decoded {
268                value: datum,
269                attachment: None,
270            },
271        )
272        .conformance
273    }
274
275    fn cbor(p: &Point) -> Vec<u8> {
276        let mut out = Vec::new();
277        ciborium::into_writer(p, &mut out).unwrap();
278        out
279    }
280
281    #[test]
282    fn a_point_is_the_schemas_on_the_wire() {
283        let p = Point::new(1_760_000_000_123, 42u64)
284            .with_unit("By")
285            .with_label("oid", "1.3.6")
286            .with_epoch("00000000000000aa");
287        assert_eq!(
288            serde_json::to_string(&p).unwrap(),
289            r#"{"timestamp":1760000000123,"value":{"type":"counter","value":42},"labels":{"oid":"1.3.6"},"unit":"By","epoch":"00000000000000aa"}"#
290        );
291        let bare = Point::new(5, Value::Gauge(-70.5));
292        assert_eq!(
293            serde_json::to_string(&bare).unwrap(),
294            r#"{"timestamp":5,"value":{"type":"gauge","value":-70.5}}"#,
295            "an empty member is left out"
296        );
297        // CBOR carries the same data item: a map of the same members, the
298        // binary as an array of integers, never a byte string.
299        for p in [
300            p,
301            bare,
302            Point::new(1, vec![0u8, 255]),
303            Point::new(1, true),
304            Point::new(1, "up"),
305        ] {
306            let bytes = cbor(&p);
307            let item: ciborium::Value = ciborium::from_reader(bytes.as_slice()).unwrap();
308            let as_json: Json = item.deserialized().unwrap();
309            assert_eq!(as_json, serde_json::to_value(&p).unwrap(), "{p:?}");
310            let back: Point = ciborium::from_reader(bytes.as_slice()).unwrap();
311            assert_eq!(back, p);
312            let d = point_decl(&[]);
313            let datum = Datum::from_cbor_bytes(&bytes).unwrap();
314            assert_eq!(conformance(&d, &datum), Conformance::Conforms, "{p:?}");
315            let datum = Datum::from_json_bytes(&serde_json::to_vec(&p).unwrap()).unwrap();
316            assert_eq!(conformance(&d, &datum), Conformance::Conforms, "{p:?}");
317        }
318        let binary = serde_json::to_value(Point::new(1, vec![7u8])).unwrap();
319        assert_eq!(binary["value"], json!({"type": "binary", "value": [7]}));
320    }
321
322    #[test]
323    fn zensights_point_reads_as_one() {
324        let z = json!({"timestamp": 3, "source": "h1", "metric": "cpu/0", "value":
325            {"type": "gauge", "value": 1.5}, "labels": {"unit": "%"}});
326        let p: Point = serde_json::from_value(z).unwrap();
327        assert_eq!(p.value, Value::Gauge(1.5));
328        assert_eq!(p.unit, None, "a label named unit is context (§2.5)");
329    }
330
331    #[test]
332    fn a_histogram_observes_into_its_bounds_upper_inclusive() {
333        let mut h = Histogram::new(&[0.005, 0.01, 0.025]).unwrap();
334        for v in [0.001, 0.005, 0.007, 0.01, 0.02, 0.5, -3.0] {
335            assert!(h.observe(v));
336        }
337        // (−∞,0.005] (0.005,0.01] (0.01,0.025] (0.025,+Inf)
338        assert_eq!(h.counts, vec![3, 2, 1, 1]);
339        assert_eq!(h.count, 7);
340        assert!((h.sum - (0.543 - 3.0)).abs() < 1e-12);
341        assert!(!h.observe(f64::NAN) && !h.observe(f64::INFINITY));
342        assert!(h.observe(f64::MAX));
343        assert!(!h.observe(f64::MAX), "no infinite sum");
344        assert_eq!(h.count, 8, "the refused observation counts nothing");
345        let d = point_decl(&[
346            (KIND, json!("histogram")),
347            (UNIT, json!("s")),
348            (BUCKETS, json!([0.005, 0.01, 0.025])),
349        ]);
350        let p = Point::new(1, h.clone()).with_unit("s");
351        let datum = Datum::from_json_bytes(&serde_json::to_vec(&p).unwrap()).unwrap();
352        assert_eq!(conformance(&d, &datum), Conformance::Conforms);
353        let other = Point::new(1, Histogram::new(&[0.005, 0.01, 0.05]).unwrap());
354        let datum = Datum::from_json_bytes(&serde_json::to_vec(&other).unwrap()).unwrap();
355        assert_eq!(
356            conformance(&d, &datum),
357            Conformance::DoesNot(vec![Problem::BoundsDiffer])
358        );
359        assert_eq!(Histogram::new(&[]), None);
360        assert_eq!(Histogram::new(&[1.0, 1.0]), None);
361        assert_eq!(Histogram::new(&[1.0, f64::INFINITY]), None);
362        let mut full = Histogram::new(&[1.0]).unwrap();
363        full.counts[0] = u64::MAX;
364        full.count = u64::MAX;
365        assert!(!full.observe(0.5), "a count past 2^64-1 is refused");
366        assert_eq!(full.counts[0], u64::MAX);
367    }
368}