Skip to content

Commit f8d3bb2

Browse files
committed
Implement methods on Registry for managing prefix and common labels
This allows users to set the registry's prefix or common labels when using the default registry.
1 parent 1e7736f commit f8d3bb2

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/registry.rs

+61
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,67 @@ impl Registry {
263263
Ok(reg)
264264
}
265265

266+
/// `prefix` returns a copy of the prefix for the registry, if any.
267+
pub fn prefix(&self) -> Option<String> {
268+
self.r.read().prefix.clone()
269+
}
270+
271+
/// `set_prefix` sets the prefix for the registry, and returns the previous
272+
/// prefix, if any. If `prefix` is empty, the function returns an error.
273+
pub fn set_prefix(&self, prefix: &str) -> Result<Option<String>> {
274+
if prefix.is_empty() {
275+
return Err(Error::Msg("empty prefix namespace".to_string()));
276+
}
277+
278+
let mut core = self.r.write();
279+
let result = core.prefix.take();
280+
core.prefix = Some(prefix.to_string());
281+
Ok(result)
282+
}
283+
284+
/// `clear_prefix` removes the prefix from the registry and returns it to
285+
/// the caller, if a prefix was set.
286+
pub fn clear_prefix(&self) -> Option<String> {
287+
let mut core = self.r.write();
288+
core.prefix.take()
289+
}
290+
291+
/// `labels` returns a copy of the common labels for the registry, if any.
292+
pub fn labels(&self) -> Option<HashMap<String, String>> {
293+
self.r.read().labels.clone()
294+
}
295+
296+
/// `insert_label` adds or updates a label in the set of common labels for
297+
/// the registry, and returns the previous value of that label, if any.
298+
/// If either `key` or `value` are empty, the function returns an error.
299+
pub fn insert_label(&self, key: &str, value: &str) -> Result<Option<String>> {
300+
if key.is_empty() {
301+
return Err(Error::Msg("empty label key".to_string()));
302+
}
303+
if value.is_empty() {
304+
return Err(Error::Msg("empty label value".to_string()));
305+
}
306+
307+
let mut core = self.r.write();
308+
309+
if core.labels.is_none() {
310+
core.labels = Some(HashMap::default());
311+
}
312+
313+
Ok(core
314+
.labels
315+
.as_mut()
316+
.unwrap()
317+
.insert(key.to_string(), value.to_string()))
318+
}
319+
320+
/// `clear_labels` removes all common labels from the registry, if any, and
321+
/// returns them to the caller.
322+
pub fn clear_labels(&self) -> Option<HashMap<String, String>> {
323+
let mut core = self.r.write();
324+
core.labels.take()
325+
}
326+
266327
/// `register` registers a new [`Collector`] to be included in metrics
267328
/// collection. It returns an error if the descriptors provided by the
268329
/// [`Collector`] are invalid or if they — in combination with descriptors of

0 commit comments

Comments
 (0)