iroh_metrics/
lib.rs

1//! Metrics library for iroh
2
3#![deny(missing_docs, rustdoc::broken_intra_doc_links)]
4#![cfg_attr(iroh_docsrs, feature(doc_auto_cfg))]
5
6pub use self::{base::*, metrics::*, registry::*};
7
8mod base;
9pub mod encoding;
10pub mod iterable;
11mod metrics;
12mod registry;
13#[cfg(feature = "service")]
14pub mod service;
15#[cfg(feature = "static_core")]
16pub mod static_core;
17
18/// Derives [`MetricsGroup`] and [`Iterable`].
19///
20/// This derive macro only works on structs with named fields.
21///
22/// It will generate a [`Default`] impl which expects all fields to be of a type
23/// that has a public `new` method taking a single `&'static str` argument.
24/// The [`Default::default`] method will call each field's `new` method with the
25/// first line of the field's doc comment as argument. Alternatively, you can override
26/// the value passed to `new` by setting a `#[metrics(help = "my help")]`
27/// attribute on the field.
28///
29/// It will also generate a [`MetricsGroup`] impl. By default, the struct's name,
30/// converted to `camel_case` will be used as the return value of the [`MetricsGroup::name`]
31/// method. The name can be customized by setting a `#[metrics(name = "my-name")]` attribute.
32///
33/// It will also generate a [`Iterable`] impl.
34///
35/// [`Iterable`]: iterable::Iterable
36pub use iroh_metrics_derive::MetricsGroup;
37/// Derives [`MetricsGroupSet`] for a struct.
38///
39/// All fields of the struct must be public and have a type of `Arc<SomeType>`,
40/// where `SomeType` implements `MetricsGroup`.
41pub use iroh_metrics_derive::MetricsGroupSet;
42
43// This lets us use the derive metrics in the lib tests within this crate.
44extern crate self as iroh_metrics;
45
46use std::collections::HashMap;
47
48/// Potential errors from this library.
49#[n0_error::stack_error(derive, add_meta, from_sources, std_sources)]
50#[non_exhaustive]
51#[allow(missing_docs)]
52pub enum Error {
53    /// Indicates that the metrics have not been enabled.
54    #[error("Metrics not enabled")]
55    NoMetrics,
56    /// Writing the metrics to the output buffer failed.
57    #[error(transparent)]
58    Fmt { source: std::fmt::Error },
59    /// Any IO related error.
60    #[error(transparent)]
61    IO { source: std::io::Error },
62}
63
64/// Parses Prometheus metrics from a string.
65pub fn parse_prometheus_metrics(data: &str) -> HashMap<String, f64> {
66    let mut metrics = HashMap::new();
67    for line in data.lines() {
68        if line.starts_with('#') {
69            continue;
70        }
71        let parts: Vec<&str> = line.split_whitespace().collect();
72        if parts.len() < 2 {
73            continue;
74        }
75        let metric = parts[0];
76        let value = parts[1].parse::<f64>();
77        if value.is_err() {
78            continue;
79        }
80        metrics.insert(metric.to_string(), value.unwrap());
81    }
82    metrics
83}