1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
//! [`metrics::Recorder`] being able to stop registering new metrics in the
//! benefit of providing fast access to already registered ones.
use std::sync::Arc;
use once_cell::sync::OnceCell;
use crate::{failure::strategy::PanicInDebugNoOpInRelease, metric, storage};
use super::Builder;
/// [`metrics::Recorder`] being essential a usual [`Recorder`], which is able to
/// become a [`Frozen`] one at some point after creation.
///
/// This [`FreezableRecorder`] is capable of registering metrics in its
/// [`prometheus::Registry`] on the fly, but only before being [`.freeze()`]d.
/// By default, the [`prometheus::default_registry()`] is used.
///
/// # Example
///
/// ```rust
/// let recorder = metrics_prometheus::install_freezable();
///
/// // Either use `metrics` crate interfaces.
/// metrics::increment_counter!("count", "whose" => "mine", "kind" => "owned");
/// metrics::increment_counter!("count", "whose" => "mine", "kind" => "ref");
/// metrics::increment_counter!("count", "kind" => "owned", "whose" => "dummy");
///
/// // Or construct and provide `prometheus` metrics directly.
/// recorder.register_metric(prometheus::Gauge::new("value", "help")?);
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&prometheus::default_registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP count count
/// ## TYPE count counter
/// count{kind="owned",whose="dummy"} 1
/// count{kind="owned",whose="mine"} 1
/// count{kind="ref",whose="mine"} 1
/// ## HELP value help
/// ## TYPE value gauge
/// value 0
/// "#
/// .trim(),
/// );
///
/// recorder.freeze();
///
/// // However, you cannot register new metrics after freezing.
/// // This is just no-op.
/// metrics::increment_gauge!("new", 2.0);
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&prometheus::default_registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP count count
/// ## TYPE count counter
/// count{kind="owned",whose="dummy"} 1
/// count{kind="owned",whose="mine"} 1
/// count{kind="ref",whose="mine"} 1
/// ## HELP value help
/// ## TYPE value gauge
/// value 0
/// "#
/// .trim(),
/// );
///
/// // Luckily, metrics still can be described anytime after being registered,
/// // even after freezing.
/// metrics::describe_counter!("count", "Example of counter.");
/// metrics::describe_gauge!("value", "Example of gauge.");
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&recorder.registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP count Example of counter.
/// ## TYPE count counter
/// count{kind="owned",whose="dummy"} 1
/// count{kind="owned",whose="mine"} 1
/// count{kind="ref",whose="mine"} 1
/// ## HELP value Example of gauge.
/// ## TYPE value gauge
/// value 0
/// "#
/// .trim(),
/// );
/// # Ok::<_, prometheus::Error>(())
/// ```
///
/// # Performance
///
/// This [`FreezableRecorder`] provides the same overhead of accessing an
/// already registered metric as a usual [`Recorder`] or a [`FrozenRecorder`],
/// depending on whether it has been [`.freeze()`]d, plus an [`AtomicBool`]
/// loading to check whether it has been actually [`.freeze()`]d.
///
/// So, before [`.freeze()`] it's: [`AtomicBool`] loading plus [`read`-lock] on
/// a sharded [`HashMap`] plus [`Arc`] cloning.
///
/// And after [`.freeze()`]: [`AtomicBool`] loading plus regular [`HashMap`]
/// lookup plus [`Arc`] cloning.
///
/// # Errors
///
/// [`prometheus::Registry`] has far more stricter semantics than the ones
/// implied by a [`metrics::Recorder`]. That's why incorrect usage of
/// [`prometheus`] metrics via [`metrics`] crate will inevitably lead to a
/// [`prometheus::Registry`] returning a [`prometheus::Error`] instead of
/// registering the metric. The returned [`prometheus::Error`] can be either
/// turned into a panic, or just silently ignored, making this
/// [`FreezableRecorder`] to return a no-op metric instead (see
/// [`metrics::Counter::noop()`] for example).
///
/// The desired behavior can be specified with a [`failure::Strategy`]
/// implementation of this [`FreezableRecorder`]. By default a
/// [`PanicInDebugNoOpInRelease`] [`failure::Strategy`] is used. See
/// [`failure::strategy`] module for other available [`failure::Strategy`]s, or
/// provide your own one by implementing the [`failure::Strategy`] trait.
///
/// ```rust,should_panic
/// use metrics_prometheus::failure::strategy;
///
/// let recoder = metrics_prometheus::Recorder::builder()
/// .with_failure_strategy(strategy::Panic)
/// .build_freezable_and_install();
///
/// metrics::increment_counter!("count", "kind" => "owned");
///
/// recoder.freeze();
///
/// // This panics, as such labeling is not allowed by `prometheus` crate.
/// metrics::increment_counter!("count", "whose" => "mine");
/// ```
///
/// [`AtomicBool`]: std::sync::atomic::AtomicBool
/// [`failure::Strategy`]: crate::failure::Strategy
/// [`FreezableRecorder`]: Recorder
/// [`Frozen`]: super::Frozen
/// [`FrozenRecorder`]: super::Frozen
/// [`HashMap`]: std::collections::HashMap
/// [`Recorder`]: super::Recorder
/// [`.freeze()`]: Self::freeze()
/// [`read`-lock]: std::sync::RwLock::read()
#[derive(Clone, Debug)]
pub struct Recorder<FailureStrategy = PanicInDebugNoOpInRelease> {
/// Usual [`Recorder`] for registering metrics on the fly.
///
/// [`Recorder`]: super::Recorder
usual: super::Recorder<FailureStrategy>,
/// [`FrozenRecorder`] for fast access to already registered metrics.
///
/// This one is built by draining the [`Recorder::usual`].
///
/// [`FrozenRecorder`]: super::Frozen
frozen: Arc<OnceCell<super::Frozen<FailureStrategy>>>,
}
impl Recorder {
/// Starts building a new [`FreezableRecorder`] on top of the
/// [`prometheus::default_registry()`].
///
/// [`FreezableRecorder`]: Recorder
pub fn builder() -> Builder {
super::Recorder::builder()
}
}
impl<S> Recorder<S> {
/// Wraps the provided `usual` [`Recorder`] into a [`Freezable`] one.
///
/// [`Freezable`]: Recorder
/// [`Recorder`]: super::Recorder
pub(super) fn wrap(usual: super::Recorder<S>) -> Self {
Self { usual, frozen: Arc::default() }
}
/// Returns the underlying [`prometheus::Registry`] backing this
/// [`FreezableRecorder`].
///
/// # Warning
///
/// Any [`prometheus`] metrics, registered directly in the returned
/// [`prometheus::Registry`], cannot be used via this [`metrics::Recorder`]
/// (and, so, [`metrics`] crate interfaces), and trying to use them will
/// inevitably cause a [`prometheus::Error`] being emitted.
///
/// ```rust,should_panic
/// use metrics_prometheus::failure::strategy;
///
/// let recorder = metrics_prometheus::Recorder::builder()
/// .with_failure_strategy(strategy::Panic)
/// .build_freezable_and_install();
///
/// let counter = prometheus::IntCounter::new("value", "help")?;
/// recorder.registry().register(Box::new(counter))?;
///
/// // panics: Duplicate metrics collector registration attempted
/// metrics::increment_counter!("value");
/// # Ok::<_, prometheus::Error>(())
/// ```
///
/// [`FreezableRecorder`]: Recorder
#[must_use]
pub const fn registry(&self) -> &prometheus::Registry {
&self.usual.storage.prometheus
}
/// Tries to register the provided [`prometheus`] `metric` in the underlying
/// [`prometheus::Registry`] in the way making it usable via this
/// [`FreezableRecorder`] (and, so, [`metrics`] crate interfaces).
///
/// No-op, if this [`FreezableRecorder`] has been [`.freeze()`]d.
///
/// Accepts only the following [`prometheus`] metrics:
/// - [`prometheus::IntCounter`], [`prometheus::IntCounterVec`]
/// - [`prometheus::Gauge`], [`prometheus::GaugeVec`]
/// - [`prometheus::Histogram`], [`prometheus::HistogramVec`]
///
/// # Errors
///
/// If the underlying [`prometheus::Registry`] fails to register the
/// provided `metric`.
///
/// # Example
///
/// ```rust
/// let recorder = metrics_prometheus::install_freezable();
///
/// let counter = prometheus::IntCounterVec::new(
/// prometheus::opts!("value", "help"),
/// &["whose", "kind"],
/// )?;
///
/// recorder.try_register_metric(counter.clone())?;
///
/// counter.with_label_values(&["mine", "owned"]).inc();
/// counter.with_label_values(&["foreign", "ref"]).inc_by(2);
/// counter.with_label_values(&["foreign", "owned"]).inc_by(3);
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&prometheus::default_registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP value help
/// ## TYPE value counter
/// value{kind="owned",whose="foreign"} 3
/// value{kind="owned",whose="mine"} 1
/// value{kind="ref",whose="foreign"} 2
/// "#
/// .trim(),
/// );
///
/// recorder.freeze();
/// // No-op, as the `Recorder` has been frozen.
/// recorder.try_register_metric(prometheus::Gauge::new("new", "help")?)?;
///
/// metrics::increment_counter!(
/// "value", "whose" => "mine", "kind" => "owned",
/// );
/// metrics::increment_counter!(
/// "value", "whose" => "mine", "kind" => "ref",
/// );
/// metrics::increment_counter!(
/// "value", "kind" => "owned", "whose" => "foreign",
/// );
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&recorder.registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP value help
/// ## TYPE value counter
/// value{kind="owned",whose="foreign"} 4
/// value{kind="owned",whose="mine"} 2
/// value{kind="ref",whose="foreign"} 2
/// value{kind="ref",whose="mine"} 1
/// "#
/// .trim(),
/// );
/// # Ok::<_, prometheus::Error>(())
/// ```
///
/// [`FreezableRecorder`]: Recorder
/// [`.freeze()`]: Recorder::freeze()
pub fn try_register_metric<M>(&self, metric: M) -> prometheus::Result<()>
where
M: metric::Bundled + prometheus::core::Collector,
<M as metric::Bundled>::Bundle:
prometheus::core::Collector + Clone + 'static,
storage::Mutable: storage::Get<
storage::mutable::Collection<<M as metric::Bundled>::Bundle>,
>,
{
if self.frozen.get().is_none() {
self.usual.try_register_metric(metric)?;
}
Ok(())
}
/// Registers the provided [`prometheus`] `metric` in the underlying
/// [`prometheus::Registry`] in the way making it usable via this
/// [`FreezableRecorder`] (and, so, [`metrics`] crate interfaces).
///
/// No-op, if this [`FreezableRecorder`] has been [`.freeze()`]d.
///
/// Accepts only the following [`prometheus`] metrics:
/// - [`prometheus::IntCounter`], [`prometheus::IntCounterVec`]
/// - [`prometheus::Gauge`], [`prometheus::GaugeVec`]
/// - [`prometheus::Histogram`], [`prometheus::HistogramVec`]
///
/// # Panics
///
/// If the underlying [`prometheus::Registry`] fails to register the
/// provided `metric`.
///
/// # Example
///
/// ```rust
/// let recorder = metrics_prometheus::install_freezable();
///
/// let gauge = prometheus::GaugeVec::new(
/// prometheus::opts!("value", "help"),
/// &["whose", "kind"],
/// )?;
///
/// recorder.register_metric(gauge.clone());
///
/// gauge.with_label_values(&["mine", "owned"]).inc();
/// gauge.with_label_values(&["foreign", "ref"]).set(2.0);
/// gauge.with_label_values(&["foreign", "owned"]).set(3.0);
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&prometheus::default_registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP value help
/// ## TYPE value gauge
/// value{kind="owned",whose="foreign"} 3
/// value{kind="owned",whose="mine"} 1
/// value{kind="ref",whose="foreign"} 2
/// "#
/// .trim(),
/// );
///
/// recorder.freeze();
/// // No-op, as the `Recorder` has been frozen.
/// recorder.register_metric(prometheus::Gauge::new("new", "help")?);
///
/// metrics::increment_gauge!(
/// "value", 2.0, "whose" => "mine", "kind" => "owned",
/// );
/// metrics::decrement_gauge!(
/// "value", 2.0, "whose" => "mine", "kind" => "ref",
/// );
/// metrics::increment_gauge!(
/// "value", 2.0, "kind" => "owned", "whose" => "foreign",
/// );
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&recorder.registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP value help
/// ## TYPE value gauge
/// value{kind="owned",whose="foreign"} 5
/// value{kind="owned",whose="mine"} 3
/// value{kind="ref",whose="foreign"} 2
/// value{kind="ref",whose="mine"} -2
/// "#
/// .trim(),
/// );
/// # Ok::<_, prometheus::Error>(())
/// ```
///
/// [`FreezableRecorder`]: Recorder
/// [`.freeze()`]: Recorder::freeze()
pub fn register_metric<M>(&self, metric: M)
where
M: metric::Bundled + prometheus::core::Collector,
<M as metric::Bundled>::Bundle:
prometheus::core::Collector + Clone + 'static,
storage::Mutable: storage::Get<
storage::mutable::Collection<<M as metric::Bundled>::Bundle>,
>,
{
if self.frozen.get().is_none() {
self.usual.register_metric(metric);
}
}
/// Freezes this [`FreezableRecorder`], making it unable to register new
/// [`prometheus`] metrics in the benefit of providing faster access to the
/// already registered ones.
///
/// No-op, if this [`FreezableRecorder`] has been [`.freeze()`]d already.
///
/// # Performance
///
/// This [`FreezableRecorder`] provides the same overhead of accessing an
/// already registered metric as a usual [`Recorder`] or a
/// [`FrozenRecorder`], depending on whether it has been [`.freeze()`]d,
/// plus an [`AtomicBool`] loading to check whether it has been actually
/// [`.freeze()`]d.
///
/// So, before [`.freeze()`] it's: [`AtomicBool`] loading plus [`read`-lock]
/// on a sharded [`HashMap`] plus [`Arc`] cloning.
///
/// And after [`.freeze()`]: [`AtomicBool`] loading plus regular [`HashMap`]
/// lookup plus [`Arc`] cloning.
///
/// # Example
///
/// ```rust
/// let recorder = metrics_prometheus::install_freezable();
///
/// metrics::increment_counter!("count");
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&recorder.registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP count count
/// ## TYPE count counter
/// count 1
/// "#
/// .trim(),
/// );
///
/// recorder.freeze();
///
/// metrics::increment_counter!("count");
/// // This is no-op.
/// metrics::increment_counter!("new");
///
/// let report = prometheus::TextEncoder::new()
/// .encode_to_string(&recorder.registry().gather())?;
/// assert_eq!(
/// report.trim(),
/// r#"
/// ## HELP count count
/// ## TYPE count counter
/// count 2
/// "#
/// .trim(),
/// );
/// # Ok::<_, prometheus::Error>(())
/// ```
///
/// [`AtomicBool`]: std::sync::atomic::AtomicBool
/// [`FreezableRecorder`]: Recorder
/// [`FrozenRecorder`]: super::Frozen
/// [`HashMap`]: std::collections::HashMap
/// [`.freeze()`]: Recorder::freeze()
pub fn freeze(&self)
where
S: Clone,
{
let _ = self.frozen.get_or_init(|| super::Frozen {
storage: (&self.usual.storage).into(),
failure_strategy: self.usual.failure_strategy.clone(),
});
}
}
#[warn(clippy::missing_trait_methods)]
impl<S> metrics::Recorder for Recorder<S>
where
super::Recorder<S>: metrics::Recorder,
super::Frozen<S>: metrics::Recorder,
{
fn describe_counter(
&self,
name: metrics::KeyName,
unit: Option<metrics::Unit>,
description: metrics::SharedString,
) {
if let Some(frozen) = self.frozen.get() {
frozen.describe_counter(name, unit, description);
} else {
self.usual.describe_counter(name, unit, description);
}
}
fn describe_gauge(
&self,
name: metrics::KeyName,
unit: Option<metrics::Unit>,
description: metrics::SharedString,
) {
if let Some(frozen) = self.frozen.get() {
frozen.describe_gauge(name, unit, description);
} else {
self.usual.describe_gauge(name, unit, description);
}
}
fn describe_histogram(
&self,
name: metrics::KeyName,
unit: Option<metrics::Unit>,
description: metrics::SharedString,
) {
if let Some(frozen) = self.frozen.get() {
frozen.describe_histogram(name, unit, description);
} else {
self.usual.describe_histogram(name, unit, description);
}
}
fn register_counter(&self, key: &metrics::Key) -> metrics::Counter {
self.frozen.get().map_or_else(
|| self.usual.register_counter(key),
|frozen| frozen.register_counter(key),
)
}
fn register_gauge(&self, key: &metrics::Key) -> metrics::Gauge {
self.frozen.get().map_or_else(
|| self.usual.register_gauge(key),
|frozen| frozen.register_gauge(key),
)
}
fn register_histogram(&self, key: &metrics::Key) -> metrics::Histogram {
self.frozen.get().map_or_else(
|| self.usual.register_histogram(key),
|frozen| frozen.register_histogram(key),
)
}
}