From 2649447198c7c3dbe2cce611f39de4c16c1f530f Mon Sep 17 00:00:00 2001 From: Max Inden Date: Sun, 14 May 2023 08:47:40 +0200 Subject: [PATCH] refactor(family): introduce `ConstFamily` type (#138) Signed-off-by: Max Inden --- CHANGELOG.md | 6 ++++++ Cargo.toml | 2 +- src/metrics/family.rs | 26 +++++++++++++++++++++++--- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 342eb376..3a8f53b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` with a new type `ConstFamily` implementing `EncodeMetric`. + ## [0.20.0] ### Added diff --git a/Cargo.toml b/Cargo.toml index f3d1aad8..627f361e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "prometheus-client" -version = "0.20.0" +version = "0.21.0" authors = ["Max Inden "] edition = "2021" description = "Open Metrics client library allowing users to natively instrument applications." diff --git a/src/metrics/family.rs b/src/metrics/family.rs index 3b70eeb9..15c3c9ab 100644 --- a/src/metrics/family.rs +++ b/src/metrics/family.rs @@ -327,11 +327,31 @@ where } } -impl> EncodeMetric - for RefCell +/// 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(RefCell); + +impl ConstFamily { + /// Creates a new [`ConstFamily`]. + pub fn new(iter: I) -> Self { + Self(RefCell::new(iter)) + } +} + +impl> EncodeMetric + for ConstFamily { 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)?;