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
//! Fast and read-only [`metrics::Recorder`].

use std::sync::Arc;

use crate::{
    failure::{self, strategy::PanicInDebugNoOpInRelease},
    storage,
};

use super::Builder;

/// [`metrics::Recorder`] allowing to access already registered metrics in a
/// [`prometheus::Registry`], but not to register new ones, and is built on top
/// of a [`storage::Immutable`].
///
/// Though this [`FrozenRecorder`] is not capable of registering new metrics in
/// its [`prometheus::Registry`] on the fly, it still does allow changing the
/// [`help` description] of already registered ones. By default, the
/// [`prometheus::default_registry()`] is used.
///
/// The only way to register metrics in this [`FrozenRecorder`] is to specify
/// them via [`Builder::with_metric()`]/[`Builder::try_with_metric()`] APIs,
/// before the [`FrozenRecorder`] is built.
///
/// # Example
///
/// ```rust
/// let registry = metrics_prometheus::Recorder::builder()
///     .with_metric(prometheus::IntCounterVec::new(
///         prometheus::opts!("count", "help"),
///         &["whose", "kind"],
///     )?)
///     .with_metric(prometheus::Gauge::new("value", "help")?)
///     .build_frozen_and_install();
///
/// // `metrics` crate interfaces allow to change already registered metrics.
/// metrics::increment_counter!("count", "whose" => "mine", "kind" => "owned");
/// metrics::increment_counter!("count", "whose" => "mine", "kind" => "ref");
/// metrics::increment_counter!("count", "kind" => "owned", "whose" => "dummy");
/// metrics::increment_gauge!("value", 1.0);
///
/// let report = prometheus::TextEncoder::new()
///     .encode_to_string(&registry.gather())?;
/// assert_eq!(
///     report.trim(),
///     r#"
/// ## HELP count help
/// ## 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 1
///     "#
///     .trim(),
/// );
///
/// // However, you cannot register new metrics. This is just no-op.
/// metrics::increment_gauge!("new", 2.0);
///
/// let report = prometheus::TextEncoder::new()
///     .encode_to_string(&registry.gather())?;
/// assert_eq!(
///     report.trim(),
///     r#"
/// ## HELP count help
/// ## 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 1
///     "#
///     .trim(),
/// );
///
/// // Luckily, metrics still can be described anytime after being registered.
/// metrics::describe_counter!("count", "Example of counter.");
/// metrics::describe_gauge!("value", "Example of gauge.");
///
/// let report = prometheus::TextEncoder::new()
///     .encode_to_string(&prometheus::default_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 1
///     "#
///     .trim(),
/// );
/// # Ok::<_, prometheus::Error>(())
/// ```
///
/// # Performance
///
/// This [`FrozenRecorder`] provides the smallest overhead of accessing an
/// already registered metric: just a 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`], which can be
/// either turned into a panic, or just silently ignored, making this
/// [`FrozenRecorder`] 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 [`FrozenRecorder`]. 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;
///
/// metrics_prometheus::Recorder::builder()
///     .with_metric(prometheus::Gauge::new("value", "help")?)
///     .with_failure_strategy(strategy::Panic)
///     .build_and_install();
///
/// metrics::increment_gauge!("value", 1.0);
/// // This panics, as such labeling is not allowed by `prometheus` crate.
/// metrics::increment_gauge!("value", 2.0, "whose" => "mine");
/// # Ok::<_, prometheus::Error>(())
/// ```
///
/// [`FrozenRecorder`]: Recorder`
/// [`HashMap`]: std::collections::HashMap
/// [`help` description]: prometheus::proto::MetricFamily::get_help
#[derive(Debug)]
pub struct Recorder<FailureStrategy = PanicInDebugNoOpInRelease> {
    /// [`storage::Immutable`] providing access to registered metrics in its
    /// [`prometheus::Registry`].
    pub(super) storage: storage::Immutable,

    /// [`failure::Strategy`] to apply when a [`prometheus::Error`] is
    /// encountered inside [`metrics::Recorder`] methods.
    pub(super) failure_strategy: FailureStrategy,
}

impl Recorder {
    /// Starts building a new [`FrozenRecorder`] on top of the
    /// [`prometheus::default_registry()`].
    ///
    /// [`FrozenRecorder`]: Recorder
    pub fn builder() -> Builder {
        super::Recorder::builder()
    }
}

impl<S> metrics::Recorder for Recorder<S>
where
    S: failure::Strategy,
{
    fn describe_counter(
        &self,
        name: metrics::KeyName,
        _: Option<metrics::Unit>,
        description: metrics::SharedString,
    ) {
        self.storage.describe::<prometheus::IntCounter>(
            name.as_str(),
            description.into_owned(),
        );
    }

    fn describe_gauge(
        &self,
        name: metrics::KeyName,
        _: Option<metrics::Unit>,
        description: metrics::SharedString,
    ) {
        self.storage.describe::<prometheus::Gauge>(
            name.as_str(),
            description.into_owned(),
        );
    }

    fn describe_histogram(
        &self,
        name: metrics::KeyName,
        _: Option<metrics::Unit>,
        description: metrics::SharedString,
    ) {
        self.storage.describe::<prometheus::Histogram>(
            name.as_str(),
            description.into_owned(),
        );
    }

    fn register_counter(&self, key: &metrics::Key) -> metrics::Counter {
        self.storage
            .get_metric::<prometheus::IntCounter>(key)
            .and_then(|res| {
                res.map_err(|e| match self.failure_strategy.decide(&e) {
                    failure::Action::NoOp => (),
                    failure::Action::Panic => panic!(
                        "failed to register `prometheus::IntCounter` metric: \
                         {e}",
                    ),
                })
                .ok()
            })
            .map_or_else(metrics::Counter::noop, |m| {
                // TODO: Eliminate this `Arc` allocation via `metrics` PR.
                metrics::Counter::from_arc(Arc::new(m))
            })
    }

    fn register_gauge(&self, key: &metrics::Key) -> metrics::Gauge {
        self.storage
            .get_metric::<prometheus::Gauge>(key)
            .and_then(|res| {
                res.map_err(|e| match self.failure_strategy.decide(&e) {
                    failure::Action::NoOp => (),
                    failure::Action::Panic => panic!(
                        "failed to register `prometheus::Gauge` metric: {e}",
                    ),
                })
                .ok()
            })
            .map_or_else(metrics::Gauge::noop, |m| {
                // TODO: Eliminate this `Arc` allocation via `metrics` PR.
                metrics::Gauge::from_arc(Arc::new(m))
            })
    }

    fn register_histogram(&self, key: &metrics::Key) -> metrics::Histogram {
        self.storage
            .get_metric::<prometheus::Histogram>(key)
            .and_then(|res| {
                res.map_err(|e| match self.failure_strategy.decide(&e) {
                    failure::Action::NoOp => (),
                    failure::Action::Panic => panic!(
                        "failed to register `prometheus::Histogram` metric: \
                         {e}",
                    ),
                })
                .ok()
            })
            .map_or_else(metrics::Histogram::noop, |m| {
                // TODO: Eliminate this `Arc` allocation via `metrics` PR.
                metrics::Histogram::from_arc(Arc::new(m))
            })
    }
}