Skip to content

Commit 98f5690

Browse files
authored
massive rework to make metric description more succinct (#260)
Signed-off-by: Toby Lawrence <[email protected]>
1 parent 6ceb065 commit 98f5690

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+743
-1161
lines changed

metrics-benchmark/src/main.rs

+17-59
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use hdrhistogram::Histogram as HdrHistogram;
44
use log::{error, info};
55
use metrics::{
66
gauge, histogram, increment_counter, register_counter, register_gauge, register_histogram,
7-
Counter, Gauge, Histogram, Key, Recorder, Unit,
7+
Counter, Gauge, Histogram, Key, KeyName, Recorder, Unit,
88
};
99
use metrics_util::{Registry, StandardPrimitives};
1010
use quanta::{Clock, Instant as QuantaInstant};
@@ -47,16 +47,12 @@ pub struct BenchmarkingRecorder {
4747
impl BenchmarkingRecorder {
4848
/// Creates a new `BenchmarkingRecorder`.
4949
pub fn new() -> BenchmarkingRecorder {
50-
BenchmarkingRecorder {
51-
registry: Arc::new(Registry::new()),
52-
}
50+
BenchmarkingRecorder { registry: Arc::new(Registry::new()) }
5351
}
5452

5553
/// Gets a `Controller` attached to this recorder.
5654
pub fn controller(&self) -> Controller {
57-
Controller {
58-
registry: self.registry.clone(),
59-
}
55+
Controller { registry: self.registry.clone() }
6056
}
6157

6258
/// Installs this recorder as the global recorder.
@@ -66,31 +62,22 @@ impl BenchmarkingRecorder {
6662
}
6763

6864
impl Recorder for BenchmarkingRecorder {
69-
fn describe_counter(&self, key: &Key, _: Option<Unit>, _: Option<&'static str>) {
70-
self.registry.get_or_create_counter(key, |_| {})
71-
}
65+
fn describe_counter(&self, _: KeyName, _: Option<Unit>, _: &'static str) {}
7266

73-
fn describe_gauge(&self, key: &Key, _: Option<Unit>, _: Option<&'static str>) {
74-
self.registry.get_or_create_gauge(key, |_| {})
75-
}
67+
fn describe_gauge(&self, _: KeyName, _: Option<Unit>, _: &'static str) {}
7668

77-
fn describe_histogram(&self, key: &Key, _: Option<Unit>, _: Option<&'static str>) {
78-
self.registry.get_or_create_histogram(key, |_| {})
79-
}
69+
fn describe_histogram(&self, _: KeyName, _: Option<Unit>, _: &'static str) {}
8070

8171
fn register_counter(&self, key: &Key) -> Counter {
82-
self.registry
83-
.get_or_create_counter(key, |c| Counter::from_arc(c.clone()))
72+
self.registry.get_or_create_counter(key, |c| Counter::from_arc(c.clone()))
8473
}
8574

8675
fn register_gauge(&self, key: &Key) -> Gauge {
87-
self.registry
88-
.get_or_create_gauge(key, |g| Gauge::from_arc(g.clone()))
76+
self.registry.get_or_create_gauge(key, |g| Gauge::from_arc(g.clone()))
8977
}
9078

9179
fn register_histogram(&self, key: &Key) -> Histogram {
92-
self.registry
93-
.get_or_create_histogram(key, |h| Histogram::from_arc(h.clone()))
80+
self.registry.get_or_create_histogram(key, |h| Histogram::from_arc(h.clone()))
9481
}
9582
}
9683

@@ -131,11 +118,7 @@ impl Generator {
131118
let t1 = clock.recent();
132119

133120
if let Some(t0) = self.t0 {
134-
let start = if loop_counter % LOOP_SAMPLE == 0 {
135-
Some(clock.now())
136-
} else {
137-
None
138-
};
121+
let start = if loop_counter % LOOP_SAMPLE == 0 { Some(clock.now()) } else { None };
139122

140123
increment_counter!("ok");
141124
gauge!("total", self.gauge as f64);
@@ -146,8 +129,7 @@ impl Generator {
146129
self.hist.saturating_record(delta.as_nanos() as u64);
147130

148131
// We also increment our global counter for the sample rate here.
149-
self.rate_counter
150-
.fetch_add(LOOP_SAMPLE * 3, Ordering::AcqRel);
132+
self.rate_counter.fetch_add(LOOP_SAMPLE * 3, Ordering::AcqRel);
151133

152134
if self.done.load(Ordering::Relaxed) {
153135
break;
@@ -175,11 +157,7 @@ impl Generator {
175157
let t1 = clock.recent();
176158

177159
if let Some(t0) = self.t0 {
178-
let start = if loop_counter % LOOP_SAMPLE == 0 {
179-
Some(clock.now())
180-
} else {
181-
None
182-
};
160+
let start = if loop_counter % LOOP_SAMPLE == 0 { Some(clock.now()) } else { None };
183161

184162
counter.increment(1);
185163
gauge.set(self.gauge as f64);
@@ -190,8 +168,7 @@ impl Generator {
190168
self.hist.saturating_record(delta.as_nanos() as u64);
191169

192170
// We also increment our global counter for the sample rate here.
193-
self.rate_counter
194-
.fetch_add(LOOP_SAMPLE * 3, Ordering::AcqRel);
171+
self.rate_counter.fetch_add(LOOP_SAMPLE * 3, Ordering::AcqRel);
195172

196173
if self.done.load(Ordering::Relaxed) {
197174
break;
@@ -226,12 +203,7 @@ fn print_usage(program: &str, opts: &Options) {
226203
pub fn opts() -> Options {
227204
let mut opts = Options::new();
228205

229-
opts.optopt(
230-
"d",
231-
"duration",
232-
"number of seconds to run the benchmark",
233-
"INTEGER",
234-
);
206+
opts.optopt("d", "duration", "number of seconds to run the benchmark", "INTEGER");
235207
opts.optopt(
236208
"m",
237209
"mode",
@@ -267,25 +239,11 @@ fn main() {
267239
info!("metrics benchmark");
268240

269241
// Build our sink and configure the facets.
270-
let seconds = matches
271-
.opt_str("duration")
272-
.unwrap_or_else(|| "60".to_owned())
273-
.parse()
274-
.unwrap();
275-
let producers = matches
276-
.opt_str("producers")
277-
.unwrap_or_else(|| "1".to_owned())
278-
.parse()
279-
.unwrap();
242+
let seconds = matches.opt_str("duration").unwrap_or_else(|| "60".to_owned()).parse().unwrap();
243+
let producers = matches.opt_str("producers").unwrap_or_else(|| "1".to_owned()).parse().unwrap();
280244
let mode = matches
281245
.opt_str("mode")
282-
.map(|s| {
283-
if s.to_ascii_lowercase() == "fast" {
284-
"fast"
285-
} else {
286-
"slow"
287-
}
288-
})
246+
.map(|s| if s.to_ascii_lowercase() == "fast" { "fast" } else { "slow" })
289247
.unwrap_or_else(|| "slow")
290248
.to_owned();
291249

metrics-exporter-prometheus/examples/prometheus_push_gateway.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,7 @@ fn main() {
2121
tracing_subscriber::fmt::init();
2222

2323
PrometheusBuilder::new()
24-
.with_push_gateway(
25-
"http://127.0.0.1:9091/metrics/job/example",
26-
Duration::from_secs(10),
27-
)
24+
.with_push_gateway("http://127.0.0.1:9091/metrics/job/example", Duration::from_secs(10))
2825
.expect("push gateway endpoint should be valid")
2926
.idle_timeout(
3027
MetricKindMask::COUNTER | MetricKindMask::HISTOGRAM,
@@ -39,10 +36,7 @@ fn main() {
3936
//
4037
// Registering metrics ahead of using them is not required, but is the only way to specify the
4138
// description of a metric.
42-
describe_counter!(
43-
"tcp_server_loops",
44-
"The iterations of the TCP server event loop so far."
45-
);
39+
describe_counter!("tcp_server_loops", "The iterations of the TCP server event loop so far.");
4640
describe_histogram!(
4741
"tcp_server_loop_delta_secs",
4842
"The time taken for iterations of the TCP server event loop."

metrics-exporter-prometheus/examples/prometheus_server.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,7 @@ fn main() {
2929
//
3030
// Registering metrics ahead of using them is not required, but is the only way to specify the
3131
// description of a metric.
32-
describe_counter!(
33-
"tcp_server_loops",
34-
"The iterations of the TCP server event loop so far."
35-
);
32+
describe_counter!("tcp_server_loops", "The iterations of the TCP server event loop so far.");
3633
describe_histogram!(
3734
"tcp_server_loop_delta_secs",
3835
"The time taken for iterations of the TCP server event loop."

metrics-exporter-prometheus/src/builder.rs

+15-40
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,7 @@ enum ExporterConfig {
6464
}
6565

6666
impl ExporterConfig {
67-
#[cfg_attr(
68-
not(any(feature = "http-listener", feature = "push-gateway")),
69-
allow(dead_code)
70-
)]
67+
#[cfg_attr(not(any(feature = "http-listener", feature = "push-gateway")), allow(dead_code))]
7168
fn as_type_str(&self) -> &'static str {
7269
match self {
7370
#[cfg(feature = "http-listener")]
@@ -81,10 +78,7 @@ impl ExporterConfig {
8178

8279
/// Builder for creating and installing a Prometheus recorder/exporter.
8380
pub struct PrometheusBuilder {
84-
#[cfg_attr(
85-
not(any(feature = "http-listener", feature = "push-gateway")),
86-
allow(dead_code)
87-
)]
81+
#[cfg_attr(not(any(feature = "http-listener", feature = "push-gateway")), allow(dead_code))]
8882
exporter_config: ExporterConfig,
8983
#[cfg(feature = "http-listener")]
9084
allowed_addresses: Option<Vec<IpNet>>,
@@ -134,9 +128,7 @@ impl PrometheusBuilder {
134128
#[cfg(feature = "http-listener")]
135129
#[cfg_attr(docsrs, doc(cfg(feature = "http-listener")))]
136130
pub fn with_http_listener(mut self, addr: impl Into<SocketAddr>) -> Self {
137-
self.exporter_config = ExporterConfig::HttpListener {
138-
listen_address: addr.into(),
139-
};
131+
self.exporter_config = ExporterConfig::HttpListener { listen_address: addr.into() };
140132
self
141133
}
142134

@@ -292,11 +284,7 @@ impl PrometheusBuilder {
292284
/// information on defining a metric kind mask.
293285
pub fn idle_timeout(mut self, mask: MetricKindMask, timeout: Option<Duration>) -> Self {
294286
self.idle_timeout = timeout;
295-
self.recency_mask = if self.idle_timeout.is_none() {
296-
MetricKindMask::NONE
297-
} else {
298-
mask
299-
};
287+
self.recency_mask = if self.idle_timeout.is_none() { MetricKindMask::NONE } else { mask };
300288
self
301289
}
302290

@@ -326,10 +314,7 @@ impl PrometheusBuilder {
326314
/// If there is an error while either building the recorder and exporter, or installing the
327315
/// recorder and exporter, an error variant will be returned describing the error.
328316
#[cfg(any(feature = "http-listener", feature = "push-gateway"))]
329-
#[cfg_attr(
330-
docsrs,
331-
doc(cfg(any(feature = "http-listener", feature = "push-gateway")))
332-
)]
317+
#[cfg_attr(docsrs, doc(cfg(any(feature = "http-listener", feature = "push-gateway"))))]
333318
pub fn install(self) -> Result<(), BuildError> {
334319
let recorder = if let Ok(handle) = runtime::Handle::try_current() {
335320
let (recorder, exporter) = {
@@ -341,10 +326,8 @@ impl PrometheusBuilder {
341326

342327
recorder
343328
} else {
344-
let thread_name = format!(
345-
"metrics-exporter-prometheus-{}",
346-
self.exporter_config.as_type_str()
347-
);
329+
let thread_name =
330+
format!("metrics-exporter-prometheus-{}", self.exporter_config.as_type_str());
348331

349332
let runtime = runtime::Builder::new_current_thread()
350333
.enable_all()
@@ -402,10 +385,7 @@ impl PrometheusBuilder {
402385
/// If there is an error while building the recorder and exporter, an error variant will be
403386
/// returned describing the error.
404387
#[cfg(any(feature = "http-listener", feature = "push-gateway"))]
405-
#[cfg_attr(
406-
docsrs,
407-
doc(cfg(any(feature = "http-listener", feature = "push-gateway")))
408-
)]
388+
#[cfg_attr(docsrs, doc(cfg(any(feature = "http-listener", feature = "push-gateway"))))]
409389
#[cfg_attr(not(feature = "http-listener"), allow(unused_mut))]
410390
pub fn build(mut self) -> Result<(PrometheusRecorder, ExporterFuture), BuildError> {
411391
#[cfg(feature = "http-listener")]
@@ -428,9 +408,7 @@ impl PrometheusBuilder {
428408
// If the allowlist is empty, the request is allowed. Otherwise, it must
429409
// match one of the entries in the allowlist or it will be denied.
430410
let is_allowed = allowed_addresses.as_ref().map_or(true, |addresses| {
431-
addresses
432-
.iter()
433-
.any(|address| address.contains(&remote_addr))
411+
addresses.iter().any(|address| address.contains(&remote_addr))
434412
});
435413

436414
let handle = handle.clone();
@@ -551,7 +529,7 @@ mod tests {
551529

552530
use quanta::Clock;
553531

554-
use metrics::{Key, Label, Recorder};
532+
use metrics::{Key, KeyName, Label, Recorder};
555533
use metrics_util::MetricKindMask;
556534

557535
use super::{Matcher, PrometheusBuilder};
@@ -751,9 +729,7 @@ mod tests {
751729

752730
#[test]
753731
pub fn test_global_labels_overrides() {
754-
let recorder = PrometheusBuilder::new()
755-
.add_global_label("foo", "foo")
756-
.build_recorder();
732+
let recorder = PrometheusBuilder::new().add_global_label("foo", "foo").build_recorder();
757733

758734
let key =
759735
Key::from_name("overridden").with_extra_labels(vec![Label::new("foo", "overridden")]);
@@ -769,13 +745,12 @@ mod tests {
769745

770746
#[test]
771747
pub fn test_sanitized_render() {
772-
let recorder = PrometheusBuilder::new()
773-
.add_global_label("foo:", "foo")
774-
.build_recorder();
748+
let recorder = PrometheusBuilder::new().add_global_label("foo:", "foo").build_recorder();
775749

776-
let key = Key::from_name("yee_haw:lets go")
750+
let key_name = KeyName::from("yee_haw:lets go");
751+
let key = Key::from_name(key_name.clone())
777752
.with_extra_labels(vec![Label::new("øhno", "\"yeet\nies\\\"")]);
778-
recorder.describe_counter(&key, None, Some("\"Simplë stuff.\nRëally.\""));
753+
recorder.describe_counter(key_name, None, "\"Simplë stuff.\nRëally.\"");
779754
let counter1 = recorder.register_counter(&key);
780755
counter1.increment(1);
781756

metrics-exporter-prometheus/src/common.rs

+1-6
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,7 @@ mod tests {
185185

186186
#[test]
187187
fn test_sanitize_metric_name_known_cases() {
188-
let cases = &[
189-
("*", "_"),
190-
("\"", "_"),
191-
("foo_bar", "foo_bar"),
192-
("1foobar", "_foobar"),
193-
];
188+
let cases = &[("*", "_"), ("\"", "_"), ("foo_bar", "foo_bar"), ("1foobar", "_foobar")];
194189

195190
for (input, expected) in cases {
196191
let result = sanitize_metric_name(input);

0 commit comments

Comments
 (0)