1use std::collections::BTreeMap;
26
27use serde::{Deserialize, Serialize};
28
29use super::{MetricKind, ascending};
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub struct Point {
35 pub timestamp: i64,
38 pub value: Value,
40 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
42 pub labels: BTreeMap<String, String>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub unit: Option<String>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub epoch: Option<String>,
53}
54
55impl Point {
56 #[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 #[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 #[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 #[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 #[must_use]
94 pub fn kind(&self) -> MetricKind {
95 self.value.kind()
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102#[serde(tag = "type", content = "value", rename_all = "lowercase")]
103pub enum Value {
104 Counter(u64),
107 Gauge(f64),
110 Text(String),
111 Boolean(bool),
112 Binary(Vec<u8>),
114 Histogram(Histogram),
115}
116
117impl Value {
118 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
177pub struct Histogram {
178 pub buckets: Vec<f64>,
181 pub counts: Vec<u64>,
184 pub count: u64,
186 pub sum: f64,
188}
189
190impl Histogram {
191 #[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 #[must_use]
210 pub fn bucket_of(&self, v: f64) -> usize {
211 self.buckets.partition_point(|b| *b < v)
212 }
213
214 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 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 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}