Skip to content

Commit

Permalink
refactor(family): introduce ConstFamily type (#138)
Browse files Browse the repository at this point in the history
Signed-off-by: Max Inden <[email protected]>
  • Loading branch information
mxinden authored May 14, 2023
1 parent 85033bf commit 2649447
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ 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.21.0]

### Changed

- Replace `impl EncodeMetric for RefCell<T>` with a new type `ConstFamily` implementing `EncodeMetric`.

## [0.20.0]

### Added
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.20.0"
version = "0.21.0"
authors = ["Max Inden <[email protected]>"]
edition = "2021"
description = "Open Metrics client library allowing users to natively instrument applications."
Expand Down
26 changes: 23 additions & 3 deletions src/metrics/family.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,11 +327,31 @@ where
}
}

impl<S: EncodeLabelSet, M: EncodeMetric + TypedMetric, T: Iterator<Item = (S, M)>> EncodeMetric
for RefCell<T>
/// As a [`Family`], but constant, meaning it cannot change once created.
///
/// Needed for advanced use-cases, e.g. in combination with [`Collector`](crate::collector::Collector).
///
/// Note that a [`ConstFamily`], given that it is based on an [`Iterator`], can
/// only be [`EncodeMetric::encode`]d once. While consecutive
/// [`EncodeMetric::encode`] calls won't panic, they won't return any metrics as
/// the provided [`Iterator`] will return [`Iterator::next`] [`None`]. Thus you
/// should not return the same [`ConstFamily`] in more than one
/// [`Collector::collect`](crate::collector::Collector::collect) calls.
#[derive(Debug, Default)]
pub struct ConstFamily<I>(RefCell<I>);

impl<I> ConstFamily<I> {
/// Creates a new [`ConstFamily`].
pub fn new(iter: I) -> Self {
Self(RefCell::new(iter))
}
}

impl<S: EncodeLabelSet, M: EncodeMetric + TypedMetric, I: Iterator<Item = (S, M)>> EncodeMetric
for ConstFamily<I>
{
fn encode(&self, mut encoder: MetricEncoder<'_, '_>) -> Result<(), std::fmt::Error> {
let mut iter = self.borrow_mut();
let mut iter = self.0.borrow_mut();

for (label_set, m) in iter.by_ref() {
let encoder = encoder.encode_family(&label_set)?;
Expand Down

0 comments on commit 2649447

Please sign in to comment.