Skip to content

Commit

Permalink
Merge branch 'master' into collector
Browse files Browse the repository at this point in the history
  • Loading branch information
mxinden committed Sep 4, 2022
2 parents 5011475 + 16993b6 commit 7978ab5
Show file tree
Hide file tree
Showing 10 changed files with 52 additions and 3 deletions.
12 changes: 11 additions & 1 deletion src/encoding/text.rs
Expand Up @@ -40,6 +40,8 @@ use std::ops::Deref;

pub use prometheus_client_derive_text_encode::*;

/// Encode the metrics registered with the provided [`Registry`] into the
/// provided [`Write`]r using the OpenMetrics text format.
pub fn encode<W, M: Clone>(writer: &mut W, registry: &Registry<M>) -> Result<(), std::io::Error>
where
W: Write,
Expand Down Expand Up @@ -92,7 +94,9 @@ where
Ok(())
}

/// OpenMetrics text encoding for a value.
pub trait Encode {
/// Encode to OpenMetrics text encoding.
fn encode(&self, writer: &mut dyn Write) -> Result<(), std::io::Error>;
}

Expand Down Expand Up @@ -304,6 +308,7 @@ impl<'a, 'b> Encoder<'a, 'b> {
}
}

/// Used to encode an OpenMetrics Histogram bucket.
#[allow(missing_debug_implementations)]
#[must_use]
pub struct BucketEncoder<'a> {
Expand Down Expand Up @@ -344,6 +349,7 @@ impl<'a> BucketEncoder<'a> {
}
}

/// Used to encode an OpenMetrics metric value.
#[allow(missing_debug_implementations)]
#[must_use]
pub struct ValueEncoder<'a> {
Expand All @@ -362,6 +368,7 @@ impl<'a> ValueEncoder<'a> {
}
}

/// Used to encode an OpenMetrics Exemplar.
#[allow(missing_debug_implementations)]
#[must_use]
pub struct ExemplarEncoder<'a> {
Expand Down Expand Up @@ -389,10 +396,12 @@ impl<'a> ExemplarEncoder<'a> {
}
}

/// Trait implemented by each metric type, e.g. [`Counter`], to implement its encoding.
/// Trait implemented by each metric type, e.g. [`Counter`], to implement its encoding in the OpenMetric text format.
pub trait EncodeMetric {
/// Encode the given instance in the OpenMetrics text encoding.
fn encode(&self, encoder: Encoder) -> Result<(), std::io::Error>;

/// The OpenMetrics metric type of the instance.
// One can not use [`TypedMetric`] directly, as associated constants are not
// object safe and thus can not be used with dynamic dispatching.
fn metric_type(&self) -> MetricType;
Expand All @@ -408,6 +417,7 @@ impl EncodeMetric for Box<dyn EncodeMetric> {
}
}

/// Trait combining [`EncodeMetric`], [`Send`] and [`Sync`].
pub trait SendSyncEncodeMetric: EncodeMetric + Send + Sync {}

impl<T: EncodeMetric + Send + Sync> SendSyncEncodeMetric for T {}
Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
@@ -1,6 +1,7 @@
#![forbid(unsafe_code)]
#![deny(unused)]
#![deny(dead_code)]
#![deny(missing_docs)]
#![deny(unused)]
#![forbid(unsafe_code)]
#![warn(missing_debug_implementations)]

//! Client library implementation of the [Open Metrics
Expand Down
3 changes: 3 additions & 0 deletions src/metrics.rs
Expand Up @@ -9,10 +9,13 @@ pub mod info;

/// A metric that is aware of its Open Metrics metric type.
pub trait TypedMetric {
/// The OpenMetrics metric type.
const TYPE: MetricType = MetricType::Unknown;
}

/// OpenMetrics metric type.
#[derive(Clone, Copy, Debug)]
#[allow(missing_docs)]
pub enum MetricType {
Counter,
Gauge,
Expand Down
5 changes: 5 additions & 0 deletions src/metrics/counter.rs
Expand Up @@ -45,6 +45,7 @@ pub struct Counter<N = u64, A = AtomicU64> {
phantom: PhantomData<N>,
}

/// Open Metrics [`Counter`] to measure discrete events.
#[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
#[derive(Debug)]
pub struct Counter<N = u32, A = AtomicU32> {
Expand Down Expand Up @@ -99,11 +100,15 @@ impl<N, A: Atomic<N>> Counter<N, A> {
}
}

/// Atomic operations for a [`Counter`] value store.
pub trait Atomic<N> {
/// Increase the value by `1`.
fn inc(&self) -> N;

/// Increase the value.
fn inc_by(&self, v: N) -> N;

/// Get the the value.
fn get(&self) -> N;
}

Expand Down
8 changes: 8 additions & 0 deletions src/metrics/exemplar.rs
Expand Up @@ -12,6 +12,7 @@ use std::sync::atomic::AtomicU32;
use std::sync::atomic::AtomicU64;
use std::sync::Arc;

/// An OpenMetrics exemplar.
#[derive(Debug)]
pub struct Exemplar<S, V> {
pub(crate) label_set: S,
Expand All @@ -36,6 +37,8 @@ pub struct CounterWithExemplar<S, N = u64, A = AtomicU64> {
pub(crate) inner: Arc<RwLock<CounterWithExemplarInner<S, N, A>>>,
}

/// Open Metrics [`Counter`] with an [`Exemplar`] to both measure discrete
/// events and track references to data outside of the metric set.
#[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
#[derive(Debug)]
pub struct CounterWithExemplar<S, N = u32, A = AtomicU32> {
Expand All @@ -50,6 +53,7 @@ impl<S, N, A> Clone for CounterWithExemplar<S, N, A> {
}
}

/// An OpenMetrics [`Counter`] in combination with an OpenMetrics [`Exemplar`].
#[derive(Debug)]
pub struct CounterWithExemplarInner<S, N, A> {
pub(crate) exemplar: Option<Exemplar<S, N>>,
Expand Down Expand Up @@ -132,13 +136,15 @@ impl<S> Clone for HistogramWithExemplars<S> {
}
}

/// An OpenMetrics [`Histogram`] in combination with an OpenMetrics [`Exemplar`].
#[derive(Debug)]
pub struct HistogramWithExemplarsInner<S> {
pub(crate) exemplars: HashMap<usize, Exemplar<S, f64>>,
pub(crate) histogram: Histogram,
}

impl<S> HistogramWithExemplars<S> {
/// Create a new [`HistogramWithExemplars`].
pub fn new(buckets: impl Iterator<Item = f64>) -> Self {
Self {
inner: Arc::new(RwLock::new(HistogramWithExemplarsInner {
Expand All @@ -148,6 +154,8 @@ impl<S> HistogramWithExemplars<S> {
}
}

/// Observe the given value, optionally providing a label set and thus
/// setting the [`Exemplar`] value.
pub fn observe(&self, v: f64, label_set: Option<S>) {
let mut inner = self.inner.write();
let bucket = inner.histogram.observe_and_bucket(v);
Expand Down
1 change: 1 addition & 0 deletions src/metrics/family.rs
Expand Up @@ -136,6 +136,7 @@ pub struct Family<S, M, C = fn() -> M> {
/// let metric = Family::<(), Histogram, CustomBuilder>::new_with_constructor(custom_builder);
/// ```
pub trait MetricConstructor<M> {
/// Create a new instance of the metric type.
fn new_metric(&self) -> M;
}

Expand Down
8 changes: 8 additions & 0 deletions src/metrics/gauge.rs
Expand Up @@ -45,6 +45,7 @@ pub struct Gauge<N = u64, A = AtomicU64> {
phantom: PhantomData<N>,
}

/// Open Metrics [`Gauge`] to record current measurements.
#[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
#[derive(Debug)]
pub struct Gauge<N = u32, A = AtomicU32> {
Expand Down Expand Up @@ -110,17 +111,24 @@ impl<N, A: Atomic<N>> Gauge<N, A> {
}
}

/// Atomic operations for a [`Gauge`] value store.
pub trait Atomic<N> {
/// Increase the value by `1`.
fn inc(&self) -> N;

/// Increase the value.
fn inc_by(&self, v: N) -> N;

/// Decrease the value by `1`.
fn dec(&self) -> N;

/// Decrease the value.
fn dec_by(&self, v: N) -> N;

/// Set the value.
fn set(&self, v: N) -> N;

/// Get the value.
fn get(&self) -> N;
}

Expand Down
4 changes: 4 additions & 0 deletions src/metrics/histogram.rs
Expand Up @@ -54,6 +54,7 @@ pub(crate) struct Inner {
}

impl Histogram {
/// Create a new [`Histogram`].
pub fn new(buckets: impl Iterator<Item = f64>) -> Self {
Self {
inner: Arc::new(RwLock::new(Inner {
Expand All @@ -68,6 +69,7 @@ impl Histogram {
}
}

/// Observe the given value.
pub fn observe(&self, v: f64) {
self.observe_and_bucket(v);
}
Expand Down Expand Up @@ -110,13 +112,15 @@ impl TypedMetric for Histogram {
const TYPE: MetricType = MetricType::Histogram;
}

/// Exponential bucket distribution.
pub fn exponential_buckets(start: f64, factor: f64, length: u16) -> impl Iterator<Item = f64> {
iter::repeat(())
.enumerate()
.map(move |(i, _)| start * factor.powf(i as f64))
.take(length.into())
}

/// Linear bucket distribution.
pub fn linear_buckets(start: f64, width: f64, length: u16) -> impl Iterator<Item = f64> {
iter::repeat(())
.enumerate()
Expand Down
1 change: 1 addition & 0 deletions src/metrics/info.rs
Expand Up @@ -16,6 +16,7 @@ use crate::metrics::{MetricType, TypedMetric};
pub struct Info<S>(pub(crate) S);

impl<S> Info<S> {
/// Create [`Info`] metric with the provided label set.
pub fn new(label_set: S) -> Self {
Self(label_set)
}
Expand Down
8 changes: 8 additions & 0 deletions src/registry.rs
Expand Up @@ -274,6 +274,7 @@ impl<M: Clone> Registry<M> {
.expect("sub_registries not to be empty.")
}

/// [`Iterator`] over all metrics registered with the [`Registry`].
pub fn iter(&self) -> std::iter::Chain<MetricIterator<M>, CollectorIterator<M>> {
return self.iter_metrics().chain(self.iter_collectors());
}
Expand Down Expand Up @@ -409,6 +410,7 @@ impl From<String> for Prefix {
}
}

/// OpenMetrics metric descriptor.
#[derive(Debug, Clone)]
pub struct Descriptor {
name: String,
Expand All @@ -418,6 +420,7 @@ pub struct Descriptor {
}

impl Descriptor {
/// Creates a new [`Descriptor`].
pub fn new<N: Into<String>, H: Into<String>>(
name: N,
help: H,
Expand All @@ -440,18 +443,22 @@ impl Descriptor {
}
}

/// Returns the name of the OpenMetrics metric [`Descriptor`].
pub fn name(&self) -> &str {
&self.name
}

/// Returns the help text of the OpenMetrics metric [`Descriptor`].
pub fn help(&self) -> &str {
&self.help
}

/// Returns the unit of the OpenMetrics metric [`Descriptor`].
pub fn unit(&self) -> &Option<Unit> {
&self.unit
}

/// Returns the label set of the OpenMetrics metric [`Descriptor`].
pub fn labels(&self) -> &[(Cow<'static, str>, Cow<'static, str>)] {
&self.labels
}
Expand All @@ -461,6 +468,7 @@ impl Descriptor {
///
/// See [`Unit::Other`] to specify alternative units.
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum Unit {
Amperes,
Bytes,
Expand Down

0 comments on commit 7978ab5

Please sign in to comment.