footing 0.1.13

Feature-gated foundations for Rust backend services
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
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
//! Metric samples, registry, snapshots, and OpenMetrics export.

use std::{
    collections::BTreeMap,
    convert::Infallible,
    fmt::{self, Write},
    sync::Mutex,
};

use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeStruct};
use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};

/// Maximum supported normalized metric name length.
pub const MAX_METRIC_NAME_LENGTH: usize = 128;
/// Maximum number of labels on one metric series.
pub const MAX_METRIC_LABELS: usize = 16;
/// Maximum supported normalized metric label key length.
pub const MAX_METRIC_LABEL_KEY_LENGTH: usize = 64;
/// Maximum supported metric label value length.
pub const MAX_METRIC_LABEL_VALUE_LENGTH: usize = 256;
/// Default maximum number of series retained by one registry.
pub const DEFAULT_MAX_METRIC_SERIES: usize = 10_000;
/// Default maximum number of series retained for one metric name.
pub const DEFAULT_MAX_METRIC_SERIES_PER_METRIC: usize = 1_000;
/// Default finite histogram bounds, suited to durations expressed in seconds.
pub const DEFAULT_HISTOGRAM_BUCKETS: &[f64] = &[
    0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];
/// Maximum finite buckets retained for one histogram series.
pub const MAX_HISTOGRAM_BUCKETS: usize = 128;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Classification of metric.
pub enum MetricKind {
    /// Indicates counter.
    Counter,
    /// Indicates gauge.
    Gauge,
    /// Indicates histogram.
    Histogram,
}

#[derive(Clone, PartialEq)]
#[non_exhaustive]
/// Represents metric sample.
pub struct MetricSample {
    name: String,
    kind: MetricKind,
    value: f64,
    labels: Vec<(String, String)>,
    count: Option<u64>,
    buckets: Vec<(f64, u64)>,
}

impl Serialize for MetricSample {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Binary structs need every field; JSON omits non-histogram fields.
        let include_count = !serializer.is_human_readable() || self.count.is_some();
        let include_buckets = !serializer.is_human_readable() || !self.buckets.is_empty();
        let mut sample = serializer.serialize_struct(
            "MetricSample",
            4 + usize::from(include_count) + usize::from(include_buckets),
        )?;
        sample.serialize_field("name", &self.name)?;
        sample.serialize_field("kind", &self.kind)?;
        sample.serialize_field("value", &self.value)?;
        sample.serialize_field("labels", &self.labels)?;
        if include_count {
            sample.serialize_field("count", &self.count)?;
        }
        if include_buckets {
            sample.serialize_field("buckets", &self.buckets)?;
        }
        sample.end()
    }
}

impl fmt::Debug for MetricSample {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MetricSample")
            .field("name", &self.name)
            .field("kind", &self.kind)
            .field("value", &self.value)
            .field("label_count", &self.labels.len())
            .field("count", &self.count)
            .finish()
    }
}

impl MetricSample {
    /// Creates a counter or gauge; counters must be nonnegative and all values finite.
    /// Histogram input is rejected here: use [`Self::histogram`] to supply its
    /// count, sum, and buckets together.
    pub fn new(
        name: impl Into<String>,
        kind: MetricKind,
        value: f64,
    ) -> Result<Self, MetricsError> {
        if kind == MetricKind::Histogram {
            return Err(MetricsError::InvalidHistogram);
        }
        validate_metric_kind_value(kind, value)?;
        let name = normalize_metric_name(name, kind)?;
        Ok(Self::from_valid_parts(name, kind, value))
    }

    fn from_valid_parts(name: String, kind: MetricKind, value: f64) -> Self {
        Self {
            name,
            kind,
            value,
            labels: Vec::new(),
            count: None,
            buckets: Vec::new(),
        }
    }

    /// Creates counter.
    pub fn counter(name: impl Into<String>, value: u64) -> Result<Self, MetricsError> {
        let name = normalize_metric_name(name, MetricKind::Counter)?;
        Ok(Self::from_valid_parts(
            name,
            MetricKind::Counter,
            value as f64,
        ))
    }

    /// Creates gauge.
    pub fn gauge(name: impl Into<String>, value: f64) -> Result<Self, MetricsError> {
        Self::new(name, MetricKind::Gauge, value)
    }

    /// Creates a histogram from its count, sum, and cumulative finite buckets.
    /// Bounds must be finite, nonnegative, and strictly increasing. Counts must
    /// be nondecreasing and must not exceed the total count. The exporter adds
    /// the implicit `+Inf` bucket with the total count.
    pub fn histogram(
        name: impl Into<String>,
        count: u64,
        sum: f64,
        buckets: Vec<(f64, u64)>,
    ) -> Result<Self, MetricsError> {
        validate_metric_kind_value(MetricKind::Histogram, sum)?;
        validate_histogram_buckets(buckets.iter().map(|(bound, _)| *bound))?;
        if (count == 0 && sum != 0.0)
            || buckets.iter().any(|(_, value)| *value > count)
            || buckets.windows(2).any(|pair| pair[0].1 > pair[1].1)
        {
            return Err(MetricsError::InvalidHistogram);
        }
        let mut sample = Self::from_valid_parts(
            normalize_metric_name(name, MetricKind::Histogram)?,
            MetricKind::Histogram,
            sum,
        );
        sample.count = Some(count);
        sample.buckets = buckets;
        Ok(sample)
    }

    #[must_use]
    /// Adds a label, dropping invalid labels and histogram-reserved `le` labels.
    /// Use [`Self::try_with_label`] to report invalid input instead.
    pub fn with_label(mut self, key: &'static str, value: impl Into<String>) -> Self {
        let _ = self.insert_label(key.to_owned(), value.into());
        self
    }

    /// Attempts to append a normalized metric label.
    pub fn try_with_label(
        mut self,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, MetricsError> {
        self.insert_label(key.into(), value.into())?;
        Ok(self)
    }

    fn insert_label(&mut self, key: String, value: String) -> Result<(), MetricsError> {
        let key = normalize_metric_label_key(key)?;
        let value = normalize_metric_label_value(value)?;
        if self.kind == MetricKind::Histogram && key == "le" {
            return Err(MetricsError::ReservedHistogramLabel);
        }
        match self
            .labels
            .binary_search_by(|(existing, _)| existing.cmp(&key))
        {
            Ok(index) => self.labels[index].1 = value,
            Err(index) => {
                if self.labels.len() >= MAX_METRIC_LABELS {
                    return Err(MetricsError::TooManyLabels {
                        max: MAX_METRIC_LABELS,
                    });
                }
                self.labels.insert(index, (key, value));
            }
        }
        Ok(())
    }

    #[must_use]
    /// Replaces labels, dropping the reserved `le` label for histograms.
    /// Use [`Self::try_with_labels`] to reject incompatible labels instead.
    pub fn with_labels(mut self, labels: MetricLabels) -> Self {
        self.labels = labels.into_vec();
        if self.kind == MetricKind::Histogram {
            self.labels.retain(|(key, _)| key != "le");
        }
        self
    }

    /// Replaces labels after validating restrictions imposed by the metric type.
    pub fn try_with_labels(mut self, labels: MetricLabels) -> Result<Self, MetricsError> {
        validate_metric_kind_labels(self.kind, &labels)?;
        self.labels = labels.into_vec();
        Ok(self)
    }

    #[must_use]
    /// Returns cumulative counts for the finite histogram bounds.
    pub fn buckets(&self) -> &[(f64, u64)] {
        &self.buckets
    }

    #[must_use]
    /// Returns the name.
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    /// Returns the kind.
    pub const fn kind(&self) -> MetricKind {
        self.kind
    }

    #[must_use]
    /// Returns the value.
    pub const fn value(&self) -> f64 {
        self.value
    }

    #[must_use]
    /// Returns the count.
    pub const fn count(&self) -> Option<u64> {
        self.count
    }

    #[must_use]
    /// Returns the labels.
    pub fn labels(&self) -> &[(String, String)] {
        &self.labels
    }
}

impl<'de> Deserialize<'de> for MetricSample {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct MetricSampleWire {
            name: String,
            kind: MetricKind,
            value: f64,
            #[serde(default)]
            labels: MetricLabels,
            #[serde(default)]
            count: Option<u64>,
            #[serde(default)]
            buckets: Vec<(f64, u64)>,
        }

        let wire = MetricSampleWire::deserialize(deserializer)?;
        let sample = match (wire.kind, wire.count) {
            (MetricKind::Histogram, Some(count)) => {
                Self::histogram(wire.name, count, wire.value, wire.buckets)
            }
            (MetricKind::Histogram, None) => Err(MetricsError::InvalidHistogram),
            (_, None) if wire.buckets.is_empty() => Self::new(wire.name, wire.kind, wire.value),
            _ => Err(MetricsError::InvalidHistogram),
        }
        .map_err(serde::de::Error::custom)?;
        sample
            .try_with_labels(wire.labels)
            .map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
/// Represents metric labels.
pub struct MetricLabels(Vec<(String, String)>);

impl fmt::Debug for MetricLabels {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MetricLabels")
            .field("label_count", &self.0.len())
            .finish_non_exhaustive()
    }
}

impl MetricLabels {
    /// Creates a new instance.
    pub fn new(
        labels: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Result<Self, MetricsError> {
        let mut normalized = BTreeMap::<String, String>::new();
        for (index, (key, value)) in labels.into_iter().enumerate() {
            if index >= MAX_METRIC_LABELS {
                return Err(MetricsError::TooManyLabels {
                    max: MAX_METRIC_LABELS,
                });
            }
            let key = normalize_metric_label_key(key)?;
            let value = normalize_metric_label_value(value)?;
            normalized.insert(key, value);
        }
        Ok(Self(normalized.into_iter().collect()))
    }

    #[must_use]
    /// Creates a value from lossy.
    pub fn from_lossy(
        labels: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        let mut normalized = BTreeMap::<String, String>::new();
        for (key, value) in labels.into_iter().take(MAX_METRIC_LABELS) {
            if let (Ok(key), Ok(value)) = (
                normalize_metric_label_key(key),
                normalize_metric_label_value(value),
            ) {
                normalized.insert(key, value);
            }
        }
        Self(normalized.into_iter().collect())
    }

    /// Creates single.
    pub fn single(key: impl Into<String>, value: impl Into<String>) -> Result<Self, MetricsError> {
        Self::new([(key, value)])
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    #[must_use]
    /// Returns this value as slice.
    pub fn as_slice(&self) -> &[(String, String)] {
        &self.0
    }

    #[must_use]
    /// Returns the metric label value associated with a key.
    pub fn get(&self, key: &str) -> Option<&str> {
        let key = normalize_metric_label_key(key).ok()?;
        self.0
            .iter()
            .find(|(name, _)| name == &key)
            .map(|(_, value)| value.as_str())
    }

    #[must_use]
    /// Converts this value to btree map.
    pub fn to_btree_map(&self) -> BTreeMap<String, String> {
        self.0.iter().cloned().collect()
    }

    #[must_use]
    /// Consumes this value and returns vec.
    pub fn into_vec(self) -> Vec<(String, String)> {
        self.0
    }
}

impl<'de> Deserialize<'de> for MetricLabels {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(Vec::<(String, String)>::deserialize(deserializer)?)
            .map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// Immutable snapshot of metrics.
/// Serializes as an object with a `samples` array.
pub struct MetricsSnapshot {
    samples: Vec<MetricSample>,
}

impl fmt::Debug for MetricsSnapshot {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MetricsSnapshot")
            .field("sample_count", &self.samples.len())
            .finish_non_exhaustive()
    }
}

impl MetricsSnapshot {
    #[must_use]
    /// Creates a new instance.
    pub fn new(samples: Vec<MetricSample>) -> Self {
        Self { samples }
    }

    /// Appends a sample; callers assembling snapshots must avoid family conflicts.
    pub fn push(&mut self, sample: MetricSample) {
        self.samples.push(sample);
    }

    #[must_use]
    /// Returns the samples.
    pub fn samples(&self) -> &[MetricSample] {
        &self.samples
    }
}

/// Defines the contract for metric recorder.
pub trait MetricRecorder: Send + Sync + 'static {
    /// Increments counter.
    fn increment_counter(
        &self,
        name: &str,
        value: u64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError>;

    /// Sets gauge.
    fn set_gauge(&self, name: &str, value: f64, labels: MetricLabels) -> Result<(), MetricsError>;

    /// Records an observation for histogram.
    fn observe_histogram(
        &self,
        name: &str,
        value: f64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError>;

    /// Returns an immutable snapshot.
    fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError>;
}

/// Cardinality limits applied to a metric registry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct MetricRegistryLimits {
    max_series: usize,
    max_series_per_metric: usize,
}

impl MetricRegistryLimits {
    /// Creates validated registry limits.
    pub const fn new(
        max_series: usize,
        max_series_per_metric: usize,
    ) -> Result<Self, MetricsError> {
        if max_series == 0 || max_series_per_metric == 0 || max_series_per_metric > max_series {
            return Err(MetricsError::InvalidRegistryLimits);
        }
        Ok(Self {
            max_series,
            max_series_per_metric,
        })
    }

    /// Returns the total series limit.
    #[must_use]
    pub const fn max_series(self) -> usize {
        self.max_series
    }

    /// Returns the per-metric series limit.
    #[must_use]
    pub const fn max_series_per_metric(self) -> usize {
        self.max_series_per_metric
    }
}

impl Default for MetricRegistryLimits {
    fn default() -> Self {
        Self {
            max_series: DEFAULT_MAX_METRIC_SERIES,
            max_series_per_metric: DEFAULT_MAX_METRIC_SERIES_PER_METRIC,
        }
    }
}

#[non_exhaustive]
/// Bounded registry that reserves each metric family and its sample names.
///
/// A name has one type across all label sets. Registration rejects names that
/// collide with another family's generated suffixes. Counter aliases such as
/// `jobs` and `jobs_total` must not be registered as separate metrics.
pub struct MetricRegistry {
    state: Mutex<MetricRegistryState>,
    limits: MetricRegistryLimits,
    histogram_buckets: BTreeMap<String, Vec<f64>>,
}

impl Default for MetricRegistry {
    fn default() -> Self {
        Self {
            state: Mutex::new(MetricRegistryState::default()),
            limits: MetricRegistryLimits::default(),
            histogram_buckets: BTreeMap::new(),
        }
    }
}

impl fmt::Debug for MetricRegistry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MetricRegistry")
            .field(
                "metric_count",
                &self.state.try_lock().ok().map(|state| state.values.len()),
            )
            .field("limits", &self.limits)
            .finish_non_exhaustive()
    }
}

impl MetricRegistry {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a registry with explicit validated cardinality limits.
    #[must_use]
    pub fn with_limits(limits: MetricRegistryLimits) -> Self {
        Self {
            state: Mutex::new(MetricRegistryState::default()),
            limits,
            histogram_buckets: BTreeMap::new(),
        }
    }

    /// Configures finite buckets for a metric before its first observation.
    /// Unconfigured histograms use [`DEFAULT_HISTOGRAM_BUCKETS`]. Boundaries
    /// cannot change after observations, even for a different label set.
    pub fn with_histogram_buckets(
        mut self,
        name: &str,
        bounds: Vec<f64>,
    ) -> Result<Self, MetricsError> {
        validate_histogram_buckets(bounds.iter().copied())?;
        let name = normalize_metric_name(name, MetricKind::Histogram)?;
        let state = self
            .state
            .get_mut()
            .map_err(|_| MetricsError::LockPoisoned)?;
        if state.series_per_metric.contains_key(&name) {
            return Err(MetricsError::HistogramAlreadyObserved);
        }
        if !self.histogram_buckets.contains_key(&name)
            && self.histogram_buckets.len() >= self.limits.max_series
        {
            return Err(MetricsError::RegistrySeriesLimitExceeded {
                max: self.limits.max_series,
            });
        }
        self.histogram_buckets.insert(name, bounds);
        Ok(self)
    }

    /// Returns this registry's cardinality limits.
    #[must_use]
    pub const fn limits(&self) -> MetricRegistryLimits {
        self.limits
    }

    /// Increments counter.
    pub fn increment_counter(
        &self,
        name: &str,
        value: u64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError> {
        MetricRecorder::increment_counter(self, name, value, labels)
    }

    /// Sets gauge.
    pub fn set_gauge(
        &self,
        name: &str,
        value: f64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError> {
        MetricRecorder::set_gauge(self, name, value, labels)
    }

    /// Records an observation for histogram.
    pub fn observe_histogram(
        &self,
        name: &str,
        value: f64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError> {
        MetricRecorder::observe_histogram(self, name, value, labels)
    }

    /// Returns an immutable snapshot.
    pub fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
        MetricRecorder::snapshot(self)
    }
}

impl MetricRecorder for MetricRegistry {
    fn increment_counter(
        &self,
        name: &str,
        value: u64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError> {
        let identity = MetricIdentity::new(name, MetricKind::Counter, labels)?;
        let mut state = self.state.lock().map_err(|_| MetricsError::LockPoisoned)?;
        if let Some(aggregate) = state.values.get_mut(&identity) {
            aggregate.value = finite_metric_sum(aggregate.value, value as f64)?;
        } else {
            state.insert_new(
                identity,
                MetricAggregate {
                    value: value as f64,
                    count: None,
                    buckets: Vec::new(),
                },
                self.limits,
            )?;
        }
        Ok(())
    }

    fn set_gauge(&self, name: &str, value: f64, labels: MetricLabels) -> Result<(), MetricsError> {
        validate_metric_value(value)?;
        let identity = MetricIdentity::new(name, MetricKind::Gauge, labels)?;
        let mut state = self.state.lock().map_err(|_| MetricsError::LockPoisoned)?;
        if let Some(aggregate) = state.values.get_mut(&identity) {
            *aggregate = MetricAggregate {
                value,
                count: None,
                buckets: Vec::new(),
            };
        } else {
            state.insert_new(
                identity,
                MetricAggregate {
                    value,
                    count: None,
                    buckets: Vec::new(),
                },
                self.limits,
            )?;
        }
        Ok(())
    }

    fn observe_histogram(
        &self,
        name: &str,
        value: f64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError> {
        validate_metric_kind_value(MetricKind::Histogram, value)?;
        let identity = MetricIdentity::new(name, MetricKind::Histogram, labels)?;
        let mut state = self.state.lock().map_err(|_| MetricsError::LockPoisoned)?;
        if let Some(aggregate) = state.values.get_mut(&identity) {
            let sum = finite_metric_sum(aggregate.value, value)?;
            let count = aggregate
                .count
                .unwrap_or_default()
                .checked_add(1)
                .ok_or(MetricsError::CountOverflow)?;
            aggregate.value = sum;
            aggregate.count = Some(count);
            for (bound, bucket_count) in &mut aggregate.buckets {
                if value <= *bound {
                    *bucket_count += 1;
                }
            }
        } else {
            let buckets = self
                .histogram_buckets
                .get(&identity.name)
                .map(Vec::as_slice)
                .unwrap_or(DEFAULT_HISTOGRAM_BUCKETS)
                .iter()
                .map(|bound| (*bound, u64::from(value <= *bound)))
                .collect();
            state.insert_new(
                identity,
                MetricAggregate {
                    value,
                    count: Some(1),
                    buckets,
                },
                self.limits,
            )?;
        }
        Ok(())
    }

    fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
        let state = self.state.lock().map_err(|_| MetricsError::LockPoisoned)?;
        let samples = state
            .values
            .iter()
            .map(|(identity, aggregate)| MetricSample {
                name: identity.name.clone(),
                kind: identity.kind,
                value: aggregate.value,
                count: aggregate.count,
                buckets: aggregate.buckets.clone(),
                labels: identity.labels.clone().into_vec(),
            })
            .collect();
        Ok(MetricsSnapshot::new(samples))
    }
}

fn finite_metric_sum(left: f64, right: f64) -> Result<f64, MetricsError> {
    let sum = left + right;
    validate_metric_value(sum)?;
    Ok(sum)
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct MetricIdentity {
    name: String,
    kind: MetricKind,
    labels: MetricLabels,
}

impl MetricIdentity {
    fn new(
        name: impl Into<String>,
        kind: MetricKind,
        labels: MetricLabels,
    ) -> Result<Self, MetricsError> {
        validate_metric_kind_labels(kind, &labels)?;
        Ok(Self {
            name: normalize_metric_name(name, kind)?,
            kind,
            labels,
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
struct MetricAggregate {
    value: f64,
    count: Option<u64>,
    buckets: Vec<(f64, u64)>,
}

#[derive(Default)]
struct MetricRegistryState {
    values: BTreeMap<MetricIdentity, MetricAggregate>,
    series_per_metric: BTreeMap<String, usize>,
    // Reserve family and generated sample names, including optional suffixes.
    exported_names: BTreeMap<String, (String, MetricKind)>,
}

impl MetricRegistryState {
    fn insert_new(
        &mut self,
        identity: MetricIdentity,
        aggregate: MetricAggregate,
        limits: MetricRegistryLimits,
    ) -> Result<(), MetricsError> {
        let names = exported_metric_names(&identity.name, identity.kind);
        for name in &names {
            if let Some((owner, kind)) = self.exported_names.get(name) {
                if owner == &identity.name && *kind != identity.kind {
                    return Err(MetricsError::MetricTypeConflict);
                }
                if owner != &identity.name {
                    return Err(MetricsError::MetricNameConflict);
                }
            }
        }
        if self.values.len() >= limits.max_series {
            return Err(MetricsError::RegistrySeriesLimitExceeded {
                max: limits.max_series,
            });
        }
        let metric_series = self
            .series_per_metric
            .get(&identity.name)
            .copied()
            .unwrap_or_default();
        if metric_series >= limits.max_series_per_metric {
            return Err(MetricsError::MetricSeriesLimitExceeded {
                max: limits.max_series_per_metric,
            });
        }

        let metric_name = identity.name.clone();
        for name in names {
            self.exported_names
                .insert(name, (metric_name.clone(), identity.kind));
        }
        self.values.insert(identity, aggregate);
        self.series_per_metric
            .insert(metric_name, metric_series.saturating_add(1));
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling metrics.
pub enum MetricsError {
    #[error(
        "histogram bounds must be nonempty, finite, nonnegative, strictly increasing, and within the bucket limit"
    )]
    /// Histogram boundaries are invalid.
    InvalidHistogramBuckets,
    #[error("histogram count, sum, or cumulative bucket counts are inconsistent")]
    /// The sample does not contain a valid histogram distribution.
    InvalidHistogram,
    #[error("histogram bounds cannot change after observations")]
    /// A metric has already been recorded with this name.
    HistogramAlreadyObserved,
    #[error("histogram observation count overflowed")]
    /// No further observations can be represented.
    CountOverflow,
    #[error("histogram labels must not contain the reserved 'le' label")]
    /// Bucket thresholds are generated by the exporter, not supplied by callers.
    ReservedHistogramLabel,
    #[error("counter and histogram values must not be negative")]
    /// A cumulative metric cannot record a negative value.
    NegativeValue,
    #[error("metric name is already registered with a different type")]
    /// A metric name must have one type across all label sets.
    MetricTypeConflict,
    #[error("metric name conflicts with another exported metric family or sample")]
    /// A family or generated sample name is already reserved by another metric.
    MetricNameConflict,
    #[error("metrics registry lock is poisoned")]
    /// Indicates lock poisoned.
    LockPoisoned,
    #[error("metric name must not be empty")]
    /// The name is invalid.
    InvalidName,
    #[error("metric name must be less than or equal to {max} bytes")]
    /// The normalized metric name exceeds the supported length.
    NameTooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("metric must contain at most {max} labels")]
    /// A metric contains too many labels.
    TooManyLabels {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("metric label key must not be empty")]
    /// A metric label key is invalid.
    InvalidLabelKey,
    #[error("metric label key must be less than or equal to {max} bytes")]
    /// A normalized metric label key exceeds the supported length.
    LabelKeyTooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("metric label value must not contain control characters")]
    /// A metric label value is invalid.
    InvalidLabelValue,
    #[error("metric label value must be less than or equal to {max} bytes")]
    /// A metric label value exceeds the supported length.
    LabelValueTooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("metric value must be finite")]
    /// The value is invalid.
    InvalidValue,
    #[error(
        "metric registry limits must be non-zero and the per-metric limit must not exceed the total limit"
    )]
    /// Registry cardinality limits are invalid.
    InvalidRegistryLimits,
    #[error("metric registry series limit of {max} was exceeded")]
    /// The total registry cardinality limit was reached.
    RegistrySeriesLimitExceeded {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("per-metric series limit of {max} was exceeded")]
    /// The per-metric cardinality limit was reached.
    MetricSeriesLimitExceeded {
        #[doc = "The configured upper bound."]
        max: usize,
    },
}

impl ClassifyError for MetricsError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::LockPoisoned => ErrorKind::Unavailable,
            Self::InvalidHistogramBuckets
            | Self::InvalidHistogram
            | Self::HistogramAlreadyObserved
            | Self::CountOverflow
            | Self::InvalidName
            | Self::ReservedHistogramLabel
            | Self::NegativeValue
            | Self::MetricTypeConflict
            | Self::MetricNameConflict
            | Self::NameTooLong { .. }
            | Self::TooManyLabels { .. }
            | Self::InvalidLabelKey
            | Self::LabelKeyTooLong { .. }
            | Self::InvalidLabelValue
            | Self::LabelValueTooLong { .. }
            | Self::InvalidValue
            | Self::InvalidRegistryLimits
            | Self::RegistrySeriesLimitExceeded { .. }
            | Self::MetricSeriesLimitExceeded { .. } => ErrorKind::Validation,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidHistogramBuckets => "metric_histogram_buckets_invalid",
            Self::InvalidHistogram => "metric_histogram_invalid",
            Self::HistogramAlreadyObserved => "metric_histogram_already_observed",
            Self::CountOverflow => "metric_count_overflow",
            Self::ReservedHistogramLabel => "metric_histogram_label_reserved",
            Self::NegativeValue => "metric_value_negative",
            Self::MetricTypeConflict => "metric_type_conflict",
            Self::MetricNameConflict => "metric_name_conflict",
            Self::LockPoisoned => "metrics_registry_unavailable",
            Self::InvalidName => "metric_name_invalid",
            Self::NameTooLong { .. } => "metric_name_too_long",
            Self::TooManyLabels { .. } => "metric_labels_too_many",
            Self::InvalidLabelKey => "metric_label_key_invalid",
            Self::LabelKeyTooLong { .. } => "metric_label_key_too_long",
            Self::InvalidLabelValue => "metric_label_value_invalid",
            Self::LabelValueTooLong { .. } => "metric_label_value_too_long",
            Self::InvalidValue => "metric_value_invalid",
            Self::InvalidRegistryLimits => "metrics_registry_limits_invalid",
            Self::RegistrySeriesLimitExceeded { .. } => "metrics_registry_series_limit_exceeded",
            Self::MetricSeriesLimitExceeded { .. } => "metric_series_limit_exceeded",
        })
    }
}

fn validate_histogram_buckets(bounds: impl Iterator<Item = f64>) -> Result<(), MetricsError> {
    let mut previous = None;
    let mut count = 0;
    for bound in bounds {
        count += 1;
        if count > MAX_HISTOGRAM_BUCKETS
            || !bound.is_finite()
            || bound < 0.0
            || previous.is_some_and(|last| bound <= last)
        {
            return Err(MetricsError::InvalidHistogramBuckets);
        }
        previous = Some(bound);
    }
    if count == 0 {
        return Err(MetricsError::InvalidHistogramBuckets);
    }
    Ok(())
}

fn validate_metric_kind_value(kind: MetricKind, value: f64) -> Result<(), MetricsError> {
    validate_metric_value(value)?;
    if kind != MetricKind::Gauge && value < 0.0 {
        return Err(MetricsError::NegativeValue);
    }
    Ok(())
}

fn validate_metric_kind_labels(
    kind: MetricKind,
    labels: &MetricLabels,
) -> Result<(), MetricsError> {
    if kind == MetricKind::Histogram && labels.get("le").is_some() {
        return Err(MetricsError::ReservedHistogramLabel);
    }
    Ok(())
}

fn metric_family_name(name: &str, kind: MetricKind) -> &str {
    if kind == MetricKind::Counter {
        name.strip_suffix("_total").unwrap_or(name)
    } else {
        name
    }
}

fn exported_metric_names(name: &str, kind: MetricKind) -> Vec<String> {
    let family = metric_family_name(name, kind);
    let suffixes: &[&str] = match kind {
        MetricKind::Counter => &["", "_total", "_created"],
        MetricKind::Gauge => &[""],
        MetricKind::Histogram => &["", "_sum", "_count", "_bucket", "_created"],
    };
    suffixes
        .iter()
        .map(|suffix| format!("{family}{suffix}"))
        .collect()
}

#[must_use]
/// Encodes OpenMetrics 1.0, grouping samples by family.
///
/// Counter names may include `_total`; the suffix belongs to the sample, not
/// the family declaration. Histograms expose cumulative finite and `+Inf` buckets.
/// Manually assembled snapshots must use consistent, nonconflicting metric
/// families; use [`MetricRegistry`] to check names during registration and
/// [`MetricSample::histogram`] to supply both histogram count and sum.
pub fn encode_openmetrics(snapshot: &MetricsSnapshot) -> String {
    let mut output = String::new();
    let mut previous_family = None;

    let mut samples: Vec<_> = snapshot.samples().iter().collect();
    samples.sort_by_key(|sample| metric_family_name(sample.name(), sample.kind()));
    for sample in samples {
        let name = sample.name();
        let family = metric_family_name(name, sample.kind());
        if previous_family != Some(family) {
            let _ = writeln!(
                output,
                "# TYPE {family} {}",
                openmetrics_kind(sample.kind())
            );
            previous_family = Some(family);
        }

        let labels = sample.labels();
        let value = if sample.value().is_finite() {
            sample.value()
        } else {
            0.0
        };
        match (sample.kind(), sample.count()) {
            (MetricKind::Histogram, Some(count)) => {
                for (bound, bucket_count) in sample.buckets() {
                    write_sample(
                        &mut output,
                        name,
                        "_bucket",
                        labels,
                        bucket_count,
                        Some(*bound),
                    );
                }
                write_sample(
                    &mut output,
                    name,
                    "_bucket",
                    labels,
                    count,
                    Some(f64::INFINITY),
                );
                write_sample(&mut output, name, "_sum", labels, value, None);
                write_sample(&mut output, name, "_count", labels, count, None);
            }
            _ => {
                let suffix = if sample.kind() == MetricKind::Counter {
                    "_total"
                } else {
                    ""
                };
                write_sample(&mut output, family, suffix, labels, value, None);
            }
        }
    }

    output.push_str("# EOF\n");
    output
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents metrics export.
pub struct MetricsExport {
    content_type: String,
    body: String,
}

impl fmt::Debug for MetricsExport {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MetricsExport")
            .field("content_type", &self.content_type)
            .field("body_bytes", &self.body.len())
            .finish()
    }
}

impl MetricsExport {
    #[must_use]
    /// Creates a new instance.
    pub fn new(content_type: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            content_type: content_type.into(),
            body: body.into(),
        }
    }

    #[must_use]
    /// Returns the content type.
    pub fn content_type(&self) -> &str {
        &self.content_type
    }

    #[must_use]
    /// Returns the body.
    pub fn body(&self) -> &str {
        &self.body
    }

    #[must_use]
    /// Consumes this value and returns body.
    pub fn into_body(self) -> String {
        self.body
    }
}

/// Defines the contract for metrics exporter.
pub trait MetricsExporter {
    /// Type used for error.
    type Error;

    /// Exports the value.
    fn export(&self, snapshot: &MetricsSnapshot) -> Result<MetricsExport, Self::Error>;
}

#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
/// Represents open metrics exporter.
pub struct OpenMetricsExporter;

impl OpenMetricsExporter {
    /// Content type.
    pub const CONTENT_TYPE: &'static str =
        "application/openmetrics-text; version=1.0.0; charset=utf-8";
}

impl MetricsExporter for OpenMetricsExporter {
    type Error = Infallible;

    fn export(&self, snapshot: &MetricsSnapshot) -> Result<MetricsExport, Self::Error> {
        Ok(MetricsExport::new(
            Self::CONTENT_TYPE,
            encode_openmetrics(snapshot),
        ))
    }
}

fn normalize_metric_name(
    value: impl Into<String>,
    kind: MetricKind,
) -> Result<String, MetricsError> {
    let value = value.into();
    let value = value.trim();
    if value.is_empty() {
        return Err(MetricsError::InvalidName);
    }
    if value.len() > MAX_METRIC_NAME_LENGTH {
        return Err(MetricsError::NameTooLong {
            max: MAX_METRIC_NAME_LENGTH,
        });
    }
    let mut normalized = String::with_capacity(value.len().max(1));
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || byte == b':' || byte == b'_' {
            normalized.push(char::from(byte));
        } else {
            normalized.push('_');
        }
    }
    if normalized.as_bytes().first().is_none_or(u8::is_ascii_digit) {
        normalized.insert(0, '_');
    }
    if normalized.len() > MAX_METRIC_NAME_LENGTH {
        return Err(MetricsError::NameTooLong {
            max: MAX_METRIC_NAME_LENGTH,
        });
    }
    if metric_family_name(&normalized, kind).is_empty() {
        return Err(MetricsError::InvalidName);
    }
    Ok(normalized)
}

fn normalize_metric_label_key(value: impl Into<String>) -> Result<String, MetricsError> {
    let value = value.into();
    let value = value.trim();
    if value.is_empty() {
        return Err(MetricsError::InvalidLabelKey);
    }
    if value.len() > MAX_METRIC_LABEL_KEY_LENGTH {
        return Err(MetricsError::LabelKeyTooLong {
            max: MAX_METRIC_LABEL_KEY_LENGTH,
        });
    }

    let mut normalized = String::with_capacity(value.len().max(1));
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || byte == b'_' {
            normalized.push(char::from(byte));
        } else {
            normalized.push('_');
        }
    }
    if normalized.as_bytes().first().is_none_or(u8::is_ascii_digit) {
        normalized.insert(0, '_');
    }
    if normalized.len() > MAX_METRIC_LABEL_KEY_LENGTH {
        return Err(MetricsError::LabelKeyTooLong {
            max: MAX_METRIC_LABEL_KEY_LENGTH,
        });
    }
    Ok(normalized)
}

fn normalize_metric_label_value(value: impl Into<String>) -> Result<String, MetricsError> {
    let value = value.into();
    if value.len() > MAX_METRIC_LABEL_VALUE_LENGTH {
        return Err(MetricsError::LabelValueTooLong {
            max: MAX_METRIC_LABEL_VALUE_LENGTH,
        });
    }
    if value.chars().any(char::is_control) {
        return Err(MetricsError::InvalidLabelValue);
    }
    Ok(value)
}

fn validate_metric_value(value: f64) -> Result<(), MetricsError> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(MetricsError::InvalidValue)
    }
}

fn openmetrics_kind(kind: MetricKind) -> &'static str {
    match kind {
        MetricKind::Counter => "counter",
        MetricKind::Gauge => "gauge",
        MetricKind::Histogram => "histogram",
    }
}

fn write_sample(
    output: &mut String,
    name: &str,
    suffix: &str,
    labels: &[(String, String)],
    value: impl fmt::Display,
    bound: Option<f64>,
) {
    output.push_str(name);
    output.push_str(suffix);
    write_labels(output, labels, bound);
    let _ = writeln!(output, " {value}");
}

fn write_labels(output: &mut String, labels: &[(String, String)], bound: Option<f64>) {
    if labels.is_empty() && bound.is_none() {
        return;
    }

    output.push('{');
    for (index, (key, value)) in labels.iter().enumerate() {
        if index > 0 {
            output.push(',');
        }
        output.push_str(key);
        output.push_str("=\"");
        for character in value.chars() {
            match character {
                '\\' => output.push_str("\\\\"),
                '"' => output.push_str("\\\""),
                '\n' => output.push_str("\\n"),
                _ => output.push(character),
            }
        }
        output.push('"');
    }
    if let Some(bound) = bound {
        if !labels.is_empty() {
            output.push(',');
        }
        if bound == f64::INFINITY {
            output.push_str("le=\"+Inf\"");
        } else {
            let _ = write!(output, "le=\"{bound}\"");
        }
    }
    output.push('}');
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn histogram_count_overflow_leaves_sum_and_buckets_unchanged() {
        let registry = MetricRegistry::new();
        registry
            .observe_histogram("latency", 0.0, MetricLabels::default())
            .unwrap();
        {
            let mut state = registry.state.lock().unwrap();
            let aggregate = state.values.values_mut().next().unwrap();
            aggregate.count = Some(u64::MAX);
            aggregate
                .buckets
                .iter_mut()
                .for_each(|(_, count)| *count = u64::MAX);
        }
        let before = registry.snapshot().unwrap();
        assert_eq!(
            registry.observe_histogram("latency", 1.0, MetricLabels::default()),
            Err(MetricsError::CountOverflow)
        );
        assert_eq!(registry.snapshot().unwrap(), before);
    }
}