Skip to main content

hyperlane_plugin_metrics/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`Counter`].
4impl Counter {
5    /// Creates a new zero-initialized [`Counter`].
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Counter initialized to `0`.
10    pub fn new() -> Self {
11        Self {
12            value: AtomicU64::new(0),
13        }
14    }
15
16    /// Increments the counter by `1`.
17    #[inline(always)]
18    pub fn inc(&self) {
19        self.inc_by(1);
20    }
21
22    /// Increments the counter by `delta`.
23    ///
24    /// # Arguments
25    ///
26    /// - `u64` - Increment amount.
27    #[inline(always)]
28    pub fn inc_by(&self, delta: u64) {
29        let Self { value } = self;
30        value.fetch_add(delta, Ordering::Relaxed);
31    }
32
33    /// Reads the current counter value.
34    ///
35    /// # Returns
36    ///
37    /// - `u64` - Cumulative count.
38    #[inline(always)]
39    pub fn get(&self) -> u64 {
40        let Self { value } = self;
41        value.load(Ordering::Relaxed)
42    }
43}
44
45/// Inherent implementation of [`Gauge`].
46impl Gauge {
47    /// Creates a new zero-initialized [`Gauge`].
48    ///
49    /// # Returns
50    ///
51    /// - `Self` - Gauge initialized to `0`.
52    pub fn new() -> Self {
53        Self {
54            value: AtomicI64::new(0),
55        }
56    }
57
58    /// Increments the gauge by `1`.
59    #[inline(always)]
60    pub fn inc(&self) {
61        let Self { value } = self;
62        value.fetch_add(1, Ordering::Relaxed);
63    }
64
65    /// Decrements the gauge by `1`.
66    #[inline(always)]
67    pub fn dec(&self) {
68        let Self { value } = self;
69        value.fetch_sub(1, Ordering::Relaxed);
70    }
71
72    /// Adds signed `delta` to the gauge.
73    ///
74    /// # Arguments
75    ///
76    /// - `i64` - Signed delta.
77    #[inline(always)]
78    pub fn add(&self, delta: i64) {
79        let Self { value } = self;
80        value.fetch_add(delta, Ordering::Relaxed);
81    }
82
83    /// Overwrites the gauge value atomically.
84    ///
85    /// # Arguments
86    ///
87    /// - `i64` - New gauge value.
88    #[inline(always)]
89    pub fn set(&self, next: i64) {
90        let Self { value } = self;
91        value.store(next, Ordering::Relaxed);
92    }
93
94    /// Reads the current gauge value.
95    ///
96    /// # Returns
97    ///
98    /// - `i64` - Current value.
99    #[inline(always)]
100    pub fn get(&self) -> i64 {
101        let Self { value } = self;
102        value.load(Ordering::Relaxed)
103    }
104}
105
106/// Inherent implementation of [`Histogram`].
107impl Histogram {
108    /// Creates a lock-free [`Histogram`] with the provided upper bucket `bounds`.
109    ///
110    /// # Arguments
111    ///
112    /// - `&[f64]` - Finite bucket upper bounds (sorted and deduplicated automatically).
113    ///
114    /// # Returns
115    ///
116    /// - `Self` - Ready atomic histogram.
117    pub fn new(bounds: &[f64]) -> Self {
118        let mut sorted: Vec<f64> = bounds
119            .iter()
120            .copied()
121            .filter(|v: &f64| v.is_finite())
122            .collect();
123        sorted.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
124        sorted.dedup();
125        let bound_labels: Vec<String> = sorted.iter().map(|b: &f64| b.to_string()).collect();
126        let mut bucket_counts: Vec<AtomicU64> = Vec::with_capacity(sorted.len() + 1);
127        for _ in 0..=sorted.len() {
128            bucket_counts.push(AtomicU64::new(0));
129        }
130        Self {
131            bounds: sorted.into_boxed_slice(),
132            bound_labels: bound_labels.into_boxed_slice(),
133            bucket_counts: bucket_counts.into_boxed_slice(),
134            total_count: AtomicU64::new(0),
135            sum_bits: AtomicU64::new(0.0_f64.to_bits()),
136        }
137    }
138
139    /// Records a single floating-point observation without locks.
140    ///
141    /// # Arguments
142    ///
143    /// - `f64` - Observed value (for example latency in seconds).
144    #[inline]
145    pub fn observe(&self, sample: f64) {
146        if !sample.is_finite() {
147            return;
148        }
149        let Self {
150            bounds,
151            bucket_counts,
152            total_count,
153            sum_bits,
154            ..
155        } = self;
156        let idx: usize = if bounds.len() <= LINEAR_SCAN_BUCKET_LIMIT {
157            let mut count: usize = 0;
158            for &bound in bounds.iter() {
159                count += usize::from(bound < sample);
160            }
161            count
162        } else {
163            bounds.partition_point(|bound: &f64| *bound < sample)
164        };
165        bucket_counts[idx].fetch_add(1, Ordering::Relaxed);
166        total_count.fetch_add(1, Ordering::Relaxed);
167        atomic_f64_add(sum_bits, sample);
168    }
169
170    /// Returns total recorded observations.
171    ///
172    /// # Returns
173    ///
174    /// - `u64` - Observation count.
175    #[inline(always)]
176    pub fn count(&self) -> u64 {
177        let Self { total_count, .. } = self;
178        total_count.load(Ordering::Relaxed)
179    }
180
181    /// Returns the cumulative sum of all recorded observations.
182    ///
183    /// # Returns
184    ///
185    /// - `f64` - Observation sum.
186    #[inline(always)]
187    pub fn sum(&self) -> f64 {
188        let Self { sum_bits, .. } = self;
189        f64::from_bits(sum_bits.load(Ordering::Relaxed))
190    }
191
192    /// Appends Prometheus cumulative `_bucket`, `_sum`, and `_count` lines using pre-formatted prefixes.
193    ///
194    /// # Arguments
195    ///
196    /// - `&str` - Pre-formatted `# HELP` and `# TYPE` header.
197    /// - `&[String]` - Pre-formatted finite bucket line prefixes matching `bucket_counts`.
198    /// - `&str` - Pre-formatted `+Inf` bucket line prefix.
199    /// - `&str` - Pre-formatted `_sum ` line prefix.
200    /// - `&str` - Pre-formatted `_count ` line prefix.
201    /// - `&mut String` - Destination Prometheus exposition buffer.
202    #[inline]
203    pub(crate) fn write_prometheus_preformatted(
204        &self,
205        header: &str,
206        bucket_prefixes: &[String],
207        inf_prefix: &str,
208        sum_prefix: &str,
209        count_prefix: &str,
210        out: &mut String,
211    ) {
212        let Self { bucket_counts, .. } = self;
213        out.push_str(header);
214        let mut cumulative: u64 = 0;
215        let mut num_buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN];
216        let mut num_start: usize = INT_STACK_BUF_LEN;
217        let mut formatted_val: u64 = 0;
218        for (bucket_prefix, bucket_count) in bucket_prefixes.iter().zip(bucket_counts.iter()) {
219            cumulative += bucket_count.load(Ordering::Relaxed);
220            out.push_str(bucket_prefix);
221            if cumulative < 100 {
222                out.push_str(PROM_DEC_0_99_NL[cumulative as usize]);
223            } else {
224                if cumulative != formatted_val {
225                    num_start = format_u64_nl_into(cumulative, &mut num_buf);
226                    formatted_val = cumulative;
227                }
228                if let Ok(text) = from_utf8(&num_buf[num_start..]) {
229                    out.push_str(text);
230                }
231            }
232        }
233        let total: u64 = self.count();
234        out.push_str(inf_prefix);
235        if total < 100 {
236            let total_str: &str = PROM_DEC_0_99_NL[total as usize];
237            out.push_str(total_str);
238            out.push_str(sum_prefix);
239            push_f64_nl(self.sum(), out);
240            out.push_str(count_prefix);
241            out.push_str(total_str);
242        } else {
243            if total != formatted_val {
244                num_start = format_u64_nl_into(total, &mut num_buf);
245            }
246            if let Ok(text) = from_utf8(&num_buf[num_start..]) {
247                out.push_str(text);
248                out.push_str(sum_prefix);
249                push_f64_nl(self.sum(), out);
250                out.push_str(count_prefix);
251                out.push_str(text);
252            } else {
253                out.push_str(sum_prefix);
254                push_f64_nl(self.sum(), out);
255                out.push_str(count_prefix);
256            }
257        }
258    }
259}
260
261/// Default construction for [`MetricsConfig`].
262impl Default for MetricsConfig {
263    /// Constructs a default [`MetricsConfig`] exposing `/metrics` under namespace `"hyperlane"`.
264    fn default() -> Self {
265        Self {
266            endpoint: DEFAULT_METRICS_ENDPOINT.to_owned(),
267            namespace: DEFAULT_METRICS_NAMESPACE.to_owned(),
268            bearer_token: None,
269        }
270    }
271}
272
273/// Inherent builders for [`MetricsConfig`].
274impl MetricsConfig {
275    /// Sets the scrape endpoint path.
276    ///
277    /// # Arguments
278    ///
279    /// - `E` - Path convertible into `String`.
280    ///
281    /// # Returns
282    ///
283    /// - `Self` - Updated configuration.
284    pub fn with_endpoint<E>(mut self, endpoint: E) -> Self
285    where
286        E: Into<String>,
287    {
288        self.set_endpoint(endpoint.into());
289        self
290    }
291
292    /// Sets the metric namespace prefix.
293    ///
294    /// # Arguments
295    ///
296    /// - `N` - Namespace convertible into `String`.
297    ///
298    /// # Returns
299    ///
300    /// - `Self` - Updated configuration.
301    pub fn with_namespace<N>(mut self, namespace: N) -> Self
302    where
303        N: Into<String>,
304    {
305        self.set_namespace(namespace.into());
306        self
307    }
308
309    /// Requires `Authorization: Bearer <token>` on `/metrics` scrapes.
310    ///
311    /// # Arguments
312    ///
313    /// - `T` - Secret bearer token convertible into `String`.
314    ///
315    /// # Returns
316    ///
317    /// - `Self` - Updated configuration.
318    pub fn with_bearer_token<T>(mut self, token: T) -> Self
319    where
320        T: Into<String>,
321    {
322        self.set_bearer_token(Some(token.into()));
323        self
324    }
325
326    /// Borrows the optional bearer token without cloning.
327    ///
328    /// # Returns
329    ///
330    /// - `Option<&str>` - Borrowed bearer token, if configured.
331    #[inline(always)]
332    pub(crate) fn get_bearer_token_ref(&self) -> Option<&str> {
333        self.bearer_token.as_deref()
334    }
335}
336
337/// Default construction for [`MetricsRegistry`].
338impl Default for MetricsRegistry {
339    /// Constructs a default [`MetricsRegistry`] under namespace `"hyperlane"`.
340    fn default() -> Self {
341        Self::new(DEFAULT_METRICS_NAMESPACE)
342    }
343}
344
345/// Inherent implementation of [`MetricsRegistry`].
346impl MetricsRegistry {
347    /// Creates a new lock-free [`MetricsRegistry`] using `namespace` for built-in HTTP metrics.
348    ///
349    /// # Arguments
350    ///
351    /// - `N` - Metric namespace prefix convertible into `String`.
352    ///
353    /// # Returns
354    ///
355    /// - `Self` - Ready metrics registry.
356    pub fn new<N>(namespace: N) -> Self
357    where
358        N: Into<String>,
359    {
360        let ns: String = namespace.into();
361        let duration_seconds: Histogram = Histogram::new(&DEFAULT_LATENCY_BUCKETS);
362        let prom_req_header: String = format!(
363            "# HELP {ns}_http_requests_total Total HTTP requests partitioned by status class.\n# TYPE {ns}_http_requests_total counter\n"
364        );
365        let prom_req_lines: [String; 6] = from_fn(|idx: usize| {
366            format!(
367                "{ns}_http_requests_total{{status_class=\"{}\"}} ",
368                STATUS_CLASS_LABELS[idx]
369            )
370        });
371        let prom_in_flight_prefix: String = format!(
372            "# HELP {ns}_http_requests_in_flight Current number of active in-flight HTTP requests.\n# TYPE {ns}_http_requests_in_flight gauge\n{ns}_http_requests_in_flight "
373        );
374        let prom_resp_bytes_prefix: String = format!(
375            "# HELP {ns}_http_response_bytes_total Cumulative HTTP response body bytes sent.\n# TYPE {ns}_http_response_bytes_total counter\n{ns}_http_response_bytes_total "
376        );
377        let dur_name: String = format!("{ns}_http_request_duration_seconds");
378        let prom_dur_header: String =
379            format!("# HELP {dur_name} {HELP_HTTP_DURATION}\n# TYPE {dur_name} histogram\n");
380        let prom_dur_bucket_prefixes: Box<[String]> = duration_seconds
381            .bound_labels
382            .iter()
383            .map(|label: &String| format!("{dur_name}_bucket{{le=\"{label}\"}} "))
384            .collect::<Vec<String>>()
385            .into_boxed_slice();
386        let prom_dur_inf_prefix: String = format!("{dur_name}_bucket{{le=\"+Inf\"}} ");
387        let prom_dur_sum_prefix: String = format!("{dur_name}_sum ");
388        let prom_dur_count_prefix: String = format!("{dur_name}_count ");
389        let mut builtin_est_bytes: usize = prom_req_header.len()
390            + prom_in_flight_prefix.len()
391            + PROM_EST_DIGITS_PER_LINE
392            + prom_resp_bytes_prefix.len()
393            + PROM_EST_DIGITS_PER_LINE
394            + prom_dur_header.len()
395            + prom_dur_inf_prefix.len()
396            + PROM_EST_DIGITS_PER_LINE
397            + prom_dur_sum_prefix.len()
398            + PROM_EST_DIGITS_PER_LINE
399            + 8
400            + prom_dur_count_prefix.len()
401            + PROM_EST_DIGITS_PER_LINE;
402        for line_prefix in &prom_req_lines {
403            builtin_est_bytes += line_prefix.len() + PROM_EST_DIGITS_PER_LINE;
404        }
405        for bucket_prefix in prom_dur_bucket_prefixes.iter() {
406            builtin_est_bytes += bucket_prefix.len() + PROM_EST_DIGITS_PER_LINE;
407        }
408        Self {
409            inner: Arc::new(MetricsRegistryInner {
410                builtin_est_bytes,
411                prom_req_header,
412                prom_req_lines,
413                prom_in_flight_prefix,
414                prom_resp_bytes_prefix,
415                prom_dur_header,
416                prom_dur_bucket_prefixes,
417                prom_dur_inf_prefix,
418                prom_dur_sum_prefix,
419                prom_dur_count_prefix,
420                status_class_counts: [
421                    Counter::new(),
422                    Counter::new(),
423                    Counter::new(),
424                    Counter::new(),
425                    Counter::new(),
426                    Counter::new(),
427                ],
428                in_flight: Gauge::new(),
429                response_bytes_total: Counter::new(),
430                duration_seconds,
431                custom_counter_count: AtomicUsize::new(0),
432                custom_gauge_count: AtomicUsize::new(0),
433                custom_histogram_count: AtomicUsize::new(0),
434                custom_est_bytes: AtomicUsize::new(0),
435                custom_counters: RwLock::new(hash_map_xx_hash3_64()),
436                custom_gauges: RwLock::new(hash_map_xx_hash3_64()),
437                custom_histograms: RwLock::new(hash_map_xx_hash3_64()),
438            }),
439        }
440    }
441
442    /// Registers or retrieves a custom lock-free [`Counter`] handle.
443    ///
444    /// # Arguments
445    ///
446    /// - `N` - Metric name.
447    /// - `H` - Prometheus `# HELP` description.
448    ///
449    /// # Returns
450    ///
451    /// - `Arc<Counter>` - Lock-free counter handle.
452    pub fn register_counter<N, H>(&self, name: N, help: H) -> Arc<Counter>
453    where
454        N: Into<String>,
455        H: Into<String>,
456    {
457        let Self { inner } = self;
458        let key: String = name.into();
459        if let Ok(read_map) = inner.custom_counters.read()
460            && let Some(entry) = read_map.get(&key)
461        {
462            return Arc::clone(&entry.metric);
463        }
464        let metric: Arc<Counter> = Arc::new(Counter::new());
465        if let Ok(mut write_map) = inner.custom_counters.write() {
466            let mut inserted_est: usize = 0;
467            let entry: &mut RegisteredCounter = write_map.entry(key.clone()).or_insert_with(|| {
468                let help_str: String = help.into();
469                let prom_prefix: String =
470                    format!("# HELP {key} {help_str}\n# TYPE {key} counter\n{key} ");
471                inserted_est = prom_prefix.len() + PROM_EST_DIGITS_PER_LINE;
472                RegisteredCounter {
473                    prom_prefix,
474                    metric: Arc::clone(&metric),
475                }
476            });
477            if inserted_est != 0 {
478                inner.custom_counter_count.fetch_add(1, Ordering::Release);
479                inner
480                    .custom_est_bytes
481                    .fetch_add(inserted_est, Ordering::Relaxed);
482            }
483            return Arc::clone(&entry.metric);
484        }
485        metric
486    }
487
488    /// Registers or retrieves a custom lock-free [`Gauge`] handle.
489    ///
490    /// # Arguments
491    ///
492    /// - `N` - Metric name.
493    /// - `H` - Prometheus `# HELP` description.
494    ///
495    /// # Returns
496    ///
497    /// - `Arc<Gauge>` - Lock-free gauge handle.
498    pub fn register_gauge<N, H>(&self, name: N, help: H) -> Arc<Gauge>
499    where
500        N: Into<String>,
501        H: Into<String>,
502    {
503        let Self { inner } = self;
504        let key: String = name.into();
505        if let Ok(read_map) = inner.custom_gauges.read()
506            && let Some(entry) = read_map.get(&key)
507        {
508            return Arc::clone(&entry.metric);
509        }
510        let metric: Arc<Gauge> = Arc::new(Gauge::new());
511        if let Ok(mut write_map) = inner.custom_gauges.write() {
512            let mut inserted_est: usize = 0;
513            let entry: &mut RegisteredGauge = write_map.entry(key.clone()).or_insert_with(|| {
514                let help_str: String = help.into();
515                let prom_prefix: String =
516                    format!("# HELP {key} {help_str}\n# TYPE {key} gauge\n{key} ");
517                inserted_est = prom_prefix.len() + PROM_EST_DIGITS_PER_LINE;
518                RegisteredGauge {
519                    prom_prefix,
520                    metric: Arc::clone(&metric),
521                }
522            });
523            if inserted_est != 0 {
524                inner.custom_gauge_count.fetch_add(1, Ordering::Release);
525                inner
526                    .custom_est_bytes
527                    .fetch_add(inserted_est, Ordering::Relaxed);
528            }
529            return Arc::clone(&entry.metric);
530        }
531        metric
532    }
533
534    /// Registers or retrieves a custom lock-free [`Histogram`] handle.
535    ///
536    /// # Arguments
537    ///
538    /// - `N` - Metric name.
539    /// - `H` - Prometheus `# HELP` description.
540    /// - `&[f64]` - Bucket upper bounds.
541    ///
542    /// # Returns
543    ///
544    /// - `Arc<Histogram>` - Lock-free histogram handle.
545    pub fn register_histogram<N, H>(&self, name: N, help: H, bounds: &[f64]) -> Arc<Histogram>
546    where
547        N: Into<String>,
548        H: Into<String>,
549    {
550        let Self { inner } = self;
551        let key: String = name.into();
552        if let Ok(read_map) = inner.custom_histograms.read()
553            && let Some(entry) = read_map.get(&key)
554        {
555            return Arc::clone(&entry.metric);
556        }
557        let metric: Arc<Histogram> = Arc::new(Histogram::new(bounds));
558        if let Ok(mut write_map) = inner.custom_histograms.write() {
559            let mut inserted_est: usize = 0;
560            let entry: &mut RegisteredHistogram =
561                write_map.entry(key.clone()).or_insert_with(|| {
562                    let help_str: String = help.into();
563                    let prom_header: String =
564                        format!("# HELP {key} {help_str}\n# TYPE {key} histogram\n");
565                    let prom_bucket_prefixes: Box<[String]> = metric
566                        .bound_labels
567                        .iter()
568                        .map(|label: &String| format!("{key}_bucket{{le=\"{label}\"}} "))
569                        .collect::<Vec<String>>()
570                        .into_boxed_slice();
571                    let prom_inf_prefix: String = format!("{key}_bucket{{le=\"+Inf\"}} ");
572                    let prom_sum_prefix: String = format!("{key}_sum ");
573                    let prom_count_prefix: String = format!("{key}_count ");
574                    let mut est: usize = prom_header.len()
575                        + prom_inf_prefix.len()
576                        + PROM_EST_DIGITS_PER_LINE
577                        + prom_sum_prefix.len()
578                        + PROM_EST_DIGITS_PER_LINE
579                        + 8
580                        + prom_count_prefix.len()
581                        + PROM_EST_DIGITS_PER_LINE;
582                    for bucket_prefix in prom_bucket_prefixes.iter() {
583                        est += bucket_prefix.len() + PROM_EST_DIGITS_PER_LINE;
584                    }
585                    inserted_est = est;
586                    RegisteredHistogram {
587                        prom_header,
588                        prom_bucket_prefixes,
589                        prom_inf_prefix,
590                        prom_sum_prefix,
591                        prom_count_prefix,
592                        metric: Arc::clone(&metric),
593                    }
594                });
595            if inserted_est != 0 {
596                inner.custom_histogram_count.fetch_add(1, Ordering::Release);
597                inner
598                    .custom_est_bytes
599                    .fetch_add(inserted_est, Ordering::Relaxed);
600            }
601            return Arc::clone(&entry.metric);
602        }
603        metric
604    }
605
606    /// Increments the built-in in-flight HTTP request gauge.
607    #[inline(always)]
608    pub fn record_request_start(&self) {
609        let Self { inner } = self;
610        inner.in_flight.inc();
611    }
612
613    /// Records a completed HTTP exchange in lock-free built-in counters and latency histogram.
614    ///
615    /// # Arguments
616    ///
617    /// - `usize` - HTTP status code.
618    /// - `usize` - Response body length in bytes.
619    /// - `f64` - Request duration in seconds.
620    #[inline]
621    pub fn record_request_finish(
622        &self,
623        status_code: usize,
624        response_bytes: usize,
625        duration_secs: f64,
626    ) {
627        let Self { inner } = self;
628        inner.in_flight.dec();
629        let class_idx: usize = match status_code / 100 {
630            2 => 1,
631            4 => 3,
632            3 => 2,
633            5 => 4,
634            1 => 0,
635            _ => 5,
636        };
637        inner.status_class_counts[class_idx].inc();
638        inner.response_bytes_total.inc_by(response_bytes as u64);
639        inner.duration_seconds.observe(duration_secs);
640    }
641
642    /// Returns total HTTP requests observed across all status classes.
643    ///
644    /// # Returns
645    ///
646    /// - `u64` - Cumulative request count.
647    #[inline]
648    pub fn total_http_requests(&self) -> u64 {
649        let Self { inner } = self;
650        inner.status_class_counts.iter().map(Counter::get).sum()
651    }
652
653    /// Renders all built-in and custom metrics into Prometheus text exposition format 0.0.4.
654    ///
655    /// # Returns
656    ///
657    /// - `String` - Prometheus scrape body.
658    pub fn render_prometheus(&self) -> String {
659        let Self { inner } = self;
660        let capacity: usize =
661            inner.builtin_est_bytes + inner.custom_est_bytes.load(Ordering::Relaxed);
662        let mut out: String = String::with_capacity(capacity);
663        out.push_str(&inner.prom_req_header);
664        for (line_prefix, counter) in inner
665            .prom_req_lines
666            .iter()
667            .zip(inner.status_class_counts.iter())
668        {
669            out.push_str(line_prefix);
670            push_u64_nl(counter.get(), &mut out);
671        }
672        out.push_str(&inner.prom_in_flight_prefix);
673        push_i64_nl(inner.in_flight.get(), &mut out);
674        out.push_str(&inner.prom_resp_bytes_prefix);
675        push_u64_nl(inner.response_bytes_total.get(), &mut out);
676        inner.duration_seconds.write_prometheus_preformatted(
677            &inner.prom_dur_header,
678            &inner.prom_dur_bucket_prefixes,
679            &inner.prom_dur_inf_prefix,
680            &inner.prom_dur_sum_prefix,
681            &inner.prom_dur_count_prefix,
682            &mut out,
683        );
684        if inner.custom_counter_count.load(Ordering::Acquire) != 0
685            && let Ok(counters) = inner.custom_counters.read()
686        {
687            for entry in counters.values() {
688                out.push_str(&entry.prom_prefix);
689                push_u64_nl(entry.metric.get(), &mut out);
690            }
691        }
692        if inner.custom_gauge_count.load(Ordering::Acquire) != 0
693            && let Ok(gauges) = inner.custom_gauges.read()
694        {
695            for entry in gauges.values() {
696                out.push_str(&entry.prom_prefix);
697                push_i64_nl(entry.metric.get(), &mut out);
698            }
699        }
700        if inner.custom_histogram_count.load(Ordering::Acquire) != 0
701            && let Ok(histograms) = inner.custom_histograms.read()
702        {
703            for entry in histograms.values() {
704                entry.metric.write_prometheus_preformatted(
705                    &entry.prom_header,
706                    &entry.prom_bucket_prefixes,
707                    &entry.prom_inf_prefix,
708                    &entry.prom_sum_prefix,
709                    &entry.prom_count_prefix,
710                    &mut out,
711                );
712            }
713        }
714        out
715    }
716}
717
718/// Inherent implementation of [`MetricsPlugin`].
719impl MetricsPlugin {
720    /// Initializes the global [`MetricsPlugin`] once with `config` and an automatically created registry.
721    ///
722    /// # Arguments
723    ///
724    /// - `MetricsConfig` - Scrape endpoint, namespace, and optional auth settings.
725    ///
726    /// # Returns
727    ///
728    /// - `&'static Self` - Reference to the initialized global plugin.
729    pub fn init(config: MetricsConfig) -> &'static Self {
730        let registry: MetricsRegistry = MetricsRegistry::new(config.get_namespace().clone());
731        Self::init_with_registry(config, registry)
732    }
733
734    /// Initializes the global [`MetricsPlugin`] once with `config` and a pre-created [`MetricsRegistry`].
735    ///
736    /// # Arguments
737    ///
738    /// - `MetricsConfig` - Scrape endpoint and auth settings.
739    /// - `MetricsRegistry` - Shared metrics registry.
740    ///
741    /// # Returns
742    ///
743    /// - `&'static Self` - Reference to the initialized global plugin.
744    pub fn init_with_registry(config: MetricsConfig, registry: MetricsRegistry) -> &'static Self {
745        METRICS_PLUGIN.get_or_init(|| Self { config, registry })
746    }
747
748    /// Returns the initialized global [`MetricsPlugin`], if initialized.
749    ///
750    /// # Returns
751    ///
752    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
753    #[inline(always)]
754    pub fn get() -> Option<&'static Self> {
755        METRICS_PLUGIN.get()
756    }
757
758    /// Returns the active [`MetricsConfig`].
759    ///
760    /// # Returns
761    ///
762    /// - `&MetricsConfig` - Active metrics configuration.
763    #[inline(always)]
764    pub fn get_config(&self) -> &MetricsConfig {
765        &self.config
766    }
767
768    /// Returns the shared lock-free [`MetricsRegistry`].
769    ///
770    /// # Returns
771    ///
772    /// - `&MetricsRegistry` - Active metrics registry.
773    #[inline(always)]
774    pub fn get_registry(&self) -> &MetricsRegistry {
775        &self.registry
776    }
777}
778
779/// Implements [`ServerHook`] for [`MetricsRequestHook`].
780impl ServerHook for MetricsRequestHook {
781    /// Constructs a per-request [`MetricsRequestHook`].
782    ///
783    /// # Arguments
784    ///
785    /// - `&mut Stream` - Connection stream.
786    /// - `&mut Context` - Request context.
787    ///
788    /// # Returns
789    ///
790    /// - `Self` - Hook instance.
791    #[inline(always)]
792    async fn new(_: &mut Stream, _: &mut Context) -> Self {
793        Self
794    }
795
796    /// Answers `/metrics` scrapes or starts request timing and increments in-flight gauge.
797    ///
798    /// # Arguments
799    ///
800    /// - `Self` - Hook instance.
801    /// - `&mut Stream` - Connection stream.
802    /// - `&mut Context` - Request context.
803    ///
804    /// # Returns
805    ///
806    /// - `Status` - `Status::Reject` after answering `/metrics`; `Status::Continue` for normal requests.
807    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
808        let Some(plugin) = MetricsPlugin::get() else {
809            return Status::Continue;
810        };
811        let config: &MetricsConfig = plugin.get_config();
812        if ctx.get_request().get_path() == config.get_endpoint() {
813            if !is_scrape_authorized(ctx, config.get_bearer_token_ref()) {
814                ctx.get_mut_response()
815                    .set_status_code(HttpStatus::Unauthorized.code())
816                    .set_body(&[] as &[u8]);
817            } else {
818                let body: Vec<u8> = if ctx.get_request().get_method().is_head() {
819                    Vec::new()
820                } else {
821                    plugin.get_registry().render_prometheus().into_bytes()
822                };
823                ctx.get_mut_response()
824                    .set_status_code(HttpStatus::Ok.code())
825                    .set_header(CONTENT_TYPE, PROMETHEUS_CONTENT_TYPE)
826                    .set_header(CACHE_CONTROL, CACHE_CONTROL_NO_STORE)
827                    .set_body(body);
828            }
829            let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
830            return Status::Reject;
831        }
832        plugin.get_registry().record_request_start();
833        ctx.set_attribute(ATTR_METRICS_STARTED_AT, Instant::now());
834        Status::Continue
835    }
836}
837
838/// Implements [`ServerHook`] for [`MetricsResponseHook`].
839impl ServerHook for MetricsResponseHook {
840    /// Constructs a per-response [`MetricsResponseHook`].
841    ///
842    /// # Arguments
843    ///
844    /// - `&mut Stream` - Connection stream.
845    /// - `&mut Context` - Request context.
846    ///
847    /// # Returns
848    ///
849    /// - `Self` - Hook instance.
850    #[inline(always)]
851    async fn new(_: &mut Stream, _: &mut Context) -> Self {
852        Self
853    }
854
855    /// Records HTTP status class, response payload bytes, and latency histogram observation.
856    ///
857    /// # Arguments
858    ///
859    /// - `Self` - Hook instance.
860    /// - `&mut Stream` - Connection stream.
861    /// - `&mut Context` - Request context.
862    ///
863    /// # Returns
864    ///
865    /// - `Status` - Always `Status::Continue`.
866    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
867        let Some(plugin) = MetricsPlugin::get() else {
868            return Status::Continue;
869        };
870        let Some(started_at) = ctx.try_get_attribute_ref::<Instant, _>(ATTR_METRICS_STARTED_AT)
871        else {
872            return Status::Continue;
873        };
874        let status: usize = ctx.get_response().get_status_code();
875        let bytes: usize = ctx.get_response().get_body().len();
876        let duration_secs: f64 = started_at.elapsed().as_secs_f64();
877        plugin
878            .get_registry()
879            .record_request_finish(status, bytes, duration_secs);
880        Status::Continue
881    }
882}