hyperlane-plugin-metrics 23.4.0

A lock-free atomic Prometheus/OpenMetrics observability plugin for the Hyperlane framework with built-in HTTP request counters, in-flight gauges, latency histograms, custom user metric registration, and a scrapeable /metrics endpoint.
Documentation
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
use super::*;

/// Inherent implementation of [`Counter`].
impl Counter {
    /// Creates a new zero-initialized [`Counter`].
    ///
    /// # Returns
    ///
    /// - `Self` - Counter initialized to `0`.
    pub fn new() -> Self {
        Self {
            value: AtomicU64::new(0),
        }
    }

    /// Increments the counter by `1`.
    #[inline(always)]
    pub fn inc(&self) {
        self.inc_by(1);
    }

    /// Increments the counter by `delta`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Increment amount.
    #[inline(always)]
    pub fn inc_by(&self, delta: u64) {
        let Self { value } = self;
        value.fetch_add(delta, Ordering::Relaxed);
    }

    /// Reads the current counter value.
    ///
    /// # Returns
    ///
    /// - `u64` - Cumulative count.
    #[inline(always)]
    pub fn get(&self) -> u64 {
        let Self { value } = self;
        value.load(Ordering::Relaxed)
    }
}

/// Inherent implementation of [`Gauge`].
impl Gauge {
    /// Creates a new zero-initialized [`Gauge`].
    ///
    /// # Returns
    ///
    /// - `Self` - Gauge initialized to `0`.
    pub fn new() -> Self {
        Self {
            value: AtomicI64::new(0),
        }
    }

    /// Increments the gauge by `1`.
    #[inline(always)]
    pub fn inc(&self) {
        let Self { value } = self;
        value.fetch_add(1, Ordering::Relaxed);
    }

    /// Decrements the gauge by `1`.
    #[inline(always)]
    pub fn dec(&self) {
        let Self { value } = self;
        value.fetch_sub(1, Ordering::Relaxed);
    }

    /// Adds signed `delta` to the gauge.
    ///
    /// # Arguments
    ///
    /// - `i64` - Signed delta.
    #[inline(always)]
    pub fn add(&self, delta: i64) {
        let Self { value } = self;
        value.fetch_add(delta, Ordering::Relaxed);
    }

    /// Overwrites the gauge value atomically.
    ///
    /// # Arguments
    ///
    /// - `i64` - New gauge value.
    #[inline(always)]
    pub fn set(&self, next: i64) {
        let Self { value } = self;
        value.store(next, Ordering::Relaxed);
    }

    /// Reads the current gauge value.
    ///
    /// # Returns
    ///
    /// - `i64` - Current value.
    #[inline(always)]
    pub fn get(&self) -> i64 {
        let Self { value } = self;
        value.load(Ordering::Relaxed)
    }
}

/// Inherent implementation of [`Histogram`].
impl Histogram {
    /// Creates a lock-free [`Histogram`] with the provided upper bucket `bounds`.
    ///
    /// # Arguments
    ///
    /// - `&[f64]` - Finite bucket upper bounds (sorted and deduplicated automatically).
    ///
    /// # Returns
    ///
    /// - `Self` - Ready atomic histogram.
    pub fn new(bounds: &[f64]) -> Self {
        let mut sorted: Vec<f64> = bounds
            .iter()
            .copied()
            .filter(|v: &f64| v.is_finite())
            .collect();
        sorted.sort_by(|a: &f64, b: &f64| a.total_cmp(b));
        sorted.dedup();
        let bound_labels: Vec<String> = sorted.iter().map(|b: &f64| b.to_string()).collect();
        let mut bucket_counts: Vec<AtomicU64> = Vec::with_capacity(sorted.len() + 1);
        for _ in 0..=sorted.len() {
            bucket_counts.push(AtomicU64::new(0));
        }
        Self {
            bounds: sorted.into_boxed_slice(),
            bound_labels: bound_labels.into_boxed_slice(),
            bucket_counts: bucket_counts.into_boxed_slice(),
            total_count: AtomicU64::new(0),
            sum_bits: AtomicU64::new(0.0_f64.to_bits()),
        }
    }

    /// Records a single floating-point observation without locks.
    ///
    /// # Arguments
    ///
    /// - `f64` - Observed value (for example latency in seconds).
    #[inline]
    pub fn observe(&self, sample: f64) {
        if !sample.is_finite() {
            return;
        }
        let Self {
            bounds,
            bucket_counts,
            total_count,
            sum_bits,
            ..
        } = self;
        let idx: usize = if bounds.len() <= LINEAR_SCAN_BUCKET_LIMIT {
            let mut count: usize = 0;
            for &bound in bounds.iter() {
                count += usize::from(bound < sample);
            }
            count
        } else {
            bounds.partition_point(|bound: &f64| *bound < sample)
        };
        bucket_counts[idx].fetch_add(1, Ordering::Relaxed);
        total_count.fetch_add(1, Ordering::Relaxed);
        atomic_f64_add(sum_bits, sample);
    }

    /// Returns total recorded observations.
    ///
    /// # Returns
    ///
    /// - `u64` - Observation count.
    #[inline(always)]
    pub fn count(&self) -> u64 {
        let Self { total_count, .. } = self;
        total_count.load(Ordering::Relaxed)
    }

    /// Returns the cumulative sum of all recorded observations.
    ///
    /// # Returns
    ///
    /// - `f64` - Observation sum.
    #[inline(always)]
    pub fn sum(&self) -> f64 {
        let Self { sum_bits, .. } = self;
        f64::from_bits(sum_bits.load(Ordering::Relaxed))
    }

    /// Appends Prometheus cumulative `_bucket`, `_sum`, and `_count` lines using pre-formatted prefixes.
    ///
    /// # Arguments
    ///
    /// - `&str` - Pre-formatted `# HELP` and `# TYPE` header.
    /// - `&[String]` - Pre-formatted finite bucket line prefixes matching `bucket_counts`.
    /// - `&str` - Pre-formatted `+Inf` bucket line prefix.
    /// - `&str` - Pre-formatted `_sum ` line prefix.
    /// - `&str` - Pre-formatted `_count ` line prefix.
    /// - `&mut String` - Destination Prometheus exposition buffer.
    #[inline]
    pub(crate) fn write_prometheus_preformatted(
        &self,
        header: &str,
        bucket_prefixes: &[String],
        inf_prefix: &str,
        sum_prefix: &str,
        count_prefix: &str,
        out: &mut String,
    ) {
        let Self { bucket_counts, .. } = self;
        out.push_str(header);
        let mut cumulative: u64 = 0;
        let mut num_buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN];
        let mut num_start: usize = INT_STACK_BUF_LEN;
        let mut formatted_val: u64 = 0;
        for (bucket_prefix, bucket_count) in bucket_prefixes.iter().zip(bucket_counts.iter()) {
            cumulative += bucket_count.load(Ordering::Relaxed);
            out.push_str(bucket_prefix);
            if cumulative < 100 {
                out.push_str(PROM_DEC_0_99_NL[cumulative as usize]);
            } else {
                if cumulative != formatted_val {
                    num_start = format_u64_nl_into(cumulative, &mut num_buf);
                    formatted_val = cumulative;
                }
                if let Ok(text) = from_utf8(&num_buf[num_start..]) {
                    out.push_str(text);
                }
            }
        }
        let total: u64 = self.count();
        out.push_str(inf_prefix);
        if total < 100 {
            let total_str: &str = PROM_DEC_0_99_NL[total as usize];
            out.push_str(total_str);
            out.push_str(sum_prefix);
            push_f64_nl(self.sum(), out);
            out.push_str(count_prefix);
            out.push_str(total_str);
        } else {
            if total != formatted_val {
                num_start = format_u64_nl_into(total, &mut num_buf);
            }
            if let Ok(text) = from_utf8(&num_buf[num_start..]) {
                out.push_str(text);
                out.push_str(sum_prefix);
                push_f64_nl(self.sum(), out);
                out.push_str(count_prefix);
                out.push_str(text);
            } else {
                out.push_str(sum_prefix);
                push_f64_nl(self.sum(), out);
                out.push_str(count_prefix);
            }
        }
    }
}

/// Default construction for [`MetricsConfig`].
impl Default for MetricsConfig {
    /// Constructs a default [`MetricsConfig`] exposing `/metrics` under namespace `"hyperlane"`.
    fn default() -> Self {
        Self {
            endpoint: DEFAULT_METRICS_ENDPOINT.to_owned(),
            namespace: DEFAULT_METRICS_NAMESPACE.to_owned(),
            bearer_token: None,
        }
    }
}

/// Inherent builders for [`MetricsConfig`].
impl MetricsConfig {
    /// Sets the scrape endpoint path.
    ///
    /// # Arguments
    ///
    /// - `E` - Path convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_endpoint<E>(mut self, endpoint: E) -> Self
    where
        E: Into<String>,
    {
        self.set_endpoint(endpoint.into());
        self
    }

    /// Sets the metric namespace prefix.
    ///
    /// # Arguments
    ///
    /// - `N` - Namespace convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_namespace<N>(mut self, namespace: N) -> Self
    where
        N: Into<String>,
    {
        self.set_namespace(namespace.into());
        self
    }

    /// Requires `Authorization: Bearer <token>` on `/metrics` scrapes.
    ///
    /// # Arguments
    ///
    /// - `T` - Secret bearer token convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_bearer_token<T>(mut self, token: T) -> Self
    where
        T: Into<String>,
    {
        self.set_bearer_token(Some(token.into()));
        self
    }

    /// Borrows the optional bearer token without cloning.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Borrowed bearer token, if configured.
    #[inline(always)]
    pub(crate) fn get_bearer_token_ref(&self) -> Option<&str> {
        self.bearer_token.as_deref()
    }
}

/// Inherent constructors for [`BuiltinMetricsShard`].
impl BuiltinMetricsShard {
    /// Creates a zero-initialized cache-line-aligned [`BuiltinMetricsShard`].
    ///
    /// # Returns
    ///
    /// - `Self` - Zeroed shard.
    pub(crate) fn new() -> Self {
        Self {
            status_class_counts: from_fn(|_: usize| AtomicU64::new(0)),
            in_flight: AtomicI64::new(0),
            response_bytes_total: AtomicU64::new(0),
            duration_buckets: from_fn(|_: usize| AtomicU64::new(0)),
            duration_count: AtomicU64::new(0),
            duration_nanos_sum: AtomicU64::new(0),
        }
    }
}

/// Default construction for [`MetricsRegistry`].
impl Default for MetricsRegistry {
    /// Constructs a default [`MetricsRegistry`] under namespace `"hyperlane"`.
    fn default() -> Self {
        Self::new(DEFAULT_METRICS_NAMESPACE)
    }
}

/// Inherent implementation of [`MetricsRegistry`].
impl MetricsRegistry {
    /// Creates a new lock-free [`MetricsRegistry`] using `namespace` for built-in HTTP metrics.
    ///
    /// # Arguments
    ///
    /// - `N` - Metric namespace prefix convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready metrics registry.
    pub fn new<N>(namespace: N) -> Self
    where
        N: Into<String>,
    {
        let ns: String = namespace.into();
        let prom_req_header: String = format!(
            "# HELP {ns}_http_requests_total Total HTTP requests partitioned by status class.\n# TYPE {ns}_http_requests_total counter\n"
        );
        let prom_req_lines: [String; 6] = from_fn(|idx: usize| {
            format!(
                "{ns}_http_requests_total{{status_class=\"{}\"}} ",
                STATUS_CLASS_LABELS[idx]
            )
        });
        let prom_in_flight_prefix: String = format!(
            "# 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 "
        );
        let prom_resp_bytes_prefix: String = format!(
            "# 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 "
        );
        let dur_name: String = format!("{ns}_http_request_duration_seconds");
        let prom_dur_header: String =
            format!("# HELP {dur_name} {HELP_HTTP_DURATION}\n# TYPE {dur_name} histogram\n");
        let prom_dur_bucket_prefixes: Box<[String]> = DEFAULT_LATENCY_BUCKETS
            .iter()
            .map(|bound: &f64| format!("{dur_name}_bucket{{le=\"{bound}\"}} "))
            .collect::<Vec<String>>()
            .into_boxed_slice();
        let prom_dur_inf_prefix: String = format!("{dur_name}_bucket{{le=\"+Inf\"}} ");
        let prom_dur_sum_prefix: String = format!("{dur_name}_sum ");
        let prom_dur_count_prefix: String = format!("{dur_name}_count ");
        let mut builtin_est_bytes: usize = prom_req_header.len()
            + prom_in_flight_prefix.len()
            + PROM_EST_DIGITS_PER_LINE
            + prom_resp_bytes_prefix.len()
            + PROM_EST_DIGITS_PER_LINE
            + prom_dur_header.len()
            + prom_dur_inf_prefix.len()
            + PROM_EST_DIGITS_PER_LINE
            + prom_dur_sum_prefix.len()
            + PROM_EST_DIGITS_PER_LINE
            + 8
            + prom_dur_count_prefix.len()
            + PROM_EST_DIGITS_PER_LINE;
        for line_prefix in &prom_req_lines {
            builtin_est_bytes += line_prefix.len() + PROM_EST_DIGITS_PER_LINE;
        }
        for bucket_prefix in prom_dur_bucket_prefixes.iter() {
            builtin_est_bytes += bucket_prefix.len() + PROM_EST_DIGITS_PER_LINE;
        }
        let builtin_shards: Box<[BuiltinMetricsShard; METRICS_SHARD_COUNT]> =
            Box::new(from_fn(|_: usize| BuiltinMetricsShard::new()));
        Self {
            inner: Arc::new(MetricsRegistryInner {
                builtin_est_bytes,
                prom_req_header,
                prom_req_lines,
                prom_in_flight_prefix,
                prom_resp_bytes_prefix,
                prom_dur_header,
                prom_dur_bucket_prefixes,
                prom_dur_inf_prefix,
                prom_dur_sum_prefix,
                prom_dur_count_prefix,
                builtin_shards,
                duration_extra_sum_bits: AtomicU64::new(0.0_f64.to_bits()),
                custom_counter_count: AtomicUsize::new(0),
                custom_gauge_count: AtomicUsize::new(0),
                custom_histogram_count: AtomicUsize::new(0),
                custom_est_bytes: AtomicUsize::new(0),
                custom_counters: RwLock::new(hash_map_xx_hash3_64()),
                custom_gauges: RwLock::new(hash_map_xx_hash3_64()),
                custom_histograms: RwLock::new(hash_map_xx_hash3_64()),
            }),
        }
    }

    /// Registers or retrieves a custom lock-free [`Counter`] handle.
    ///
    /// # Arguments
    ///
    /// - `N` - Metric name.
    /// - `H` - Prometheus `# HELP` description.
    ///
    /// # Returns
    ///
    /// - `Arc<Counter>` - Lock-free counter handle.
    pub fn register_counter<N, H>(&self, name: N, help: H) -> Arc<Counter>
    where
        N: Into<String>,
        H: Into<String>,
    {
        let Self { inner } = self;
        let key: String = name.into();
        if let Ok(read_map) = inner.custom_counters.read()
            && let Some(entry) = read_map.get(&key)
        {
            return Arc::clone(&entry.metric);
        }
        let metric: Arc<Counter> = Arc::new(Counter::new());
        if let Ok(mut write_map) = inner.custom_counters.write() {
            let mut inserted_est: usize = 0;
            let entry: &mut RegisteredCounter = write_map.entry(key.clone()).or_insert_with(|| {
                let help_str: String = help.into();
                let prom_prefix: String =
                    format!("# HELP {key} {help_str}\n# TYPE {key} counter\n{key} ");
                inserted_est = prom_prefix.len() + PROM_EST_DIGITS_PER_LINE;
                RegisteredCounter {
                    prom_prefix,
                    metric: Arc::clone(&metric),
                }
            });
            if inserted_est != 0 {
                inner.custom_counter_count.fetch_add(1, Ordering::Release);
                inner
                    .custom_est_bytes
                    .fetch_add(inserted_est, Ordering::Relaxed);
            }
            return Arc::clone(&entry.metric);
        }
        metric
    }

    /// Registers or retrieves a custom lock-free [`Gauge`] handle.
    ///
    /// # Arguments
    ///
    /// - `N` - Metric name.
    /// - `H` - Prometheus `# HELP` description.
    ///
    /// # Returns
    ///
    /// - `Arc<Gauge>` - Lock-free gauge handle.
    pub fn register_gauge<N, H>(&self, name: N, help: H) -> Arc<Gauge>
    where
        N: Into<String>,
        H: Into<String>,
    {
        let Self { inner } = self;
        let key: String = name.into();
        if let Ok(read_map) = inner.custom_gauges.read()
            && let Some(entry) = read_map.get(&key)
        {
            return Arc::clone(&entry.metric);
        }
        let metric: Arc<Gauge> = Arc::new(Gauge::new());
        if let Ok(mut write_map) = inner.custom_gauges.write() {
            let mut inserted_est: usize = 0;
            let entry: &mut RegisteredGauge = write_map.entry(key.clone()).or_insert_with(|| {
                let help_str: String = help.into();
                let prom_prefix: String =
                    format!("# HELP {key} {help_str}\n# TYPE {key} gauge\n{key} ");
                inserted_est = prom_prefix.len() + PROM_EST_DIGITS_PER_LINE;
                RegisteredGauge {
                    prom_prefix,
                    metric: Arc::clone(&metric),
                }
            });
            if inserted_est != 0 {
                inner.custom_gauge_count.fetch_add(1, Ordering::Release);
                inner
                    .custom_est_bytes
                    .fetch_add(inserted_est, Ordering::Relaxed);
            }
            return Arc::clone(&entry.metric);
        }
        metric
    }

    /// Registers or retrieves a custom lock-free [`Histogram`] handle.
    ///
    /// # Arguments
    ///
    /// - `N` - Metric name.
    /// - `H` - Prometheus `# HELP` description.
    /// - `&[f64]` - Bucket upper bounds.
    ///
    /// # Returns
    ///
    /// - `Arc<Histogram>` - Lock-free histogram handle.
    pub fn register_histogram<N, H>(&self, name: N, help: H, bounds: &[f64]) -> Arc<Histogram>
    where
        N: Into<String>,
        H: Into<String>,
    {
        let Self { inner } = self;
        let key: String = name.into();
        if let Ok(read_map) = inner.custom_histograms.read()
            && let Some(entry) = read_map.get(&key)
        {
            return Arc::clone(&entry.metric);
        }
        let metric: Arc<Histogram> = Arc::new(Histogram::new(bounds));
        if let Ok(mut write_map) = inner.custom_histograms.write() {
            let mut inserted_est: usize = 0;
            let entry: &mut RegisteredHistogram =
                write_map.entry(key.clone()).or_insert_with(|| {
                    let help_str: String = help.into();
                    let prom_header: String =
                        format!("# HELP {key} {help_str}\n# TYPE {key} histogram\n");
                    let prom_bucket_prefixes: Box<[String]> = metric
                        .bound_labels
                        .iter()
                        .map(|label: &String| format!("{key}_bucket{{le=\"{label}\"}} "))
                        .collect::<Vec<String>>()
                        .into_boxed_slice();
                    let prom_inf_prefix: String = format!("{key}_bucket{{le=\"+Inf\"}} ");
                    let prom_sum_prefix: String = format!("{key}_sum ");
                    let prom_count_prefix: String = format!("{key}_count ");
                    let mut est: usize = prom_header.len()
                        + prom_inf_prefix.len()
                        + PROM_EST_DIGITS_PER_LINE
                        + prom_sum_prefix.len()
                        + PROM_EST_DIGITS_PER_LINE
                        + 8
                        + prom_count_prefix.len()
                        + PROM_EST_DIGITS_PER_LINE;
                    for bucket_prefix in prom_bucket_prefixes.iter() {
                        est += bucket_prefix.len() + PROM_EST_DIGITS_PER_LINE;
                    }
                    inserted_est = est;
                    RegisteredHistogram {
                        prom_header,
                        prom_bucket_prefixes,
                        prom_inf_prefix,
                        prom_sum_prefix,
                        prom_count_prefix,
                        metric: Arc::clone(&metric),
                    }
                });
            if inserted_est != 0 {
                inner.custom_histogram_count.fetch_add(1, Ordering::Release);
                inner
                    .custom_est_bytes
                    .fetch_add(inserted_est, Ordering::Relaxed);
            }
            return Arc::clone(&entry.metric);
        }
        metric
    }

    /// Increments the built-in in-flight HTTP request gauge.
    #[inline(always)]
    pub fn record_request_start(&self) {
        let Self { inner } = self;
        inner.builtin_shards[worker_metrics_shard_index()]
            .in_flight
            .fetch_add(1, Ordering::Relaxed);
    }

    /// Records a completed HTTP exchange directly from integer nanoseconds without float or CAS loops.
    ///
    /// # Arguments
    ///
    /// - `usize` - HTTP status code.
    /// - `usize` - Response body length in bytes.
    /// - `u64` - Request duration in integer nanoseconds.
    #[inline]
    pub(crate) fn record_request_finish_nanos(
        &self,
        status_code: usize,
        response_bytes: usize,
        duration_ns: u64,
    ) {
        let Self { inner } = self;
        let shard: &BuiltinMetricsShard = &inner.builtin_shards[worker_metrics_shard_index()];
        shard.in_flight.fetch_sub(1, Ordering::Relaxed);
        let class_idx: usize = match status_code / 100 {
            2 => 1,
            4 => 3,
            3 => 2,
            5 => 4,
            1 => 0,
            _ => 5,
        };
        shard.status_class_counts[class_idx].fetch_add(1, Ordering::Relaxed);
        shard
            .response_bytes_total
            .fetch_add(response_bytes as u64, Ordering::Relaxed);
        let mut bucket_idx: usize = 0;
        for &bound_ns in &DEFAULT_LATENCY_BUCKETS_NS {
            bucket_idx += usize::from(bound_ns < duration_ns);
        }
        shard.duration_buckets[bucket_idx].fetch_add(1, Ordering::Relaxed);
        shard.duration_count.fetch_add(1, Ordering::Relaxed);
        shard
            .duration_nanos_sum
            .fetch_add(duration_ns, Ordering::Relaxed);
    }

    /// Records a completed HTTP exchange in lock-free built-in counters and latency histogram.
    ///
    /// # Arguments
    ///
    /// - `usize` - HTTP status code.
    /// - `usize` - Response body length in bytes.
    /// - `f64` - Request duration in seconds.
    #[inline]
    pub fn record_request_finish(
        &self,
        status_code: usize,
        response_bytes: usize,
        duration_secs: f64,
    ) {
        let Self { inner } = self;
        let shard: &BuiltinMetricsShard = &inner.builtin_shards[worker_metrics_shard_index()];
        shard.in_flight.fetch_sub(1, Ordering::Relaxed);
        let class_idx: usize = match status_code / 100 {
            2 => 1,
            4 => 3,
            3 => 2,
            5 => 4,
            1 => 0,
            _ => 5,
        };
        shard.status_class_counts[class_idx].fetch_add(1, Ordering::Relaxed);
        shard
            .response_bytes_total
            .fetch_add(response_bytes as u64, Ordering::Relaxed);
        if duration_secs.is_finite() {
            let mut bucket_idx: usize = 0;
            for &bound in &DEFAULT_LATENCY_BUCKETS {
                bucket_idx += usize::from(bound < duration_secs);
            }
            shard.duration_buckets[bucket_idx].fetch_add(1, Ordering::Relaxed);
            shard.duration_count.fetch_add(1, Ordering::Relaxed);
            if (0.0..MAX_SHARD_DURATION_SECS).contains(&duration_secs) {
                let nanos: u64 = (duration_secs * NANOS_PER_SEC_F64) as u64;
                shard.duration_nanos_sum.fetch_add(nanos, Ordering::Relaxed);
            } else {
                atomic_f64_add(&inner.duration_extra_sum_bits, duration_secs);
            }
        }
    }

    /// Returns total HTTP requests observed across all status classes.
    ///
    /// # Returns
    ///
    /// - `u64` - Cumulative request count.
    #[inline]
    pub fn total_http_requests(&self) -> u64 {
        let Self { inner } = self;
        let mut total: u64 = 0;
        for shard in inner.builtin_shards.iter() {
            for counter in &shard.status_class_counts {
                total = total.wrapping_add(counter.load(Ordering::Relaxed));
            }
        }
        total
    }

    /// Renders all built-in and custom metrics into Prometheus text exposition format 0.0.4.
    ///
    /// # Returns
    ///
    /// - `String` - Prometheus scrape body.
    pub fn render_prometheus(&self) -> String {
        let Self { inner } = self;
        let capacity: usize =
            inner.builtin_est_bytes + inner.custom_est_bytes.load(Ordering::Relaxed);
        let mut out: String = String::with_capacity(capacity);
        let mut status_totals: [u64; 6] = [0; 6];
        let mut in_flight_total: i64 = 0;
        let mut resp_bytes_total: u64 = 0;
        let mut bucket_totals: [u64; 12] = [0; 12];
        let mut dur_count_total: u64 = 0;
        let mut dur_nanos_total: u128 = 0;
        for shard in inner.builtin_shards.iter() {
            for idx in 0..6 {
                status_totals[idx] = status_totals[idx]
                    .wrapping_add(shard.status_class_counts[idx].load(Ordering::Relaxed));
            }
            in_flight_total = in_flight_total.wrapping_add(shard.in_flight.load(Ordering::Relaxed));
            resp_bytes_total =
                resp_bytes_total.wrapping_add(shard.response_bytes_total.load(Ordering::Relaxed));
            for idx in 0..12 {
                bucket_totals[idx] = bucket_totals[idx]
                    .wrapping_add(shard.duration_buckets[idx].load(Ordering::Relaxed));
            }
            dur_count_total =
                dur_count_total.wrapping_add(shard.duration_count.load(Ordering::Relaxed));
            dur_nanos_total = dur_nanos_total
                .wrapping_add(u128::from(shard.duration_nanos_sum.load(Ordering::Relaxed)));
        }
        let dur_sum_secs: f64 = ((dur_nanos_total as f64) / NANOS_PER_SEC_F64)
            + f64::from_bits(inner.duration_extra_sum_bits.load(Ordering::Relaxed));
        out.push_str(&inner.prom_req_header);
        for (line_prefix, count) in inner.prom_req_lines.iter().zip(status_totals.iter()) {
            out.push_str(line_prefix);
            push_u64_nl(*count, &mut out);
        }
        out.push_str(&inner.prom_in_flight_prefix);
        push_i64_nl(in_flight_total, &mut out);
        out.push_str(&inner.prom_resp_bytes_prefix);
        push_u64_nl(resp_bytes_total, &mut out);
        out.push_str(&inner.prom_dur_header);
        let mut cumulative: u64 = 0;
        let mut num_buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN];
        let mut num_start: usize = INT_STACK_BUF_LEN;
        let mut formatted_val: u64 = 0;
        for (bucket_prefix, bucket_count) in inner
            .prom_dur_bucket_prefixes
            .iter()
            .zip(bucket_totals.iter())
        {
            cumulative = cumulative.wrapping_add(*bucket_count);
            out.push_str(bucket_prefix);
            if cumulative < 100 {
                out.push_str(PROM_DEC_0_99_NL[cumulative as usize]);
            } else {
                if cumulative != formatted_val {
                    num_start = format_u64_nl_into(cumulative, &mut num_buf);
                    formatted_val = cumulative;
                }
                if let Ok(text) = from_utf8(&num_buf[num_start..]) {
                    out.push_str(text);
                }
            }
        }
        out.push_str(&inner.prom_dur_inf_prefix);
        if dur_count_total < 100 {
            let total_str: &str = PROM_DEC_0_99_NL[dur_count_total as usize];
            out.push_str(total_str);
            out.push_str(&inner.prom_dur_sum_prefix);
            push_f64_nl(dur_sum_secs, &mut out);
            out.push_str(&inner.prom_dur_count_prefix);
            out.push_str(total_str);
        } else {
            if dur_count_total != formatted_val {
                num_start = format_u64_nl_into(dur_count_total, &mut num_buf);
            }
            if let Ok(text) = from_utf8(&num_buf[num_start..]) {
                out.push_str(text);
                out.push_str(&inner.prom_dur_sum_prefix);
                push_f64_nl(dur_sum_secs, &mut out);
                out.push_str(&inner.prom_dur_count_prefix);
                out.push_str(text);
            } else {
                out.push_str(&inner.prom_dur_sum_prefix);
                push_f64_nl(dur_sum_secs, &mut out);
                out.push_str(&inner.prom_dur_count_prefix);
            }
        }
        if inner.custom_counter_count.load(Ordering::Acquire) != 0
            && let Ok(counters) = inner.custom_counters.read()
        {
            for entry in counters.values() {
                out.push_str(&entry.prom_prefix);
                push_u64_nl(entry.metric.get(), &mut out);
            }
        }
        if inner.custom_gauge_count.load(Ordering::Acquire) != 0
            && let Ok(gauges) = inner.custom_gauges.read()
        {
            for entry in gauges.values() {
                out.push_str(&entry.prom_prefix);
                push_i64_nl(entry.metric.get(), &mut out);
            }
        }
        if inner.custom_histogram_count.load(Ordering::Acquire) != 0
            && let Ok(histograms) = inner.custom_histograms.read()
        {
            for entry in histograms.values() {
                entry.metric.write_prometheus_preformatted(
                    &entry.prom_header,
                    &entry.prom_bucket_prefixes,
                    &entry.prom_inf_prefix,
                    &entry.prom_sum_prefix,
                    &entry.prom_count_prefix,
                    &mut out,
                );
            }
        }
        out
    }
}

/// Inherent implementation of [`MetricsPlugin`].
impl MetricsPlugin {
    /// Initializes the global [`MetricsPlugin`] once with `config` and an automatically created registry.
    ///
    /// # Arguments
    ///
    /// - `MetricsConfig` - Scrape endpoint, namespace, and optional auth settings.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(config: MetricsConfig) -> &'static Self {
        let registry: MetricsRegistry = MetricsRegistry::new(config.get_namespace().clone());
        Self::init_with_registry(config, registry)
    }

    /// Initializes the global [`MetricsPlugin`] once with `config` and a pre-created [`MetricsRegistry`].
    ///
    /// # Arguments
    ///
    /// - `MetricsConfig` - Scrape endpoint and auth settings.
    /// - `MetricsRegistry` - Shared metrics registry.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init_with_registry(config: MetricsConfig, registry: MetricsRegistry) -> &'static Self {
        METRICS_PLUGIN.get_or_init(|| Self { config, registry })
    }

    /// Returns the initialized global [`MetricsPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        METRICS_PLUGIN.get()
    }

    /// Returns the active [`MetricsConfig`].
    ///
    /// # Returns
    ///
    /// - `&MetricsConfig` - Active metrics configuration.
    #[inline(always)]
    pub fn get_config(&self) -> &MetricsConfig {
        &self.config
    }

    /// Returns the shared lock-free [`MetricsRegistry`].
    ///
    /// # Returns
    ///
    /// - `&MetricsRegistry` - Active metrics registry.
    #[inline(always)]
    pub fn get_registry(&self) -> &MetricsRegistry {
        &self.registry
    }
}

/// Implements [`ServerHook`] for [`MetricsRequestHook`].
impl ServerHook for MetricsRequestHook {
    /// Constructs a per-request [`MetricsRequestHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Synchronously handles normal non-scrape requests and unconfigured pass-through without async futures.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Option<Status>` - `Some(Status::Continue)` for pass-through/normal requests, or `None` for `/metrics` scrapes.
    #[inline(always)]
    fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option<Status> {
        let Some(plugin) = MetricsPlugin::get() else {
            return Some(Status::Continue);
        };
        if ctx.get_request().get_path() == plugin.get_config().get_endpoint() {
            return None;
        }
        plugin.get_registry().record_request_start();
        put_metrics_started_at(ctx, Instant::now());
        Some(Status::Continue)
    }

    /// Answers `/metrics` scrapes or starts request timing and increments in-flight gauge.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` after answering `/metrics`; `Status::Continue` for normal requests.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = MetricsPlugin::get() else {
            return Status::Continue;
        };
        let config: &MetricsConfig = plugin.get_config();
        if ctx.get_request().get_path() == config.get_endpoint() {
            if !is_scrape_authorized(ctx, config.get_bearer_token_ref()) {
                ctx.get_mut_response()
                    .set_status_code(HttpStatus::Unauthorized.code())
                    .set_body(&[] as &[u8]);
            } else {
                let body: Vec<u8> = if ctx.get_request().get_method().is_head() {
                    Vec::new()
                } else {
                    plugin.get_registry().render_prometheus().into_bytes()
                };
                ctx.get_mut_response()
                    .set_status_code(HttpStatus::Ok.code())
                    .set_header(CONTENT_TYPE, PROMETHEUS_CONTENT_TYPE)
                    .set_header(CACHE_CONTROL, CACHE_CONTROL_NO_STORE)
                    .set_body(body);
            }
            let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
            return Status::Reject;
        }
        plugin.get_registry().record_request_start();
        put_metrics_started_at(ctx, Instant::now());
        Status::Continue
    }
}

/// Implements [`ServerHook`] for [`MetricsResponseHook`].
impl ServerHook for MetricsResponseHook {
    /// Constructs a per-response [`MetricsResponseHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Synchronously records HTTP status class, response bytes, and integer-nanosecond latency without async futures.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Option<Status>` - Always `Some(Status::Continue)`.
    #[inline(always)]
    fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option<Status> {
        let Some(plugin) = MetricsPlugin::get() else {
            return Some(Status::Continue);
        };
        let Some(started_at) = get_metrics_started_at(ctx) else {
            return Some(Status::Continue);
        };
        let status: usize = ctx.get_response().get_status_code();
        let bytes: usize = ctx.get_response().get_body().len();
        let duration_ns: u64 = started_at.elapsed().as_nanos().min(u64::MAX as u128) as u64;
        plugin
            .get_registry()
            .record_request_finish_nanos(status, bytes, duration_ns);
        Some(Status::Continue)
    }

    /// Records HTTP status class, response payload bytes, and latency histogram observation.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue)
    }
}