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(metrics/family): 🍫 add Family::get_or_create_clone() #244

Open
wants to merge 1 commit 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
10 changes: 9 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.23.1] - unreleased
## [0.23.2]

### Added

- `Family::get_or_create_clone` can access a metric in a labeled family. This
method avoids the risk of runtime deadlocks at the expense of incrementing
a reference count.

## [0.23.1]

### Changed

Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "prometheus-client"
version = "0.23.1"
version = "0.23.2"
authors = ["Max Inden <[email protected]>"]
edition = "2021"
description = "Open Metrics client library allowing users to natively instrument applications."
Expand Down
57 changes: 57 additions & 0 deletions src/metrics/family.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,40 @@ impl<S: Clone + std::hash::Hash + Eq, M, C> Family<S, M, C> {
}
}

impl<S: Clone + std::hash::Hash + Eq, M: Clone, C: MetricConstructor<M>> Family<S, M, C>
where
S: Clone + std::hash::Hash + Eq,
M: Clone,
C: MetricConstructor<M>,
{
/// Access a metric with the given label set, creating it if one does not yet exist.
///
/// ```
/// # use prometheus_client::metrics::counter::{Atomic, Counter};
/// # use prometheus_client::metrics::family::Family;
/// #
/// let family = Family::<Vec<(String, String)>, Counter>::default();
///
/// // Will create and return the metric with label `method="GET"` when first called.
/// family.get_or_create_clone(&vec![("method".to_owned(), "GET".to_owned())]).inc();
///
/// // Will return a clone of the existing metric on all subsequent calls.
/// family.get_or_create_clone(&vec![("method".to_owned(), "GET".to_owned())]).inc();
/// ```
///
/// Callers wishing to avoid a clone of the metric `M` can call [`Family::get_or_create()`] to
/// return a reference to the metric instead.
pub fn get_or_create_clone(&self, label_set: &S) -> M {
use std::ops::Deref;

let guard = self.get_or_create(label_set);
let metric = guard.deref().to_owned();
drop(guard);

metric
}
}

impl<S: Clone + std::hash::Hash + Eq, M, C: MetricConstructor<M>> Family<S, M, C> {
/// Access a metric with the given label set, creating it if one does not
/// yet exist.
Expand All @@ -225,6 +259,10 @@ impl<S: Clone + std::hash::Hash + Eq, M, C: MetricConstructor<M>> Family<S, M, C
/// // calls.
/// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc();
/// ```
///
/// NB: This method can cause deadlocks if multiple metrics within this family are read at
/// once. Use [`Family::get_or_create()`] if you would like to avoid this by cloning the
/// metric `M`.
pub fn get_or_create(&self, label_set: &S) -> MappedRwLockReadGuard<M> {
if let Some(metric) = self.get(label_set) {
return metric;
Expand Down Expand Up @@ -510,4 +548,23 @@ mod tests {
let non_existent_string = string_family.get(&"non_existent".to_string());
assert!(non_existent_string.is_none());
}

/// Tests that [`Family::get_or_create_clone()`] does not cause deadlocks.
#[test]
fn counter_family_does_not_deadlock() {
/// A structure we'll place two counters into, within a single expression.
struct S {
apples: Counter,
oranges: Counter,
}

let family = Family::<(&str, &str), Counter>::default();
let s = S {
apples: family.get_or_create_clone(&("kind", "apple")),
oranges: family.get_or_create_clone(&("kind", "orange")),
};

s.apples.inc();
s.oranges.inc_by(2);
}
}
Loading