Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Summary metric type #254

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ documentation = "https://docs.rs/prometheus-client"
[features]
default = []
protobuf = ["dep:prost", "dep:prost-types", "dep:prost-build"]
summary = ["dep:fastant", "dep:quantiles"]

[workspace]
members = ["derive-encode"]
Expand All @@ -22,8 +23,12 @@ dtoa = "1.0"
itoa = "1.0"
parking_lot = "0.12"
prometheus-client-derive-encode = { version = "0.4.1", path = "derive-encode" }
prost = { version = "0.12.0", optional = true }
prost-types = { version = "0.12.0", optional = true }

# Optional dependencies
fastant = { version = "0.1", optional = true }
prost = { version = "0.12", optional = true }
prost-types = { version = "0.12", optional = true }
quantiles = { version = "0.7", optional = true }

[dev-dependencies]
async-std = { version = "1", features = ["attributes"] }
Expand Down
16 changes: 16 additions & 0 deletions src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,22 @@ impl MetricEncoder<'_> {
)
}

/// Encode a summary.
#[cfg(feature = "summary")]
pub fn encode_summary<S: EncodeLabelSet>(
&mut self,
sum: f64,
count: u64,
quantiles: &[(f64, f64)],
) -> Result<(), std::fmt::Error> {
for_both_mut!(
self,
MetricEncoderInner,
e,
e.encode_summary::<S>(sum, count, quantiles)
)
}

/// Encode a metric family.
pub fn encode_family<'s, S: EncodeLabelSet>(
&'s mut self,
Expand Down
72 changes: 72 additions & 0 deletions src/encoding/protobuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ impl From<MetricType> for openmetrics_data_model::MetricType {
MetricType::Counter => openmetrics_data_model::MetricType::Counter,
MetricType::Gauge => openmetrics_data_model::MetricType::Gauge,
MetricType::Histogram => openmetrics_data_model::MetricType::Histogram,
#[cfg(feature = "summary")]
MetricType::Summary => openmetrics_data_model::MetricType::Summary,
MetricType::Info => openmetrics_data_model::MetricType::Info,
MetricType::Unknown => openmetrics_data_model::MetricType::Unknown,
}
Expand Down Expand Up @@ -288,6 +290,42 @@ impl MetricEncoder<'_> {

Ok(())
}

#[cfg(feature = "summary")]
pub fn encode_summary<S: EncodeLabelSet>(
&mut self,
sum: f64,
count: u64,
quantiles: &[(f64, f64)],
) -> Result<(), std::fmt::Error> {
let quantile = quantiles
.iter()
.enumerate()
.map(|(_, (quantile, value))| {
Ok(openmetrics_data_model::summary_value::Quantile {
quantile: *quantile,
value: *value,
})
})
.collect::<Result<Vec<_>, std::fmt::Error>>()?;

self.family.push(openmetrics_data_model::Metric {
labels: self.labels.clone(),
metric_points: vec![openmetrics_data_model::MetricPoint {
value: Some(openmetrics_data_model::metric_point::Value::SummaryValue(
openmetrics_data_model::SummaryValue {
count,
created: None,
quantile,
sum: Some(openmetrics_data_model::summary_value::Sum::DoubleValue(sum)),
},
)),
..Default::default()
}],
});

Ok(())
}
}

impl<S: EncodeLabelSet, V: EncodeExemplarValue> TryFrom<&Exemplar<S, V>>
Expand Down Expand Up @@ -749,6 +787,40 @@ mod tests {
}
}

#[cfg(feature = "summary")]
#[test]
fn encode_summary() {
use crate::metrics::summary::Summary;

let mut registry = Registry::default();
let summary = Summary::new(5, 10, vec![0.5, 0.9, 0.99], 0.01);
registry.register("my_summary", "My summary", summary.clone());
summary.observe(1.0);

let metric_set = encode(&registry).unwrap();

let family = metric_set.metric_families.first().unwrap();
assert_eq!("my_summary", family.name);
assert_eq!("My summary.", family.help);

assert_eq!(
openmetrics_data_model::MetricType::Summary as i32,
extract_metric_type(&metric_set)
);

match extract_metric_point_value(&metric_set) {
openmetrics_data_model::metric_point::Value::SummaryValue(value) => {
assert_eq!(
Some(openmetrics_data_model::summary_value::Sum::DoubleValue(1.0)),
value.sum
);
assert_eq!(1, value.count);
assert_eq!(11, value.quantile.len());
}
_ => panic!("wrong value type"),
}
}

#[test]
fn encode_histogram() {
let mut registry = Registry::default();
Expand Down
62 changes: 62 additions & 0 deletions src/encoding/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,40 @@ impl MetricEncoder<'_> {
})
}

#[cfg(feature = "summary")]
pub fn encode_summary<S: EncodeLabelSet>(
&mut self,
sum: f64,
count: u64,
quantiles: &[(f64, f64)],
) -> Result<(), std::fmt::Error> {
self.write_prefix_name_unit()?;
self.write_suffix("sum")?;
self.encode_labels::<NoLabelSet>(None)?;
self.writer.write_str(" ")?;
self.writer.write_str(dtoa::Buffer::new().format(sum))?;
self.newline()?;

self.write_prefix_name_unit()?;
self.write_suffix("count")?;
self.encode_labels::<NoLabelSet>(None)?;
self.writer.write_str(" ")?;
self.writer.write_str(itoa::Buffer::new().format(count))?;
self.newline()?;

for (_, (quantile, result)) in quantiles.iter().enumerate() {
self.write_prefix_name_unit()?;
self.encode_labels(Some(&[("quantile", *quantile)]))?;

self.writer.write_str(" ")?;
self.writer.write_str(result.to_string().as_str())?;

self.newline()?;
}

Ok(())
}

pub fn encode_histogram<S: EncodeLabelSet>(
&mut self,
sum: f64,
Expand Down Expand Up @@ -1160,6 +1194,34 @@ mod tests {
assert_eq!(&response[response.len() - 20..], "ogins_total 0\n# EOF\n");
}

#[cfg(feature = "summary")]
#[test]
fn encode_summary() {
use crate::metrics::summary::Summary;

let mut registry = Registry::default();
let summary = Summary::new(3, 10, vec![0.5, 0.9, 0.99], 0.0);
registry.register("my_summary", "My summary", summary.clone());
summary.observe(0.10);
summary.observe(0.20);
summary.observe(0.30);

let mut encoded = String::new();
encode(&mut encoded, &registry).unwrap();

let expected = "# HELP my_summary My summary.\n".to_owned()
+ "# TYPE my_summary summary\n"
+ "my_summary_sum 0.6000000000000001\n"
+ "my_summary_count 3\n"
+ "my_summary{quantile=\"0.5\"} 0.2\n"
+ "my_summary{quantile=\"0.9\"} 0.3\n"
+ "my_summary{quantile=\"0.99\"} 0.3\n"
+ "# EOF\n";
assert_eq!(expected, encoded);

parse_with_python_client(encoded);
}

fn parse_with_python_client(input: String) {
pyo3::prepare_freethreaded_python();

Expand Down
7 changes: 6 additions & 1 deletion src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pub mod family;
pub mod gauge;
pub mod histogram;
pub mod info;
#[cfg(feature = "summary")]
pub mod summary;
Comment on lines +9 to +10
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we add this line...

Suggested change
#[cfg(feature = "summary")]
pub mod summary;
#[cfg(feature = "summary")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
pub mod summary;

we'll also make sure that this shows up in the documentation generated on docs.rs, see: https://doc.rust-lang.org/rustdoc/unstable-features.html#doccfg-recording-what-platforms-or-features-are-required-for-code-to-be-present

n.b. we'd need to also add this above in lib.rs, if it's not already present:

#![cfg_attr(docsrs, feature(doc_cfg))]

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I use this trick for my crates and I'm glad to include this.

However, it seems a separated topic to this PR so I'd like to listen to maintainer's idea whether we should include it in this PR or add in a follow-up. Both works for me but different maintainers would have different preference.


/// A metric that is aware of its Open Metrics metric type.
pub trait TypedMetric {
Expand All @@ -21,12 +23,13 @@ pub enum MetricType {
Gauge,
Histogram,
Info,
#[cfg(feature = "summary")]
Summary,
Unknown,
// Not (yet) supported metric types.
//
// GaugeHistogram,
// StateSet,
// Summary
}

impl MetricType {
Expand All @@ -37,6 +40,8 @@ impl MetricType {
MetricType::Gauge => "gauge",
MetricType::Histogram => "histogram",
MetricType::Info => "info",
#[cfg(feature = "summary")]
MetricType::Summary => "summary",
MetricType::Unknown => "unknown",
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/metrics/counter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ mod tests {
// Map infinite, subnormal and NaN to 0.0.
.map(|f| if f.is_normal() { f } else { 0.0 })
.collect();
let sum = fs.iter().sum();
let sum: f64 = fs.iter().sum();
let counter = Counter::<f64, AtomicU64>::default();
for f in fs {
counter.inc_by(f);
Expand Down
Loading