Skip to content
Merged
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added `encoding::negotiate::negotiate` to choose the exposition format of a response from the `Accept` header of an HTTP request. See [PR 381].
- Added `encoding::negotiate::MediaType::encode` to encode a `Registry` into an `io::Write` in the negotiated format. See [PR 384].
- Added `http::ScrapeHandler` to answer scrapes over HTTP: it negotiates the format from the `Accept` header, encodes a `Registry` and returns the status, headers and body to copy into the response of any HTTP framework. See [PR 387].
- Added `Counter::with_created`, `ConstCounter::with_created` and `Histogram::with_created` to expose the OpenMetrics Created timestamp in the protobuf formats, so ingestors can count the first increments of a new series. Native histograms now also send `created` (their last reset) in OpenMetrics protobuf; other metrics without it encode as before. See [PR 395].

### Changed

Expand Down Expand Up @@ -40,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[PR 387]: https://github.com/prometheus/client_rust/pull/387
[PR 389]: https://github.com/prometheus/client_rust/pull/389
[PR 394]: https://github.com/prometheus/client_rust/pull/394
[PR 395]: https://github.com/prometheus/client_rust/pull/395
[Issue 382]: https://github.com/prometheus/client_rust/issues/382
[Issue 292]: https://github.com/prometheus/client_rust/issues/292
[zmij]: https://github.com/vitaut/zmij
Expand Down
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ be fixed in the future. Contributions in all forms are most welcome.

- Gauge histogram metric.

- Allow "A MetricPoint in a Metric with the type [Counter, Histogram] SHOULD have a Timestamp

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

OpenMetrics text still doesn't emit it, so could we reword this line (e.g. "Created timestamps in the OpenMetrics text format") instead of deleting it?

value called Created".
- Created timestamps in the OpenMetrics text format.

- Summary metric.

Expand Down
37 changes: 35 additions & 2 deletions src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,27 @@ impl MetricEncoder<'_> {
v: &CounterValue,
exemplar: Option<&Exemplar<S, ExemplarValue>>,
) -> Result<(), std::fmt::Error> {
for_both_mut!(self, MetricEncoderInner, e, e.encode_counter(v, exemplar))
self.encode_counter_with_created(v, exemplar, None)
}

/// Encode a counter with its created time, see
/// [`with_created`](crate::metrics::counter::Counter::with_created).
pub fn encode_counter_with_created<
S: EncodeLabelSet,
CounterValue: EncodeCounterValue,
ExemplarValue: EncodeExemplarValue,
>(
&mut self,
v: &CounterValue,
exemplar: Option<&Exemplar<S, ExemplarValue>>,
created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
for_both_mut!(
self,
MetricEncoderInner,
e,
e.encode_counter(v, exemplar, created)
)
}

/// Encode a gauge.
Expand All @@ -348,12 +368,25 @@ impl MetricEncoder<'_> {
count: u64,
buckets: &[(f64, u64)],
exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
) -> Result<(), std::fmt::Error> {
self.encode_histogram_with_created(sum, count, buckets, exemplars, None)
}

/// Encode a histogram with its created time, see
/// [`with_created`](crate::metrics::counter::Counter::with_created).
pub fn encode_histogram_with_created<S: EncodeLabelSet>(
&mut self,
sum: f64,
count: u64,
buckets: &[(f64, u64)],
exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
for_both_mut!(
self,
MetricEncoderInner,
e,
e.encode_histogram(sum, count, buckets, exemplars)
e.encode_histogram(sum, count, buckets, exemplars, created)
)
}

Expand Down
49 changes: 44 additions & 5 deletions src/encoding/openmetrics_protobuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub mod openmetrics_data_model {
include!(concat!(env!("OUT_DIR"), "/openmetrics.rs"));
}

use std::{borrow::Cow, collections::HashMap};
use std::{borrow::Cow, collections::HashMap, time::SystemTime};

use crate::metrics::MetricType;
use crate::registry::{Registry, Unit};
Expand Down Expand Up @@ -163,6 +163,7 @@ impl MetricEncoder<'_> {
&mut self,
v: &CounterValue,
exemplar: Option<&Exemplar<S, ExemplarValue>>,
created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
let mut value = openmetrics_data_model::counter_value::Total::IntValue(0);
let mut e = CounterValueEncoder { value: &mut value }.into();
Expand All @@ -175,7 +176,7 @@ impl MetricEncoder<'_> {
openmetrics_data_model::CounterValue {
total: Some(value),
exemplar: exemplar.map(|e| e.try_into()).transpose()?,
..Default::default()
created: created.map(Into::into),
},
)),
..Default::default()
Expand Down Expand Up @@ -256,6 +257,7 @@ impl MetricEncoder<'_> {
count: u64,
buckets: &[(f64, u64)],
exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
let buckets = buckets
.iter()
Expand All @@ -277,7 +279,7 @@ impl MetricEncoder<'_> {
value: Some(openmetrics_data_model::metric_point::Value::HistogramValue(
openmetrics_data_model::HistogramValue {
count,
created: None,
created: created.map(Into::into),
buckets,
sum: Some(openmetrics_data_model::histogram_value::Sum::DoubleValue(
sum,
Expand All @@ -297,13 +299,13 @@ impl MetricEncoder<'_> {
count: u64,
buckets: &[(f64, u64)],
exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
_native: NativeHistogram<'_>,
native: NativeHistogram<'_>,
) -> Result<(), std::fmt::Error> {
if buckets.is_empty() {
return Err(std::fmt::Error);
}

self.encode_histogram(sum, count, buckets, exemplars)
self.encode_histogram(sum, count, buckets, exemplars, native.created)
}
}

Expand Down Expand Up @@ -514,6 +516,43 @@ mod tests {
}
}

#[test]
fn encode_counter_and_histogram_with_created() {
let created = SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(1_520_430_000_123);
let expected = Some(Timestamp {
seconds: 1_520_430_000,
nanos: 123_000_000,
});

let mut registry = Registry::default();
registry.register(
"my_counter",
"My counter",
Counter::<u64>::default().with_created(created),
);
let metric_set = encode(&registry).unwrap();
match extract_metric_point_value(&metric_set) {
openmetrics_data_model::metric_point::Value::CounterValue(value) => {
assert_eq!(expected, value.created);
}
_ => panic!("wrong value type"),
}

let mut registry = Registry::default();
registry.register(
"my_histogram",
"My histogram",
Histogram::new([1.0]).with_created(created),
);
let metric_set = encode(&registry).unwrap();
match extract_metric_point_value(&metric_set) {
openmetrics_data_model::metric_point::Value::HistogramValue(value) => {
assert_eq!(expected, value.created);
}
_ => panic!("wrong value type"),
}
}

#[test]
fn encode_counter_double() {
// Using `f64`
Expand Down
65 changes: 63 additions & 2 deletions src/encoding/prometheus_protobuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ impl MetricEncoder<'_> {
&mut self,
v: &CounterValue,
exemplar: Option<&Exemplar<S, ExemplarValue>>,
created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
let mut value = 0.0;
let mut e = CounterValueEncoder { value: &mut value }.into();
Expand All @@ -262,7 +263,7 @@ impl MetricEncoder<'_> {
counter: Some(prometheus_data_model::Counter {
value,
exemplar: exemplar.map(TryInto::try_into).transpose()?,
start_timestamp: None,
start_timestamp: created.map(system_time_to_timestamp).transpose()?,
}),
..Default::default()
});
Expand Down Expand Up @@ -333,6 +334,7 @@ impl MetricEncoder<'_> {
count: u64,
buckets: &[(f64, u64)],
exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
let bucket = classic_buckets(buckets, exemplars)?;

Expand All @@ -343,7 +345,7 @@ impl MetricEncoder<'_> {
sample_count_float: 0.0,
sample_sum: sum,
bucket,
start_timestamp: None,
start_timestamp: created.map(system_time_to_timestamp).transpose()?,
..Default::default()
}),
..Default::default()
Expand Down Expand Up @@ -642,6 +644,65 @@ mod tests {
assert_eq!(1.0, metric.counter.as_ref().unwrap().value);
}

#[test]
fn encode_counter_and_histogram_with_created() {
let created = SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(1_520_430_000_123);
let expected = Some(Timestamp {
seconds: 1_520_430_000,
nanos: 123_000_000,
});

let mut registry = Registry::default();
registry.register(
"my_counter",
"My counter",
Counter::<u64>::default().with_created(created),
);
registry.register(
"my_histogram",
"My histogram",
Histogram::new([1.0]).with_created(created),
);

let metric_families = encode(&registry).unwrap();
let counter = metric_families[0].metric[0].counter.as_ref().unwrap();
assert_eq!(expected, counter.start_timestamp);
let histogram = metric_families[1].metric[0].histogram.as_ref().unwrap();
assert_eq!(expected, histogram.start_timestamp);
}

#[test]
fn classic_and_native_histogram_uses_the_created_time() {
let created = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_520_430_000);
let mut registry = Registry::default();
registry.register(
"my_histogram",
"My histogram",
Histogram::new_classic_and_native([1.0], NativeHistogramConfig::with_schema(3))
.with_created(created),
);

let metric_families = encode(&registry).unwrap();
let histogram = metric_families[0].metric[0].histogram.as_ref().unwrap();
assert_eq!(
Some(Timestamp {
seconds: 1_520_430_000,
nanos: 0
}),
histogram.start_timestamp
);
}

#[test]
fn counter_without_created_has_no_start_timestamp() {
let mut registry = Registry::default();
registry.register("my_counter", "My counter", Counter::<u64>::default());

let metric_families = encode(&registry).unwrap();
let counter = metric_families[0].metric[0].counter.as_ref().unwrap();
assert_eq!(None, counter.start_timestamp);
}

#[test]
fn encode_counter_with_unit() {
let counter: Counter = Counter::default();
Expand Down
20 changes: 19 additions & 1 deletion src/encoding/prometheus_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use crate::registry::{Prefix, Registry, Unit};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Write;
use std::time::SystemTime;

/// The `Content-Type` of the Prometheus text format (version 0.0.4).
///
Expand Down Expand Up @@ -206,6 +207,8 @@ impl MetricEncoder<'_> {
&mut self,
v: &CounterValue,
_exemplar: Option<&Exemplar<S, ExemplarValue>>,
// The Prometheus text format has no created sample.
_created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
self.write_name("")?;
self.write_labels::<NoLabelSet>(None)?;
Expand Down Expand Up @@ -262,6 +265,7 @@ impl MetricEncoder<'_> {
count: u64,
buckets: &[(f64, u64)],
_exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
_created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
let mut cumulative = 0;
let mut inf_seen = false;
Expand Down Expand Up @@ -299,7 +303,7 @@ impl MetricEncoder<'_> {
exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
_native: NativeHistogram<'_>,
) -> Result<(), std::fmt::Error> {
self.encode_histogram(sum, count, buckets, exemplars)
self.encode_histogram(sum, count, buckets, exemplars, None)
}

fn write_name(&mut self, suffix: &str) -> Result<(), std::fmt::Error> {
Expand Down Expand Up @@ -757,6 +761,20 @@ mod tests {
parse_with_python_client(Parser::PrometheusClientParser, &encoded);
}

#[test]
fn omits_created_samples() {
let created = std::time::SystemTime::now();
let mut registry = Registry::default();
let counter: Counter = Counter::default().with_created(created);
registry.register("my_counter", "My counter", counter);
let histogram = Histogram::new([1.0]).with_created(created);
registry.register("my_histogram", "My histogram", histogram);

let encoded = encode_to_string(&registry);
assert!(!encoded.contains("_created"));
parse_with_python_client(Parser::PrometheusClientParser, &encoded);
}

#[test]
fn encode_histogram() {
let mut registry = Registry::default();
Expand Down
22 changes: 21 additions & 1 deletion src/encoding/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ use crate::registry::{Prefix, Registry, Unit};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Write;
use std::time::SystemTime;

/// The `Content-Type` of the OpenMetrics text format (version 1.0.0).
///
Expand Down Expand Up @@ -446,6 +447,8 @@ impl MetricEncoder<'_> {
&mut self,
v: &CounterValue,
exemplar: Option<&Exemplar<S, ExemplarValue>>,
// Not encoded: Prometheus stores it as a series unless created-timestamp-zero-ingestion is on.
_created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
self.write_prefix_name_unit()?;

Expand Down Expand Up @@ -528,6 +531,7 @@ impl MetricEncoder<'_> {
count: u64,
buckets: &[(f64, u64)],
exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
_created: Option<SystemTime>,
) -> Result<(), std::fmt::Error> {
self.write_prefix_name_unit()?;
self.write_suffix("sum")?;
Expand Down Expand Up @@ -593,7 +597,7 @@ impl MetricEncoder<'_> {
return Err(std::fmt::Error);
}

self.encode_histogram(sum, count, buckets, exemplars)
self.encode_histogram(sum, count, buckets, exemplars, None)
}

/// Encode an exemplar for the given metric.
Expand Down Expand Up @@ -1114,6 +1118,22 @@ mod tests {
parse_with_python_client(Parser::OpenMetricsParser, &encoded);
}

#[test]
fn omits_created_samples() {
let created = SystemTime::now();
let mut registry = Registry::default();
let counter: Counter = Counter::default().with_created(created);
registry.register("my_counter", "My counter", counter);
let histogram = Histogram::new([1.0]).with_created(created);
registry.register("my_histogram", "My histogram", histogram);

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

assert!(!encoded.contains("_created"));
parse_with_python_client(Parser::OpenMetricsParser, &encoded);
}

#[test]
fn encode_counter_with_unit() {
let mut registry = Registry::default();
Expand Down
Loading
Loading